ysyt-agent-sdk 1.0.12 → 1.0.13

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,4 +1,4 @@
1
- import e from"crypto";import t from"buffer";class s extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class i extends s{constructor(e){super(e||"Unsupported content type.")}}class r extends s{constructor(e){super(e||"Request pending.")}}class n extends s{constructor(e){super(e||"Unspecified session description handler error.")}}class o extends s{constructor(){super("The session has terminated.")}}class a extends s{constructor(e){super(e||"An error occurred during state transition.")}}class c{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class h{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class d{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class l{constructor(){this.listeners=new Array}addListener(e,t){const s=t=>{this.removeListener(s),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class g{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class u{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class p extends u{constructor(e,t,s){super(s),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new p(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class f extends u{constructor(e="sip",t,s,i,r,n){if(super(r||{}),this.headers={},!s)throw new TypeError('missing or invalid "host" parameter');for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:s,port:i},this.normal={scheme:e.toLowerCase(),user:t,host:s.toLowerCase(),port:i}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new f(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const s=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&s.push(e+"="+this.headers[e][t]);return s.length>0&&(t+="?"+s.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e<i;e++)0!==e&&(r+="-"),r+=s[e].charAt(0).toUpperCase()+s[e].substring(1);return t[r]&&(r=t[r]),r}}function m(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){const s=Object.keys(e.parameters),i=Object.keys(t.parameters),r=s.filter(e=>i.includes(e));return!!r.every(s=>e.parameters[s]===t.parameters[s])&&(!!["user","ttl","method","transport"].every(s=>e.hasParam(s)&&t.hasParam(s)||!e.hasParam(s)&&!t.hasParam(s))&&!!["maddr"].every(s=>e.hasParam(s)&&t.hasParam(s)||!e.hasParam(s)&&!t.hasParam(s)))}(e,t))return!1;const s=Object.keys(e.headers),i=Object.keys(t.headers);if(0!==s.length||0!==i.length){if(s.length!==i.length)return!1;const r=s.filter(e=>i.includes(e));if(r.length!==i.length)return!1;if(!r.every(s=>e.headers[s].length&&t.headers[s].length&&e.headers[s][0]===t.headers[s][0]))return!1}return!0}function v(e,t,s){return s=s||" ",e.length>t?e:(t-=e.length,e+(s+=s.repeat(t)).slice(0,t))}class w extends Error{constructor(e,t,s,i){super(),this.message=e,this.expected=t,this.found=s,this.location=i,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,w.prototype):this.__proto__=w.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,w)}static buildMessage(e,t){function s(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,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(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,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function n(e){switch(e.type){case"literal":return'"'+i(e.text)+'"';case"class":const t=e.parts.map(e=>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){const t=e.map(n);let s,i;if(t.sort(),t.length>0){for(s=1,i=1;s<t.length;s++)t[s-1]!==t[s]&&(t[i]=t[s],i++);t.length=i}switch(t.length){case 1:return t[0];case 2:return t[0]+" or "+t[1];default:return t.slice(0,-1).join(", ")+", or "+t[t.length-1]}}(e)+" but "+(((o=t)?'"'+i(o)+'"':"end of input")+" found.");var o}format(e){let t="Error: "+this.message;if(this.location){let s,i=null;for(s=0;s<e.length;s++)if(e[s].source===this.location.source){i=e[s].text.split(/\r\n|\n|\r/g);break}let r=this.location.start,n=this.location.source+":"+r.line+":"+r.column;if(i){let e=this.location.end,s=v("",r.line.toString().length," "),o=i[r.line-1],a=r.line===e.line?e.column:o.length+1;t+="\n --\x3e "+n+"\n"+s+" |\n"+r.line+" | "+o+"\n"+s+" | "+v("",r.column-1," ")+v("",a-r.column,"^")}else t+="\n at "+n}return t}}const y=function(e,t){const s={},i=(t=void 0!==t?t:{}).grammarSource,r={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231};let n=119;const o=["\r\n",b("\r\n",!1),/^[0-9]/,T([["0","9"]],!1,!1),/^[a-zA-Z]/,T([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,T([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,T([["\0","ÿ"]],!1,!1),/^["]/,T(['"'],!1,!1)," ",b(" ",!1),"\t",b("\t",!1),/^[a-zA-Z0-9]/,T([["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":"},/^[!-~]/,T([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,T([["€","￿"]],!1,!1),/^[\x80-\xBF]/,T([["€","¿"]],!1,!1),/^[a-f]/,T([["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'"'},/^[!-']/,T([["!","'"]],!1,!1),/^[*-[]/,T([["*","["]],!1,!1),/^[\]-~]/,T([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,T([["#","["]],!1,!1),/^[\0-\t]/,T([["\0","\t"]],!1,!1),/^[\v-\f]/,T([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,T([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new f(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 f(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_\-]/,T([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,T([["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]/,T([["0","5"]],!1,!1),"2",b("2",!1),/^[0-4]/,T([["0","4"]],!1,!1),"1",b("1",!1),/^[1-9]/,T([["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,s){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),s=null===s?void 0:s[1],t.data.uri_params[e.toLowerCase()]=s},function(e,s){e=e.join("").toLowerCase(),s=s.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(s):t.data.uri_headers[e]=[s]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new f(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,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e<s;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 p(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:c,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,s){(t=t||{data:{}}).data.params||(t.data.params={}),s=null===s?void 0:s[1],t.data.params[e.toLowerCase()]=s},"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 p(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 p(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,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e<s;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 p(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:c,offset:y().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new p(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 p(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)],a=[A('2 ""6 7!'),A('4"""5!7#'),A('4$""5!7%'),A('4&""5!7\''),A(";'.# &;("),A('4(""5!7)'),A('4*""5!7+'),A('2,""6,7-'),A('2.""6.7/'),A('40""5!71'),A('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'),A(";).# &;,"),A('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),A('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),A('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),A(';.." &"'),A("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),A('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),A('4\\""5!7].# &;3'),A('4^""5!7_'),A('4`""5!7a'),A(';!.) &4b""5!7c'),A('%$;).• &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&&&#/"!&,)'),A('%$;).‰ &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&&&#/"!&,)'),A('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.) &;\'.# &;('),A('%$;).ī &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&&&#/"!&,)'),A("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),A("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),A("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),A("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),A("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),A('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),A('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),A("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),A("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),A("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),A("%;//0#;&/'$8\":~\" )(\"'#&'#"),A("%;&/0#;//'$8\":~\" )(\"'#&'#"),A("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),A('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),A("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),A("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),A(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),A('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),A("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),A("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),A('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),A('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),A("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),A('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'),A('%$;+._ &;-.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!:–! )'),A('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),A("%;U.) &;\\.# &;X/& 8!:—! )"),A('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),A('$4™""5!7š/,#0)*4™""5!7š&&&#'),A('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),A('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),A('%%;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!: ! )'),A('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),A("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),A("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),A('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),A('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),A('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),A(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),A('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),A('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),A('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),A('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),A('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),A('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),A('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),A('%$;j/&#0#*;j&&&#/"!&,)'),A('%$;j/&#0#*;j&&&#/"!&,)'),A(";k.) &;+.# &;-"),A('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),A('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),A('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),A("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),A("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),A('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),A(";‘.# &;r"),A("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),A(";M.# &;t"),A("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),A('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),A('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),A('%24""6475/,#;{/#$+")("\'#&\'#'),A("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),A(";*.) &;+.# &;-"),A(';+. &;-.‰ &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'),A('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),A('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),A("$;~0#*;~&"),A(';+.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'),A('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),A(";.# &;‚"),A('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),A('$;+.ƒ &;-.} &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&&&#'),A("$;y0#*;y&"),A('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),A('2Õ""6Õ7Ö'),A('2×""6×7Ø'),A('2Ù""6Ù7Ú'),A('2Û""6Û7Ü'),A('2Ý""6Ý7Þ'),A('2ß""6ß7à'),A('2á""6á7â'),A('2ã""6ã7ä'),A('2å""6å7æ'),A('2ç""6ç7è'),A('2é""6é7ê'),A("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),A("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),A("%;“/' 8!:ì!! )"),A("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),A("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),A("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),A("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),A("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),A("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),A("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),A(";œ.) &;.# &; "),A("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),A("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),A('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),A('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),A(";6.) &;T.# &;H"),A("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),A(";¥.# &; "),A('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),A("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),A("%;©/& 8!:č! )"),A("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),A(";«.# &;¬"),A('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),A('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),A(";6.# &;®"),A('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),A(";­.# &;6"),A("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),A(";6.# &;H"),A("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),A("%;ž/' 8!:ğ!! )"),A('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),A('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),A("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),A(";¹.# &; "),A("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),A("%;ž/' 8!:Ħ!! )"),A("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),A(";¾"),A("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),A("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),A("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),A(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),A("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),A("%;I/' 8!:Ĭ!! )"),A("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),A(";t.# &;w"),A("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),A("%;I/' 8!:ı!! )"),A("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),A('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),A('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),A('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),A('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),A("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),A("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),A("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),A('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),A("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),A("%;–/& 8!:Ő! )"),A('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),A('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),A("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),A("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),A("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),A('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'),A(';1." &"'),A('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),A("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),A(";¹.# &; "),A("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),A(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),A("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),A("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),A("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),A("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),A("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),A("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),A('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),A('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),A('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),A("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),A('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),A('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),A(";¾"),A('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),A(";ô.# &; "),A('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),A('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),A("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),A("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),A("$;%0#*;%&"),A("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),A('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),A('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),A("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),A(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),A('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?'),A('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),A('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),A('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),A("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),A("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),A("%;ă/,#;ă/#$+\")(\"'#&'#"),A("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),A("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),A('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),A(";™.# &;L"),A("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),A("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let c=0,h=0;const d=[{line:1,column:1}];let l,g=0,u=[],m=0;if(void 0!==t.startRule){if(!(t.startRule in r))throw new Error("Can't start parsing from rule \""+t.startRule+'".');n=r[t.startRule]}function v(){return e.substring(h,c)}function y(){return C(h,c)}function b(e,t){return{type:"literal",text:e,ignoreCase:t}}function T(e,t,s){return{type:"class",parts:e,inverted:t,ignoreCase:s}}function S(t){let s,i=d[t];if(i)return i;for(s=t-1;!d[s];)s--;for(i=d[s],i={line:i.line,column:i.column};s<t;)10===e.charCodeAt(s)?(i.line++,i.column=1):i.column++,s++;return d[t]=i,i}function C(e,t){const s=S(e),r=S(t);return{source:i,start:{offset:e,line:s.line,column:s.column},end:{offset:t,line:r.line,column:r.column}}}function E(e){c<g||(c>g&&(g=c,u=[]),u.push(e))}function A(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},l=function t(i){const r=a[i];let n=0;const d=[];let l=r.length;const g=[],u=[];let p;for(;;){for(;n<l;)switch(r[n]){case 0:u.push(o[r[n+1]]),n+=2;break;case 1:u.push(void 0),n++;break;case 2:u.push(null),n++;break;case 3:u.push(s),n++;break;case 4:u.push([]),n++;break;case 5:u.push(c),n++;break;case 6:u.pop(),n++;break;case 7:c=u.pop(),n++;break;case 8:u.length-=r[n+1],n+=2;break;case 9:u.splice(-2,1),n++;break;case 10:u[u.length-2].push(u.pop()),n++;break;case 11:u.push(u.splice(u.length-r[n+1],r[n+1])),n+=2;break;case 12:u.push(e.substring(u.pop(),c)),n++;break;case 13:g.push(l),d.push(n+3+r[n+1]+r[n+2]),u[u.length-1]?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 14:g.push(l),d.push(n+3+r[n+1]+r[n+2]),u[u.length-1]===s?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 15:g.push(l),d.push(n+3+r[n+1]+r[n+2]),u[u.length-1]!==s?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 16:u[u.length-1]!==s?(g.push(l),d.push(n),l=n+2+r[n+1],n+=2):n+=2+r[n+1];break;case 17:g.push(l),d.push(n+3+r[n+1]+r[n+2]),e.length>c?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 18:g.push(l),d.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length)===o[r[n+1]]?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 19:g.push(l),d.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length).toLowerCase()===o[r[n+1]]?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 20:g.push(l),d.push(n+4+r[n+2]+r[n+3]),o[r[n+1]].test(e.charAt(c))?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 21:u.push(e.substr(c,r[n+1])),c+=r[n+1],n+=2;break;case 22:u.push(o[r[n+1]]),c+=o[r[n+1]].length,n+=2;break;case 23:u.push(s),0===m&&E(o[r[n+1]]),n+=2;break;case 24:h=u[u.length-1-r[n+1]],n+=2;break;case 25:h=c,n++;break;case 26:p=r.slice(n+4,n+4+r[n+3]).map(function(e){return u[u.length-1-e]}),u.splice(u.length-r[n+2],r[n+2],o[r[n+1]].apply(null,p)),n+=4+r[n+3];break;case 27:u.push(t(r[n+1])),n+=2;break;case 28:m++,n++;break;case 29:m--,n++;break;default:throw new Error("Invalid opcode: "+r[n]+".")}if(!(g.length>0))break;l=g.pop(),n=d.pop()}return u[0]}(n),l!==s&&c===e.length)return l;throw l!==s&&c<e.length&&E({type:"end"}),_=u,I=g<e.length?e.charAt(g):null,R=g<e.length?C(g,g+1):C(g,g),new w(w.buildMessage(_,I),_,I,R);var _,I,R};var b;!function(e){e.parse=function(e,t){const s={startRule:t};try{y(e,s)}catch(e){s.data=-1}return s.data},e.nameAddrHeaderParse=function(t){const s=e.parse(t,"Name_Addr_Header");return-1!==s?s:void 0},e.URIParse=function(t){const s=e.parse(t,"SIP_URI");return-1!==s?s:void 0}}(b=b||(b={}));const T={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 S(e,t=32){let s="";for(let i=0;i<e;i++){s+=Math.floor(Math.random()*t).toString(t)}return s}function C(e){return T[e]||""}function E(){return S(10)}function A(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e<i;e++)0!==e&&(r+="-"),r+=s[e].charAt(0).toUpperCase()+s[e].substring(1);return t[r]&&(r=t[r]),r}function _(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class I{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=A(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[A(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[A(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[A(e)]}parseHeader(e,t=0){if(e=A(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const s=this.headers[e][t],i=s.raw;if(s.parsed)return s.parsed;const r=b.parse(i,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(s.parsed=r,r)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[A(e)]=[{raw:t}]}toString(){return this.data}}class R extends I{constructor(){super()}}class $ extends I{constructor(){super()}}class D{constructor(e,t,s,i,r,n,o){this.headers={},this.extraHeaders=[],this.options=D.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),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())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=s.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:E(),this.from=D.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=D.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+S(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")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,s){const i={};return s&&(i.tag=s),new p(e,t,i)}getHeader(e){const t=this.headers[A(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],s=this.headers[A(e)];if(s)for(const e of s)t.push(e);else{const s=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)s.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[A(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[A(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let s="SIP/2.0/"+t;s+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(s+=";rport"),this.setHeader("via",s),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const s of this.headers[t])e+=t+": "+s+"\r\n";for(const t of this.extraHeaders)e+=t.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: "+_(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: "+_(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}}function x(e){return"application/sdp"===e?"session":"render"}function k(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:x(s),contentType:s,content:t}}function N(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function H(e){let t,s,i;if(e instanceof R&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof $&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof D&&e.body)if(t=e.getHeader("Content-Disposition"),s=e.getHeader("Content-Type"),"string"==typeof e.body){if(!s)throw new Error("Header content type header does not equal body content type.");i=e.body}else{if(s&&s!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");s=e.body.contentType,i=e.body.body}if(N(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=x(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var P,O;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(P=P||(P={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(O=O||(O={}));const q=500,L=5e3,U={T1:q,T2:4e3,T4:L,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class M extends s{constructor(e){super(e||"Transaction state error.")}}var F;!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"}(F=F||(F={}));const j=[F.ACK,F.BYE,F.CANCEL,F.INFO,F.INVITE,F.MESSAGE,F.NOTIFY,F.OPTIONS,F.PRACK,F.REFER,F.REGISTER,F.SUBSCRIBE];class B{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}let G=class{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}};class V{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof p))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const s=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&s.push("Replaces: "+decodeURIComponent(i));const r=this.referredBy;return r&&s.push("Referred-By: "+r),e.extraHeaders=s,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var K,W;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(K=K||(K={}));class Y{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=K.Initial,this.delegate=t.delegate,this._stateEventEmitter=new l,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case K.Initial:case K.Establishing:break;case K.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case K.Terminating:case K.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case K.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 K.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 K.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case K.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 K.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(e={}){if(this.state!==K.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._info(t,s)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==K.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new r("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const s=H(t.message);if(!s)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(K.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(s,i).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===K.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(K.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(s,i).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==K.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(K.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==K.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},s=e.requestOptions||{};if(s.extraHeaders=(s.extraHeaders||[]).slice(),s.extraHeaders.push("Allow: "+j.toString()),s.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,s))}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return s.body=e,this.dialog.invite(t,s)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==K.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._message(t,s)}refer(e,t={}){if(this.state!==K.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(e instanceof Y&&!e.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const s=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,s,i)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const s=this.dialog;switch(s.sessionState){case P.Initial:case P.Early:throw new Error(`Invalid dialog state ${s.sessionState}`);case P.AckWait:return this.stateTransition(K.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(K.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(K.Terminated),i(r)}}});case P.Confirmed:{const i=s.bye(e,t);return this.stateTransition(K.Terminated),Promise.resolve(i)}case P.Terminated:throw new Error(`Invalid dialog state ${s.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,s){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,s))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,s){e.ack();const i=[];t&&i.push("Reason: "+this.getReasonHeaderValue(t,s)),e.session.bye(void 0,{extraHeaders:i})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==K.Established&&this.state!==K.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const s={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new c(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case O.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated),Promise.resolve()}case O.Stable:{const i=H(e.message);return i?"render"===i.contentDisposition?(this._renderbody=i.content,this._rendertype=i.contentType,Promise.resolve()):"session"!==i.contentDisposition?Promise.resolve():this.setAnswer(i,s).catch(e=>{this.logger.error(e.message);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:s}),this.stateTransition(K.Terminated)}):Promise.resolve()}case O.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated),Promise.resolve()}case O.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated),Promise.resolve()}case O.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===K.Established){if(this.delegate&&this.delegate.onBye){const t=new h(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(K.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===K.Established)if(this.delegate&&this.delegate.onInfo){const t=new g(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==K.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=b.nameAddrHeaderParse(t)}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(s).then(s=>{const i=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,200)}).catch(t=>{if(this.logger.error(t.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState===O.Stable){const t=e.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488))}this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(t=>{this.logger.error(t.message),this.logger.error("Failed to rollback offer on re-INVITE request");const s=e.reject({statusCode:488});if(this.state!==K.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,s.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===K.Established)if(this.delegate&&this.delegate.onMessage){const t=new B(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===K.Established){if(this.onNotify){const t=new G(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new G(e);this.delegate.onNotify(t)}else e.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===K.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==K.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new V(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const s=H(e.message);return s&&"session"===s.contentDisposition?this.setOfferAndGetAnswer(s,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case O.Initial:return this.getOffer(e);case O.HaveLocalOffer:return Promise.resolve(void 0);case O.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case O.Stable:return this.state!==K.Established?Promise.resolve(void 0):this.getOffer(e);case O.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),s=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(s,i).then(e=>k(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const s=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,n=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new i)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,r,n).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const s=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,n=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new i)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,r,n).then(()=>s.getDescription(r,n)).then(e=>k(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case K.Initial:e!==K.Establishing&&e!==K.Established&&e!==K.Terminating&&e!==K.Terminated&&t();break;case K.Establishing:e!==K.Established&&e!==K.Terminating&&e!==K.Terminated&&t();break;case K.Established:e!==K.Terminating&&e!==K.Terminated&&t();break;case K.Terminating:e!==K.Terminated&&t();break;case K.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===K.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const s=e;let i=C(e);return!i&&t&&(i=t),"SIP;cause="+s+';text="'+i+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof f)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const s=e.remoteIdentity.friendlyName,i=e.dialog.remoteTarget.toString(),r=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${s}" <${i}?Replaces=${encodeURIComponent(`${r};to-tag=${n};from-tag=${o}`)}>`}return t}}!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(W=W||(W={}));const J={"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};class z extends Y{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const s=this.incomingInviteRequest.message,i=s.getHeader("require");i&&i.toLowerCase().includes("100rel")&&(this.rel100="required");const r=s.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),s.toTag=t.toTag,"string"!=typeof s.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(K.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),s.hasHeader("expires")){const e=1e3*Number(s.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===K.Initial&&(t.reject({statusCode:487}),this.stateTransition(K.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=b.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=s.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=s.body,this._rendertype=s.getHeader("Content-Type")),this._id=s.callId+s.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case K.Initial:case K.Establishing:return this.reject().then(()=>super.dispose());case K.Established:case K.Terminating:case K.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==K.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(K.Establishing),this.sendAccept(e).then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(K.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==K.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===W.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==K.Initial&&this.state!==K.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,s=e.reasonPhrase?e.reasonPhrase:C(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?k(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}),this.stateTransition(K.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===K.Initial||this.state===K.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new d(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(K.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=H(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case O.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case O.Stable:return this.setAnswer(t,s).then(()=>{});case O.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case O.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case O.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof i?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof n?this.logger.error("A session description handler occurred while sending response"):e instanceof o?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof M&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===K.Initial||this.state===K.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(K.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(K.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:s})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:s})))}sendProgress(e={}){const t=e.statusCode||180,s=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),r=e.body?k(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();let n;return r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++),new Promise((e,a)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(n=e,this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n}))).then(t=>{let c,h;this._dialog=t.session,t.session.delegate={onPrack:s=>{c=s,clearTimeout(d),clearTimeout(u),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(c).then(s=>{try{h=c.accept({statusCode:200,body:s}),this.prackArrived(),e({prackRequest:c,prackResponse:h,progressResponse:t})}catch(e){a(e)}}).catch(e=>a(e)))}};const d=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(u),this.reject({statusCode:504}).then(()=>a(new o)).catch(e=>a(e)))},64*U.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n})}catch(e){return this.waitingForPrack=!1,void a(e)}u=setTimeout(l,g*=2)};let g=U.T1,u=setTimeout(l,g)}).catch(e=>{this.waitingForPrack=!1,a(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new o),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class Z extends Y{constructor(e,t,s={}){super(e,s),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==s.earlyMedia?s.earlyMedia:this.earlyMedia,this.fromTag=E(),this.inviteWithoutSdp=void 0!==s.inviteWithoutSdp?s.inviteWithoutSdp:this.inviteWithoutSdp;const i=Object.assign({},s);i.params=Object.assign({},s.params);const r=s.anonymous||!1,n=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(i.params.fromDisplayName="Anonymous",i.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(o="string"==typeof i.params.fromUri?b.URIParse(i.params.fromUri):i.params.fromUri),!o)throw new TypeError("Invalid from URI: "+i.params.fromUri);let a=t;if(i.params.toUri&&(a="string"==typeof i.params.toUri?b.URIParse(i.params.toUri):i.params.toUri),!a)throw new TypeError("Invalid to URI: "+i.params.toUri);const c=Object.assign({},i.params);c.fromTag=this.fromTag;const h=(i.extraHeaders||[]).slice();r&&e.configuration.uri&&(h.push("P-Preferred-Identity: "+e.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+n),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===W.Required&&h.push("Require: 100rel"),e.configuration.sipExtensionReplaces===W.Required&&h.push("Require: replaces"),i.extraHeaders=h;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(F.INVITE,t,o,a,c,h,undefined),this._contact=n,this._referralInviterOptions=i,this._renderbody=s.renderbody,this._rendertype=s.rendertype,s.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=s.sessionDescriptionHandlerModifiers),s.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=s.sessionDescriptionHandlerOptions),s.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=s.sessionDescriptionHandlerModifiersReInvite),s.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=s.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case K.Initial:case K.Establishing:return this.cancel().then(()=>super.dispose());case K.Established:case K.Terminating:case K.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==K.Initial&&this.state!==K.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(K.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(C(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(K.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==K.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(K.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(K.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==K.Terminated&&this.stateTransition(K.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(K.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof Y))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==K.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.message,s=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=b.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),s.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=s,s.signalingState){case O.Initial:case O.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(K.Terminated),Promise.reject(new Error("Bad Media Description"));case O.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(K.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(K.Terminated),t})}case O.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(s.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(s.id),e.ack(),this.stateTransition(K.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==s){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(K.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(K.Established),Promise.resolve()}const t=s.answer;if(!t)throw new Error("Answer is undefined.");const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,i).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(K.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(K.Terminated),t})}case O.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==K.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const s=e.message,i=e.session;s.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=b.nameAddrHeaderParse(s.getHeader("P-Asserted-Identity")));const r=s.getHeader("require"),n=s.getHeader("rseq"),o=!!(r&&r.includes("100rel")&&n?Number(n):void 0),a=[];switch(o&&a.push("RAck: "+s.getHeader("rseq")+" "+s.getHeader("cseq")),i.signalingState){case O.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:a})),Promise.resolve();case O.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case O.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,r),r.setDescription(s.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const s={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:a,body:s})}).catch(e=>{throw this.stateTransition(K.Terminated),e})}case O.Stable:if(o&&e.prack({extraHeaders:a}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;const e=i.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(K.Terminated),e})}return Promise.resolve();case O.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===K.Establishing||this.state===K.Terminating?this.stateTransition(K.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===K.Establishing||this.state===K.Terminating?this.stateTransition(K.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===K.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var X,Q,ee,te,se,ie,re;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(X=X||(X={}));class ne{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=X.Initial,this._waiting=!1,this._stateEventEmitter=new l,this._waitingEventEmitter=new l,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},ne.defaultOptions()),{registrar:s}),ne.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===b.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const i=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(F.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||ne.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||ne.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=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:ne.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new f("sip","anonymous","anonymous.invalid"),refreshFrequency:ne.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===X.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===X.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new r("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let s;t.message.hasHeader("expires")&&(s=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let i,r=this._contacts.length;if(!r)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;r--;){if(i=t.message.parseHeader("contact",r),!i)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&m(i.uri,this.userAgent.contact.pubGruu)){s=Number(i.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(i.uri.user===this.userAgent.contact.uri.user){s=Number(i.getParam("expires"));break}}else if(m(i.uri,this.userAgent.contact.uri)){s=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===s)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(i.hasParam("temp-gruu")){const e=i.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=b.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=b.URIParse(e.replace(/"/g,"")))}this.registered(s),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let s=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(s=Number.parseInt(e,void 0))}this._retryAfter=isNaN(s)?void 0:s,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}unregister(e={}){if(this.state===X.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==X.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new r("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===X.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});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(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==X.Registered&&this.stateTransition(X.Registered)}unregistered(){this.clearTimers(),this._state!==X.Unregistered&&this.stateTransition(X.Unregistered)}terminated(){this.clearTimers(),this._state!==X.Terminated&&this.stateTransition(X.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case X.Initial:e!==X.Registered&&e!==X.Unregistered&&e!==X.Terminated&&t();break;case X.Registered:e!==X.Unregistered&&e!==X.Terminated&&t();break;case X.Unregistered:e!==X.Registered&&e!==X.Terminated&&t();break;case X.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===X.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===X.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}ne.defaultExpires=600,ne.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(Q=Q||(Q={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(ee=ee||(ee={})),function(e){e.Started="Started",e.Stopped="Stopped"}(te=te||(te={}));class oe{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=oe.hexChars,s=oe.hexOut;let i,r,n,o;for(o=0;o<4;o+=1)for(r=8*o,i=e[o],n=0;n<8;n+=2)s[r+1+n]=t.charAt(15&i),i>>>=4,s[r+0+n]=t.charAt(15&i),i>>>=4;return s.join("")}static _md5cycle(e,t){let s=e[0],i=e[1],r=e[2],n=e[3];s+=(i&r|~i&n)+t[0]-680876936|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[1]-389564586|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[2]+606105819|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[3]-1044525330|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[4]-176418897|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[5]+1200080426|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[6]-1473231341|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[7]-45705983|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[8]+1770035416|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[9]-1958414417|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[10]-42063|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[11]-1990404162|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[12]+1804603682|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[13]-40341101|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[14]-1502002290|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[15]+1236535329|0,i=(i<<22|i>>>10)+r|0,s+=(i&n|r&~n)+t[1]-165796510|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[6]-1069501632|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[11]+643717713|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[0]-373897302|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[5]-701558691|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[10]+38016083|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[15]-660478335|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[4]-405537848|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[9]+568446438|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[14]-1019803690|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[3]-187363961|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[8]+1163531501|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[13]-1444681467|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[2]-51403784|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[7]+1735328473|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[12]-1926607734|0,i=(i<<20|i>>>12)+r|0,s+=(i^r^n)+t[5]-378558|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[8]-2022574463|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[11]+1839030562|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[14]-35309556|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[1]-1530992060|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[4]+1272893353|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[7]-155497632|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[10]-1094730640|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[13]+681279174|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[0]-358537222|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[3]-722521979|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[6]+76029189|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[9]-640364487|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[12]-421815835|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[15]+530742520|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[2]-995338651|0,i=(i<<23|i>>>9)+r|0,s+=(r^(i|~n))+t[0]-198630844|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[7]+1126891415|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[14]-1416354905|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[5]-57434055|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[12]+1700485571|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[3]-1894986606|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[10]-1051523|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[1]-2054922799|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[8]+1873313359|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[15]-30611744|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[6]-1560198380|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[13]+1309151649|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[4]-145523070|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[11]-1120210379|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[2]+718787259|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[9]-343485551|0,i=(i<<21|i>>>11)+r|0,e[0]=s+e[0]|0,e[1]=i+e[1]|0,e[2]=r+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(oe.stateIdentity),this}appendStr(e){const t=this._buffer8,s=this._buffer32;let i,r,n=this._bufferLength;for(r=0;r<e.length;r+=1){if(i=e.charCodeAt(r),i<128)t[n++]=i;else if(i<2048)t[n++]=(i>>>6)+192,t[n++]=63&i|128;else if(i<55296||i>56319)t[n++]=(i>>>12)+224,t[n++]=i>>>6&63|128,t[n++]=63&i|128;else{if(i=1024*(i-55296)+(e.charCodeAt(++r)-56320)+65536,i>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[n++]=(i>>>18)+240,t[n++]=i>>>12&63|128,t[n++]=i>>>6&63|128,t[n++]=63&i|128}n>=64&&(this._dataLength+=64,oe._md5cycle(this._state,s),n-=64,s[0]=s[16])}return this._bufferLength=n,this}appendAsciiStr(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e.charCodeAt(n++);if(r<64)break;this._dataLength+=64,oe._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}appendByteArray(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e[n++];if(r<64)break;this._dataLength+=64,oe._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}getState(){const 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]]}}setState(e){const t=e.buffer,s=e.state,i=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],r=0;r<t.length;r+=1)this._buffer8[r]=t.charCodeAt(r)}end(e=!1){const t=this._bufferLength,s=this._buffer8,i=this._buffer32,r=1+(t>>2);let n;if(this._dataLength+=t,s[t]=128,s[t+1]=s[t+2]=s[t+3]=0,i.set(oe.buffer32Identity.subarray(r),r),t>55&&(oe._md5cycle(this._state,i),i.set(oe.buffer32Identity)),n=8*this._dataLength,n<=4294967295)i[14]=n;else{const e=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),s=parseInt(e[1],16)||0;i[14]=t,i[15]=s}return oe._md5cycle(this._state,i),e?this._state:oe._hex(this._state)}}function ae(e){return oe.hashStr(e)}oe.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),oe.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),oe.hexChars="0123456789abcdef",oe.hexOut=[],oe.onePassHasher=new oe,"5d41402abc4b2a76b9719d911017c592"!==oe.hashStr("hello")&&console.error("Md5 self test failed.");class ce{constructor(e,t,s,i){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=s,this.password=i,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,s){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=S(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(s),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,s;t=this.ha1,""!==t&&void 0!==t||(t=ae(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=ae(this.method+":"+this.uri),this.response=ae(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=ae(this.method+":"+this.uri+":"+ae(e||"")),this.response=ae(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=ae(this.method+":"+this.uri),this.response=ae(t+":"+this.nonce+":"+s))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(se=se||(se={}));class he{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(se.error,e)}warn(e){this.genericLog(se.warn,e)}log(e){this.genericLog(se.log,e)}debug(e){this.genericLog(se.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class de{constructor(){this.builtinEnabled=!0,this._level=se.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:se.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new he(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new he(this,e);return this.loggers[e]=t,t}}genericLog(e,t,s,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,s,i),this.connector&&this.connector(se[e],t,s,i)}print(e,t,s,i){if("string"==typeof i){const e=[new Date,t];s&&e.push(s),i=e.concat(i).join(" | ")}switch(e){case se.error:console.error(i);break;case se.warn:console.warn(i);break;case se.log:console.log(i);break;case se.debug:console.debug(i)}}}function le(e,t){const s="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const i=t.reasonPhrase?t.reasonPhrase:C(t.statusCode);let r="SIP/2.0 "+t.statusCode+" "+i+s;t.statusCode>=100&&t.statusCode,t.statusCode;const n="From: "+e.getHeader("From")+s,o="Call-ID: "+e.callId+s,a="CSeq: "+e.cseq+" "+e.method+s,c=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+s,"");let h="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=E()),h+=";tag="+e}h+=s;let d="";t.supported&&(d="Supported: "+t.supported.join(", ")+s);let l="";t.userAgent&&(l="User-Agent: "+t.userAgent+s);let g="";return t.extraHeaders&&(g=t.extraHeaders.reduce((e,t)=>e+t.trim()+s,"")),r+=c,r+=n,r+=h,r+=a,r+=o,r+=d,r+=l,r+=g,t.body?(r+="Content-Type: "+t.body.contentType+s,r+="Content-Length: "+_(t.body.content)+s+s,r+=t.body.content):r+="Content-Length: 0\r\n\r\n",{message:r}}!function(e){function t(e,t){let s=t,i=0,r=0;if(e.substring(s,s+2).match(/(^\r\n)/))return-2;for(;0===i;){if(r=e.indexOf("\r\n",s),-1===r)return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?s=r+2:i=r}return i}function s(e,t,s,i){const r=t.indexOf(":",s),n=t.substring(s,r).trim(),o=t.substring(r+1,i).trim();let a;switch(n.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=b.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("record-route",o.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",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=b.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("contact",o.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",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof $&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(n.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+n+"'"}}e.getHeader=t,e.parseHeader=s,e.parseMessage=function(e,i){let r=0,n=e.indexOf("\r\n");if(-1===n)return void i.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,n),a=b.parse(o,"Request_Response");let c,h;if(-1!==a){for(a.status_code?(c=new $,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new R,c.method=a.method,c.ruri=a.uri),c.data=e,r=n+2;;){if(n=t(e,r),-2===n){h=r+2;break}if(-1===n)return void i.error("malformed message");const o=s(c,e,r,n);if(o&&!0!==o)return void i.error(o.error);r=n+2}return c.hasHeader("content-length")?c.body=e.substr(h,Number(c.getHeader("content-length"))):c.body=e.substring(h),c}i.warn('error parsing first line of SIP message: "'+o+'"')}}(ie=ie||(ie={}));class ge extends s{constructor(e){super(e||"Unspecified transport error.")}}class ue{constructor(e,t,s,i,r){this._transport=e,this._user=t,this._id=s,this._state=i,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,s),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const s=()=>{this.removeStateChangeListener(s),e()};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof ge)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new ge(e.message):new ge,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class pe extends ue{constructor(e,t,s,i,r){super(t,s,e.viaBranch,i,r),this._request=e,this.user=s}get request(){return this._request}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(re=re||(re={}));class fe extends pe{constructor(e,t,s){super(e,t,s,re.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case re.Proceeding:if(e.method===F.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case re.Accepted:if(e.method===F.INVITE)return;break;case re.Completed:if(e.method===F.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===F.ACK)return void this.stateTransition(re.Confirmed);break;case re.Confirmed:case re.Terminated:if(e.method===F.INVITE||e.method===F.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case re.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(re.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(re.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case re.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case re.Completed:case re.Confirmed:case re.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}retransmitAcceptedResponse(){this.state===re.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case re.Proceeding:t();break;case re.Accepted:case re.Completed:this.state!==re.Proceeding&&t();break;case re.Confirmed:this.state!==re.Completed&&t();break;case re.Terminated:this.state!==re.Accepted&&this.state!==re.Completed&&this.state!==re.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===re.Accepted&&(this.L=setTimeout(()=>this.timerL(),U.TIMER_L)),e===re.Completed&&(this.H=setTimeout(()=>this.timerH(),U.TIMER_H)),e===re.Confirmed&&(this.I=setTimeout(()=>this.timerI(),U.TIMER_I)),e===re.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},U.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===re.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(re.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(re.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===re.Accepted&&this.stateTransition(re.Terminated)}}class me extends ue{constructor(e,t,s,i,r){super(t,s,me.makeId(e),i,r),this._request=e,this.user=s,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class ve extends me{constructor(e,t,s){super(e,t,s,re.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),U.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case re.Trying:if(t>=100&&t<=199)return this.stateTransition(re.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(re.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case re.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(re.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case re.Completed:case re.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const s=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(re.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case re.Trying:s();break;case re.Proceeding:this.state!==re.Trying&&s();break;case re.Completed:this.state!==re.Trying&&this.state!==re.Proceeding&&s();break;case re.Terminated:this.state!==re.Trying&&this.state!==re.Proceeding&&this.state!==re.Completed&&(t||s());break;default:s()}e===re.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),U.TIMER_K)),e===re.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==re.Trying&&this.state!==re.Proceeding||(this.onRequestTimeout(),this.stateTransition(re.Terminated))}timerK(){this.state===re.Completed&&this.stateTransition(re.Terminated)}}class we{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const s=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof p))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=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.");const h=e.from.uri,d=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:n,remoteSequenceNumber:undefined,localURI:h,remoteURI:d,remoteTarget:r,routeSet:s,secure:!1}}static initialDialogStateForUserAgentServer(e,t,s=!1){const i=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof p))throw new Error("Contact not instance of NameAddrHeader.");const n=r.uri,o=e.cseq,a=e.callId,c=t,h=e.fromTag,d=e.from.uri;return{id:a+c+h,early:s,callId:a,localTag:c,remoteTag:h,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:d,remoteTarget:n,routeSet:i,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==F.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const s=this.remoteURI,i=this.remoteTag,r=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,h=this.routeSet,d=t&&t.extraHeaders,l=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,r,s,{callId:o,cseq:a,fromTag:n,toTag:i,routeSet:h},d,l)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===F.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class ye extends me{constructor(e,t,s){super(e,t,s,re.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),U.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const s="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(s,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case re.Calling:if(t>=100&&t<=199)return this.stateTransition(re.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(re.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(re.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case re.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(re.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(re.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case re.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case re.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case re.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(re.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,s=this.request.callId,i=this.request.cseq,r=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!r)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${r}\r\n`,c+=`Call-ID: ${s}\r\n`,c+=`CSeq: ${i} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case re.Calling:s();break;case re.Proceeding:this.state!==re.Calling&&s();break;case re.Accepted:case re.Completed:this.state!==re.Calling&&this.state!==re.Proceeding&&s();break;case re.Terminated:this.state!==re.Calling&&this.state!==re.Accepted&&this.state!==re.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),re.Proceeding,e===re.Completed&&(this.D=setTimeout(()=>this.timerD(),U.TIMER_D)),e===re.Accepted&&(this.M=setTimeout(()=>this.timerM(),U.TIMER_M)),e===re.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===re.Calling&&(this.onRequestTimeout(),this.stateTransition(re.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===re.Completed&&this.stateTransition(re.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===re.Accepted&&this.stateTransition(re.Terminated)}}class be{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");const s=this.core.makeOutgoingRequestMessage(F.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},t.extraHeaders);return s.branch=this.message.branch,this.message.headers.Route&&(s.headers.Route=this.message.headers.Route),e&&s.setHeader("Reason",e),this.transaction.state===re.Proceeding?new be(ve,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===re.Proceeding&&new be(ve,this.core,s)},{once:!0}),s}authenticationGuard(e,t){const s=e.statusCode;if(!s)throw new Error("Response status code undefined.");if(401!==s&&407!==s)return!0;let i,r;if(401===s?(i=e.parseHeader("www-authenticate"),r="authorization"):(i=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!i)return this.logger.warn(s+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==i.stale))return this.logger.warn(s+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,i))return!0;this.challenged=!0,i.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new $;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new $;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===re.Terminated&&(this.core.userAgentClients.delete(s),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id+t.request.method;this.core.userAgentClients.set(s,this)}}class Te extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.BYE,s);super(ve,e.userAgentCore,i,t),e.dispose()}}class Se extends pe{constructor(e,t,s){super(e,t,s,re.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case re.Trying:break;case re.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case re.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case re.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case re.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(re.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(re.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case re.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(re.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case re.Completed:return;case re.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(re.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case re.Trying:s();break;case re.Proceeding:this.state!==re.Trying&&s();break;case re.Completed:this.state!==re.Trying&&this.state!==re.Proceeding&&s();break;case re.Terminated:this.state!==re.Proceeding&&this.state!==re.Completed&&(t||s());break;default:s()}e===re.Completed&&(this.J=setTimeout(()=>this.timerJ(),U.TIMER_J)),e===re.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===re.Completed&&this.stateTransition(re.Terminated)}}class Ce{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=s.toTag?s.toTag:E(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new M(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new M(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new M(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const s=t.statusCode;if(s<300||s>399)throw new TypeError(`Invalid statusCode: ${s}`);const i=new Array;e.forEach(e=>i.push(`Contact: ${e.toString()}`)),t.extraHeaders=(t.extraHeaders||[]).concat(i);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new M(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new M(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding||this.transaction.state===re.Accepted;if(this.transaction instanceof Se)return this.transaction.state===re.Trying||this.transaction.state===re.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding;if(this.transaction instanceof Se)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding;if(this.transaction instanceof Se)return this.transaction.state===re.Trying||this.transaction.state===re.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding;if(this.transaction instanceof Se)return this.transaction.state===re.Trying||this.transaction.state===re.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding;if(this.transaction instanceof Se)return this.transaction.state===re.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=le(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===re.Terminated&&(this.core.userAgentServers.delete(s),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id;this.core.userAgentServers.set(t.id,this)}}class Ee extends Ce{constructor(e,t,s){super(Se,e.userAgentCore,t,s)}}class Ae extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.INFO,s);super(ve,e.userAgentCore,i,t)}}class _e extends Ce{constructor(e,t,s){super(Se,e.userAgentCore,t,s)}}class Ie extends be{constructor(e,t,s){super(ve,e,t,s)}}class Re extends Ce{constructor(e,t,s){super(Se,e,t,s)}}class $e extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.NOTIFY,s);super(ve,e.userAgentCore,i,t)}}class De extends Ce{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Se,i,t,s)}}class xe extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.PRACK,s);super(ve,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class ke extends Ce{constructor(e,t,s){super(Se,e.userAgentCore,t,s),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Ne extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.INVITE,s);super(ye,e.userAgentCore,i,t),this.delegate=t,e.signalingStateTransition(i),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}}class He extends Ce{constructor(e,t,s){super(fe,e.userAgentCore,t,s),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>`Record-Route: ${e}`));const t=super.accept(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),i}progress(e={statusCode:180}){const t=super.progress(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),i}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class Pe extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.REFER,s);super(ve,e.userAgentCore,i,t)}}class Oe extends Ce{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Se,i,t,s)}}class qe extends we{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=O.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof fe&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=O.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?P.Early:this.ackWait?P.AckWait:this._signalingState===O.Closed?P.Terminated:P.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof ye))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof ye))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(F.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(s),this.signalingStateTransition(s),{message:s}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof fe){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==re.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 Te(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new Ae(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${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 Ne(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const s=this.createOutgoingRequestMessage(F.MESSAGE,t);return new Ie(this.core,s,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new $e(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new xe(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new Pe(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==F.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===F.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},s=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.ackWait&&this.signalingState!==O.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===F.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof p))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case F.BYE:{const t=new Ee(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case F.INFO:{const t=new _e(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case F.INVITE:{const t=new He(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case F.MESSAGE:{const t=new Re(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case F.NOTIFY:{const t=new De(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case F.PRACK:{const t=new ke(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case F.REFER:{const t=new Oe(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof ye)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),s=e.getHeader("rseq"),i=t&&t.includes("100rel")&&s?Number(s):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq=this.rseq?this.rseq+1:i}}return!0}signalingStateRollback(){this._signalingState!==O.HaveLocalOffer&&this.signalingState!==O.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=O.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=H(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===O.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof R)switch(this._signalingState){case O.Initial:case O.Stable:this._signalingState=O.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case O.HaveLocalOffer:this._signalingState=O.Stable,this._answer=t;break;case O.HaveRemoteOffer:case O.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof $)switch(this._signalingState){case O.Initial:case O.Stable:this._signalingState=O.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case O.HaveLocalOffer:this._signalingState=O.Stable,this._answer=t;break;case O.HaveRemoteOffer:case O.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof D)switch(this._signalingState){case O.Initial:case O.Stable:this._signalingState=O.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case O.HaveLocalOffer:break;case O.HaveRemoteOffer:this._signalingState=O.Stable,this._answer=t;break;case O.Closed:break;default:throw new Error("Unexpected signaling state.")}if(N(e))switch(this._signalingState){case O.Initial:case O.Stable:this._signalingState=O.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case O.HaveLocalOffer:break;case O.HaveRemoteOffer:this._signalingState=O.Stable,this._answer=t;break;case O.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof fe){const e=this.initialTransaction;let t=U.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,U.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===re.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(i)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof fe){const e=this.reinviteUserAgentServer.transaction;let t=U.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,U.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===re.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class Le extends be{constructor(e,t,s){super(ye,e,t,s),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=s}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===re.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=we.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof ye))throw new Error("Transaction not instance of InviteClientTransaction.");s=new qe(e,this.core,t),this.earlyDialogs.set(s.id,s)}if(!s.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");s.signalingState!==O.Initial&&s.signalingState!==O.HaveLocalOffer||s.signalingStateTransition(e);const i=s;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:i,prack:e=>i.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=we.initialDialogStateForUserAgentClient(this.message,e);let s=this.confirmedDialogs.get(t.id);if(s){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof ye))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(s=this.earlyDialogs.get(t.id),s)s.confirm(),s.recomputeRouteSet(e),this.earlyDialogs.delete(s.id),this.confirmedDialogs.set(s.id,s);else{const e=this.transaction;if(!(e instanceof ye))throw new Error("Transaction not instance of InviteClientTransaction.");s=new qe(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==O.Initial&&s.signalingState!==O.HaveLocalOffer||s.signalingStateTransition(e);const i=s;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:i,ack:e=>{const t=i.ack(e);return this.confirmedDialogAcks.set(i.id,t),t}});else{const e=i.ack();this.confirmedDialogAcks.set(i.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class Ue extends Ce{constructor(e,t,s){super(fe,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new M(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof fe))throw new Error("Transaction not instance of InviteClientTransaction.");const t=we.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new qe(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),s=`Contact: ${this.core.configuration.contact.toString()}`,i="Allow: "+j.toString();if(!e.body)if(this.confirmedDialog.signalingState===O.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===O.Initial||this.confirmedDialog.signalingState===O.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i),e.extraHeaders.push(s);const r=super.accept(e),n=this.confirmedDialog,o=Object.assign(Object.assign({},r),{session:n});return e.body&&this.confirmedDialog.signalingState!==O.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new M(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof fe))throw new Error("Transaction not instance of InviteClientTransaction.");const t=we.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new qe(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),s=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(s);const i=super.progress(e),r=this.earlyDialog,n=Object.assign(Object.assign({},i),{session:r});return e.body&&this.earlyDialog.signalingState!==O.Stable&&this.earlyDialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class Me extends be{constructor(e,t,s){super(ve,e,t,s)}}class Fe extends be{constructor(e,t,s){super(ve,e,t,s)}}class je extends Ce{constructor(e,t,s){super(Se,e,t,s),this.core=e}}class Be extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.SUBSCRIBE,s);super(ve,e.userAgentCore,i,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class Ge extends we{constructor(e,t,s,i,r,n){super(i,r),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=s,this.logger=i.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const s=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof p))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=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:n,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:s,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(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){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===F.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+j.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){var s;if(this.subscriptionState!==Q.Pending&&this.subscriptionState!==Q.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const i=new Be(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(s=t.extraHeaders)||void 0===s?void 0:s.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),U.TIMER_N)),i}terminate(){this.stateTransition(Q.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+j.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const s=e.parseHeader("Subscription-State");if(!s||!s.state)return void this.core.replyStateless(e,{statusCode:489});const i=s.state,r=s.expires?Math.max(s.expires,0):void 0;switch(i){case"pending":this.stateTransition(Q.Pending,r);break;case"active":this.stateTransition(Q.Active,r);break;case"terminated":this.stateTransition(Q.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new De(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const s=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case Q.Initial:case Q.NotifyWait:return void s();case Q.Pending:if(this.subscriptionState!==Q.NotifyWait&&this.subscriptionState!==Q.Pending)return void s();break;case Q.Active:case Q.Terminated:if(this.subscriptionState!==Q.NotifyWait&&this.subscriptionState!==Q.Pending&&this.subscriptionState!==Q.Active)return void s();break;default:return void s()}e===Q.Pending&&t&&(this.subscriptionExpires=t),e===Q.Active&&t&&(this.subscriptionExpires=t),e===Q.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==Q.Terminated&&(this.stateTransition(Q.Terminated),this.onTerminated())}}class Ve extends be{constructor(e,t,s){const i=t.getHeader("Event");if(!i)throw new Error("Event undefined");const r=t.getHeader("Expires");if(!r)throw new Error("Expires undefined");super(ve,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=Q.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const s=e.message.parseHeader("Subscription-State");if(!s||!s.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const i=s.state;switch(i){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${i}`),void e.reject({statusCode:489})}if("terminated"!==i){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=s.expires?Math.min(this.subscriptionExpires,Math.max(s.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=Q.Pending;break;case"active":this.subscriptionState=Q.Active;break;case"terminated":this.subscriptionState=Q.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==Q.Terminated){const t=Ge.initialDialogStateForSubscription(this.message,e.message);this.dialog=new Ge(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,s=this.dialog;this.delegate.onNotify({request:t,subscription:s})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),U.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),e<this.subscriptionExpires&&(this.subscriptionExpires=e)}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)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}class Ke extends Ce{constructor(e,t,s){super(Se,e,t,s),this.core=e}}const We=["application/sdp","application/dtmf-relay"];class Ye{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new Le(this,e,t)}message(e,t){return new Ie(this,e,t)}publish(e,t){return new Me(this,e,t)}register(e,t){return new Fe(this,e,t)}subscribe(e,t){return new Ve(this,e,t)}request(e,t){return new be(ve,this,e,t)}makeOutgoingRequestMessage(e,t,s,i,r,n,o){const a=this.configuration.sipjsId,c=this.configuration.displayName,h=this.configuration.viaForceRport,d=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();e===F.REGISTER&&l.push("path","gruu"),e===F.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");const g={callIdPrefix:a,forceRport:h,fromDisplayName:c,hackViaTcp:d,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},u=Object.assign(Object.assign({},g),r);return new D(e,t,s,i,u,n,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const s=this.configuration.userAgentHeaderFieldValue,i=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:s,supported:i});const r=le(e,t);return this.transport.send(r.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),r}receiveRequestFromTransport(e){const t=e.viaBranch,s=this.userAgentServers.get(t);e.method===F.ACK&&s&&s.transaction.state===re.Accepted&&s instanceof Ue?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==F.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof fe&&s.transaction.state===re.Proceeding&&s instanceof Ue&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!j.includes(e.method)){const t="Allow: "+j.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,s=e=>!!e&&e.user===t.user;if(!s(this.configuration.aor)&&!(s(this.configuration.contact.uri)||s(this.configuration.contact.pubGruu)||s(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==F.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==F.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===F.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const s=e.callId+e.toTag+t.event,i=this.subscribers.get(s);if(i){const t=new De(this,e);return void i.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,s=this.dialogs.get(t);if(s){if(e.method===F.OPTIONS){const t="Allow: "+j.toString(),s="Accept: "+We.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==F.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case F.ACK:break;case F.BYE:this.replyStateless(e,{statusCode:481});break;case F.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case F.INFO:this.replyStateless(e,{statusCode:405});break;case F.INVITE:{const t=new Ue(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case F.MESSAGE:{const t=new Re(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case F.NOTIFY:{const t=new De(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case F.OPTIONS:{const t="Allow: "+j.toString(),s="Accept: "+We.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case F.REFER:{const t=new Oe(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case F.REGISTER:{const t=new je(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case F.SUBSCRIBE:{const t=new Ke(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,s=this.userAgentClients.get(t);s?s.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class Je{constructor(e,t,s){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=s,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==s?void 0:s.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach(t=>{t.track&&(t.track.enabled=e)})}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}getDescription(e,t){var s,i;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const r=null===(s=null==e?void 0:e.offerOptions)||void 0===s?void 0:s.iceRestart,n=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(i=this.sessionDescriptionHandlerConfiguration)||void 0===i?void 0:i.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.updateDirection(e)).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(r,n)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const s=this._peerConnection.getSenders();if(0===s.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const i=s[0].dtmf;if(!i)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const r=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{i.insertDTMF(e,r,n)}catch(e){return this.logger.error(e.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,s){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const i="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:i},s)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,s=this._localMediaStream,i=[],r=e=>{const r=e.kind;if("audio"!==r&&"video"!==r)throw new Error(`Unknown new track kind ${r}.`);const n=t.getSenders().find(e=>e.track&&e.track.kind===r);n?i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${r} track`),e()}).then(()=>n.replaceTrack(e).then(()=>{const t=s.getTracks().find(e=>e.kind===r);t&&(t.stop(),s.removeTrack(t),Je.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),Je.dispatchAddTrackEvent(s,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${r} track`),e}))):i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${r} track`),e()}).then(()=>{try{t.addTrack(e,s)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${r} track`),e}s.addTrack(e),Je.dispatchAddTrackEvent(s,e)}))},n=e.getAudioTracks();n.length&&r(n[0]);const o=e.getVideoTracks();return o.length&&r(o[0]),i.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let s;switch(this._peerConnection.signalingState){case"stable":s="offer";break;case"have-local-offer":s="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:s}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),Je.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),Je.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),Je.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),Je.dispatchAddTrackEvent(t,e))}updateDirection(e){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");{const t=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")}};this._peerConnection.getTransceivers().forEach(e=>{if(e.direction){const s=t(e.direction);e.direction!==s&&(e.direction=s)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[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"})(),s=(()=>{switch(t){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(e=>{e.direction&&"stopped"!==e.direction&&e.direction!==s&&(e.direction=s)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,s)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=s,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var s;const i=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var s;const i=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var s;const i=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${i}`),"complete"===i&&this.iceGatheringComplete(),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var s;const i=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const s=e.track.kind,i=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${s} ${i}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function ze(e){return(t,s)=>{void 0===e&&(e=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream));const i={iceGatheringTimeout:void 0!==(null==s?void 0:s.iceGatheringTimeout)?null==s?void 0:s.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==s?void 0:s.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new Je(r,e,i)}}class Ze{constructor(e,t){if(this._state=ee.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new l,this.logger=e,t){const e=t,s=null==e?void 0:e.wsServers,i=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==s){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}s&&!t.server&&("string"==typeof s&&(t.server=s),s instanceof Array&&(t.server=s[0]))}this.configuration=Object.assign(Object.assign({},Ze.defaultOptions),t);const s=this.configuration.server,i=b.parse(s,"absoluteURI");if(-1===i)throw this.logger.error(`Invalid WebSocket Server URL "${s}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(i.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${s}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=i.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===ee.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case ee.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ee.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case ee.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ee.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case ee.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ee.Connecting)}catch(e){if(e instanceof a)return Promise.reject(e);throw e}break;case ee.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ee.Connecting)}catch(e){if(e instanceof a)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e.toString()),new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.transitionState(ee.Disconnected,e)})}return this.connectPromise=new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case ee.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ee.Disconnecting)}catch(e){if(e instanceof a)return Promise.reject(e);throw e}break;case ee.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ee.Disconnecting)}catch(e){if(e instanceof a)return Promise.reject(e);throw e}break;case ee.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ee.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case ee.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ee.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,s)=>{this.disconnectResolve=t,this.disconnectReject=s;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e.toString()),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==ee.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const s=`WebSocket closed ${this.server} (code: ${e.code})`,i=this.disconnectPromise?void 0:new Error(s);i&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(s),this._ws=void 0,this.transitionState(ee.Disconnected,i)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const s=e.data;let i;if(/^(\r\n)+$/.test(s))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(s){if("string"!=typeof s){try{i=(new TextDecoder).decode(new Uint8Array(s))}catch(e){return this.logger.error(e.toString()),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"+i+"\n")}else i=s,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+i+"\n");if(this.state===ee.Connected){if(this.onMessage)try{this.onMessage(i)}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===ee.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(ee.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new a("Loop detected.")}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case ee.Connecting:e!==ee.Connected&&e!==ee.Disconnecting&&e!==ee.Disconnected&&s();break;case ee.Connected:e!==ee.Disconnecting&&e!==ee.Disconnected&&s();break;case ee.Disconnecting:e!==ee.Connecting&&e!==ee.Disconnected&&s();break;case ee.Disconnected:e!==ee.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===ee.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===ee.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 ${i} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===ee.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onConnect callback"),e}if(i===ee.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onDisconnect callback"),e}if(i===ee.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===ee.Connected?r():n(t||new Error("Connect aborted."))}if(i===ee.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===ee.Disconnected?o():a(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}Ze.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class Xe{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=te.Stopped,this._stateEventEmitter=new l,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Xe.defaultOptions()),{sipjsId:S(5)}),{uri:new f("sip","anonymous."+S(6),"anonymous.invalid")}),{viaHost:S(12)+".invalid"}),Xe.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,s=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+s}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new de,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=se.error;break;case"warn":this.loggerFactory.level=se.warn;break;case"log":this.loggerFactory.level=se.log;break;case"debug":this.loggerFactory.level=se.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,s=t.maxReconnectionAttempts,i=t.reconnectionTimeout;if(void 0!==s){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==i&&(this.options.reconnectionDelay=i),void 0===e.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:Xe.newUUID(),-1===b.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return b.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:ze(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:W.Unsupported,sipExtensionReplaces:W.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Ze,transportOptions:{},uri:new f("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)});return e}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===te.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===te.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(te.Started),this.transport.connect())}async stop(){if(this.state===te.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(te.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),s=Object.assign({},this._sessions),i=Object.assign({},this._subscriptions),r=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t});this.logger.log("Dispose of sessions");for(const e in s)s[e]&&await s[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t});this.logger.log("Dispose of subscriptions");for(const e in i)i[e]&&await i[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t});this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e});this.logger.log("Dispose of transport"),await r.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose(),this.transitionState(te.Stopped)}_makeInviter(e,t){return new Z(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,s=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(s=>{this.logger.error(s.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*s))}initContact(){const e=""!==this.options.contactName?this.options.contactName:S(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new f("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const s=e.anonymous||!1,i=e.outbound||!1,r=e.register||!1;let n="<";return n+=s?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:r?this.contact.uri:this.contact.pubGruu||this.contact.uri,i&&(n+=";ob"),n+=">",this.options.instanceIdAlwaysAdded&&(n+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),n}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===W.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===W.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>J[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const s={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new ce(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport},i={onInvite:e=>{var t;const s=new z(this,e);if(e.delegate={onCancel:e=>{s._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==W.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const i=t.replaces_to_tag;if("string"!=typeof i)throw new Error("Type of to tag is not string");const r=t.replaces_from_tag;if("string"!=typeof r)throw new Error("type of from tag is not string");const n=e+i+r,o=this.userAgentCore.dialogs.get(n);if(!o)return void s.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void s.reject({statusCode:486});const a=this._sessions[e+r]||this._sessions[e+i]||void 0;if(!a)throw new Error("Session does not exist.");s._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new B(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new G(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}};return new Ye(s,i)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==te.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==te.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=ie.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===te.Stopped&&t instanceof R)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const s=()=>{const e=["from","to","call_id","cseq","via"];for(const s of e)if(!t.hasHeader(s))return this.logger.warn(`Missing mandatory header field : ${s}.`),!1;return!0};if(t instanceof R){if(!s())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=_(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof $){if(!s())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(t.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=_(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(t instanceof R)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof $))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case te.Started:e!==te.Stopped&&s();break;case te.Stopped:e!==te.Started&&s();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}class Qe{constructor(e){this.listeners=[],this.keyListeners={},this.data={...e},this.proxy=new Proxy(this.data,{set:(e,t,s)=>(e[t]!==s&&(e[t]=s,this.notify(),this.notifyKey(t,s)),!0)})}getState(){return this.proxy}setState(e){let t=!1;for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)){const i=this.data[s],r=e[s];i!==r&&(this.data[s]=r,t=!0,this.notifyKey(s,r))}t&&this.notify()}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}subscribeKey(e,t){return this.keyListeners[e]||(this.keyListeners[e]=[]),this.keyListeners[e].push(t),()=>{this.keyListeners[e]=this.keyListeners[e].filter(e=>e!==t)}}notify(){const e=this.getState();for(const t of this.listeners)t(e)}notifyKey(e,t){const s=this.keyListeners[e];s&&s.forEach(e=>e(t))}}var et,tt,st,it,rt,nt,ot;!function(e){e[e.IDLE=1]="IDLE",e[e.BUSY=2]="BUSY",e[e.RINGING=3]="RINGING",e[e.OFFLINE=0]="OFFLINE"}(et||(et={})),function(e){e.OUTGOING="outgoing",e.INCOMING="incoming",e.CONSULT="consult"}(tt||(tt={})),function(e){e.WEB_RTC_CONNECTING="connecting",e.WEB_RTC_CONNECTED="connected",e.WEB_RTC_DISCONNECTING="disconnecting",e.WEB_RTC_DISCONNECTED="disconnected",e.WEB_RTC_REGISTERED="registered",e.WEB_RTC_UNREGISTERED="unregistered",e.WEB_RTC_TERMINATED="terminated",e.WEB_RTC_REGISTER_FAILED="register_failed",e.WEB_RTC_INCOMING_CALL="incoming_call",e.WEB_RTC_ANSWER_SUCCESS="answer_success",e.WEB_RTC_ANSWER_FAILED="answer_failed",e.WEB_RTC_CALL_ENDED="call_ended",e.OUTGOING_LADING="outgoing_login",e.INCOMING_LADING="incoming_login",e.WEB_RTC_SEND_DTMF="send_dtmf"}(st||(st={})),function(e){e.OUT_INCOMING_CALL="out_call_incoming_call",e.OUT_FAILED="out_call_failed",e.OUT_RINGING="out_call_ringing",e.OUT_OFF_ANSWER="out_call_answer",e.OUT_HANGUP="out_call_hangup",e.CONSULT_RINGING="consult_ringing",e.CONSULT_OFF_HOOK="consult_off_hook",e.CONSULT_FAILED="consult_failed",e.CONSULT_INCOMING="consult_incoming",e.CONSULT_CALL_IN_SUCCESS="consult_call_in_success",e.OTHER_SIDE_CONSULT_HANGUP="other_side_consult_hangup",e.OUR_SIDE_CONSULT_HANGUP="Our_side_consult_hangup",e.AGENT_STATE="agent_state",e.MUTE_SUCCESS="mute_success",e.MUTE_FAILED="mute_failed",e.UNMUTE_SUCCESS="unmute_success",e.UNMUTE_FAILED="unmute_failed",e.CONSULT_TRANSFER_SUCCESS="consult_transfer_success",e.CONSULT_TRANSFER_FAILED="consult_transfer_failed",e.CONSULT_TRANSFER_OFF_HOOK="consult_transfer_off_hook",e.INCOMING_CALL="incoming_call",e.INCOMING_CALL_OFF_HOOK="incoming_call_off_hook",e.INCOMING_CALL_END="incoming_call_end"}(it||(it={})),function(e){e[e.OUT_CALL=100]="OUT_CALL",e[e.AGENT_STATE=101]="AGENT_STATE",e[e.OUT_CALL_INCOMING_CALL=102]="OUT_CALL_INCOMING_CALL",e[e.OUT_CALL_RINGING=103]="OUT_CALL_RINGING",e[e.OUT_CALL_ANSWER=104]="OUT_CALL_ANSWER",e[e.CALL_HOLD=105]="CALL_HOLD",e[e.CALL_UNHOLD=106]="CALL_UNHOLD",e[e.OUT_CALL_END=107]="OUT_CALL_END",e[e.CONSULT_REQUEST=108]="CONSULT_REQUEST",e[e.CONSULT_RINGING=109]="CONSULT_RINGING",e[e.CONSULT_ANSWER=110]="CONSULT_ANSWER",e[e.CONSULT_FAIL=111]="CONSULT_FAIL",e[e.MUTE=112]="MUTE",e[e.UNMUTE=113]="UNMUTE",e[e.CONSULT_CALL_IN=114]="CONSULT_CALL_IN",e[e.CONSULT_CALL_IN_SUCCESS=115]="CONSULT_CALL_IN_SUCCESS",e[e.CONSULT_TRANSFER=116]="CONSULT_TRANSFER",e[e.CONSULT_TRANSFER_FAILED=118]="CONSULT_TRANSFER_FAILED",e[e.CONSULT_TRANSFER_OFF_HOOK=117]="CONSULT_TRANSFER_OFF_HOOK",e[e.INCOMING_CALL=119]="INCOMING_CALL",e[e.INCOMING_CALL_OFF_HOOK=120]="INCOMING_CALL_OFF_HOOK",e[e.INCOMING_CALL_END=121]="INCOMING_CALL_END"}(rt||(rt={})),function(e){e.EVENT_ALL="event_all",e.NOTIFICATION_CLICK="notification_click",e.UPDATE_ANSWER_DEVICE="update_answer_device",e.PHONE_BAR_OPERATION="phone_bar_operation"}(nt||(nt={})),function(e){e.RINGING="客户振铃",e.HOLD="通话保持",e.AGENT_RINGING="振铃中",e.CALLING="通话中",e.CONSULTING="正在咨询",e.CONSULT_CALL_IN="咨询来电",e.INCOMING_CALL="客户来电"}(ot||(ot={}));const at=function(e){return{all:e=e||new Map,on:function(t,s){var i=e.get(t);i?i.push(s):e.set(t,[s])},off:function(t,s){var i=e.get(t);i&&(s?i.splice(i.indexOf(s)>>>0,1):e.set(t,[]))},emit:function(t,s){var i=e.get(t);i&&i.slice().map(function(e){e(s)}),(i=e.get("*"))&&i.slice().map(function(e){e(t,s)})}}}(),ct={on(e,t){at.on(e,t)},off(e,t){at.off(e,t)},emit(e,t){at.emit(e,t),at.emit(nt.EVENT_ALL,{event:e,data:t})},clearAllListeners(){at.all.clear()}},ht={isCalling:!1,direction:null,outCallIsAnswer:!1,incomingIsAnswer:!1,isHold:!1,displayText:"",isMuted:!1,consultIsAnswer:!1,actionConfigs:[],answerDevice:1};const dt=new class extends Qe{updateIsCalling(e){this.setState({isCalling:e})}updateDirection(e){this.setState({direction:e})}updateOutCallIsAnswer(e){this.setState({outCallIsAnswer:e})}updateIsHold(e){this.getState().isHold=e}updateDisplayText(e){this.setState({displayText:e})}updateActionConfigs(e){let t=[...e];1!==this.get("answerDevice")&&(t=t.filter(e=>"answer"!==e&&"hangup"!==e&&"reject"!==e)),this.setState({actionConfigs:t}),ct.emit(nt.PHONE_BAR_OPERATION,t)}updateConsultIsAnswer(e){this.setState({consultIsAnswer:e})}updateIsMuted(e){this.setState({isMuted:e})}updateIncomingIsAnswer(e){this.setState({incomingIsAnswer:e})}updateAnswerDevice(e){this.setState({answerDevice:e}),ct.emit(nt.UPDATE_ANSWER_DEVICE,e)}reset(){this.setState({...ht})}getCallInfo(){return this.getState()}get(e){return this.getState()[e]}}(ht);class lt extends Error{response;request;options;constructor(e,t,s){const i=`${e.status||0===e.status?e.status:""} ${e.statusText||""}`.trim();super(`Request failed with ${i?`status code ${i}`:"an unknown error"}: ${t.method} ${t.url}`),this.name="HTTPError",this.response=e,this.request=t,this.options=s}}class gt extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name="TimeoutError",this.request=e}}const ut=(()=>{let e=!1,t=!1;const s="function"==typeof globalThis.ReadableStream,i="function"==typeof globalThis.Request;if(s&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(e){if(e instanceof Error&&"unsupported BodyInit type"===e.message)return!1;throw e}return e&&!t})(),pt="function"==typeof globalThis.AbortController,ft="function"==typeof globalThis.AbortSignal&&"function"==typeof globalThis.AbortSignal.any,mt="function"==typeof globalThis.ReadableStream,vt="function"==typeof globalThis.FormData,wt=["get","post","put","patch","head","delete"],yt={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},bt=2147483647,Tt=(new TextEncoder).encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,St=Symbol("stop"),Ct={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Et={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},At=(e,t)=>{const s=(e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(const[s,i]of e)t+=Tt,t+=(new TextEncoder).encode(`Content-Disposition: form-data; name="${s}"`).length,t+="string"==typeof i?(new TextEncoder).encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if("string"==typeof e)return(new TextEncoder).encode(e).length;if(e instanceof URLSearchParams)return(new TextEncoder).encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if("object"==typeof e&&null!==e)try{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length}catch{return 0}return 0})(e.body);let i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(r){const n=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();await async function e(){const{done:o,value:a}=await n.read();if(o)return t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(s,i)},new Uint8Array),void r.close();i+=a.byteLength;let c=0===s?0:i/s;(s<i||1===c)&&(c=.99),t&&t({percent:Number(c.toFixed(2)),transferredBytes:i,totalBytes:s},a),r.enqueue(a),await e()}()}})})},_t=e=>null!==e&&"object"==typeof e,It=(...e)=>{for(const t of e)if((!_t(t)||Array.isArray(t))&&void 0!==t)throw new TypeError("The `options` argument must be an object");return xt({},...e)},Rt=(e={},t={})=>{const s=new globalThis.Headers(e),i=t instanceof globalThis.Headers,r=new globalThis.Headers(t);for(const[e,t]of r.entries())i&&"undefined"===t||void 0===t?s.delete(e):s.set(e,t);return s};function $t(e,t,s){return Object.hasOwn(t,s)&&void 0===t[s]?[]:xt(e[s]??[],t[s]??[])}const Dt=(e={},t={})=>({beforeRequest:$t(e,t,"beforeRequest"),beforeRetry:$t(e,t,"beforeRetry"),afterResponse:$t(e,t,"afterResponse"),beforeError:$t(e,t,"beforeError")}),xt=(...e)=>{let t={},s={},i={};for(const r of e)if(Array.isArray(r))Array.isArray(t)||(t=[]),t=[...t,...r];else if(_t(r)){for(let[e,s]of Object.entries(r))_t(s)&&e in t&&(s=xt(t[e],s)),t={...t,[e]:s};_t(r.hooks)&&(i=Dt(i,r.hooks),t.hooks=i),_t(r.headers)&&(s=Rt(s,r.headers),t.headers=s)}return t},kt=e=>wt.includes(e)?e.toUpperCase():e,Nt={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Ht=(e={})=>{if("number"==typeof e)return{...Nt,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Nt,...e}};class Pt{static create(e,t){const s=new Pt(e,t),i=async()=>{if("number"==typeof s._options.timeout&&s._options.timeout>bt)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await s._fetch();for(const t of s._options.hooks.afterResponse){const i=await t(s.request,s._options,s._decorateResponse(e.clone()));i instanceof globalThis.Response&&(e=i)}if(s._decorateResponse(e),!e.ok&&s._options.throwHttpErrors){let t=new lt(e,s.request,s._options);for(const e of s._options.hooks.beforeError)t=await e(t);throw t}if(s._options.onDownloadProgress){if("function"!=typeof s._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!mt)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return((e,t)=>{const s=Number(e.headers.get("content-length"))||0;let i=0;return 204===e.status?(t&&t({percent:1,totalBytes:s,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(r){const n=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array),await async function e(){const{done:o,value:a}=await n.read();o?r.close():(t&&(i+=a.byteLength,t({percent:0===s?0:i/s,transferredBytes:i,totalBytes:s},a)),r.enqueue(a),await e())}()}}),{status:e.status,statusText:e.statusText,headers:e.headers})})(e.clone(),s._options.onDownloadProgress)}return e},r=(s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(i):i()).finally(async()=>{s.request.bodyUsed||await(s.request.body?.cancel())});for(const[e,i]of Object.entries(yt))r[e]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||i);const n=await r;if("json"===e){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(t.parseJson)return t.parseJson(await n.text())}return n[e]()};return r}request;abortController;_retryCount=0;_input;_options;constructor(e,t={}){if(this._input=e,this._options={...t,headers:Rt(this._input.headers,t.headers),hooks:Dt({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:kt(t.method??this._input.method??"GET"),prefixUrl:String(t.prefixUrl||""),retry:Ht(t.retry),throwHttpErrors:!1!==t.throwHttpErrors,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(pt&&ft){const e=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=e?AbortSignal.any([e,this.abortController.signal]):this.abortController.signal}if(ut&&(this._options.duplex="half"),void 0!==this._options.json&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const e="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);!(vt&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(t,{...this.request}),this._options)}if(this._options.onUploadProgress){if("function"!=typeof this._options.onUploadProgress)throw new TypeError("The `onUploadProgress` option must be a function");if(!ut)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=At(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount>this._options.retry.limit||e instanceof gt)throw e;if(e instanceof lt){if(!this._options.retry.statusCodes.includes(e.response.status))throw e;const t=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(t&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=1e3*Number(t);Number.isNaN(e)?e=Date.parse(t)-Date.now():e>=Date.parse("2024-01-01")&&(e-=Date.now());const s=this._options.retry.maxRetryAfter??e;return e<s?e:s}if(413===e.response.status)throw e}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const s=Math.min(this._calculateRetryDelay(t),bt);if(this._retryCount<1)throw t;await async function(e,{signal:t}){return new Promise((s,i)=>{function r(){clearTimeout(n),i(t.reason)}t&&(t.throwIfAborted(),t.addEventListener("abort",r,{once:!0}));const n=setTimeout(()=>{t?.removeEventListener("abort",r),s()},e)})}(s,{signal:this._options.signal});for(const e of this._options.hooks.beforeRetry){if(await e({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===St)return}return this._retry(e)}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const t=await e(this.request,this._options);if(t instanceof Request){this.request=t;break}if(t instanceof Response)return t}const e=((e,t)=>{const s={};for(const i in t)i in Et||i in Ct||i in e||(s[i]=t[i]);return s})(this.request,this._options),t=this.request;return this.request=t.clone(),!1===this._options.timeout?this._options.fetch(t,e):async function(e,t,s,i){return new Promise((r,n)=>{const o=setTimeout(()=>{s&&s.abort(),n(new gt(e))},i.timeout);i.fetch(e,t).then(r).catch(n).then(()=>{clearTimeout(o)})})}(t,e,this.abortController,this._options)}}
1
+ import e from"crypto";import t from"buffer";class s extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class i extends s{constructor(e){super(e||"Unsupported content type.")}}class r extends s{constructor(e){super(e||"Request pending.")}}class n extends s{constructor(e){super(e||"Unspecified session description handler error.")}}class o extends s{constructor(){super("The session has terminated.")}}class a extends s{constructor(e){super(e||"An error occurred during state transition.")}}class c{constructor(e){this.incomingAckRequest=e}get request(){return this.incomingAckRequest.message}}class h{constructor(e){this.incomingByeRequest=e}get request(){return this.incomingByeRequest.message}accept(e){return this.incomingByeRequest.accept(e),Promise.resolve()}reject(e){return this.incomingByeRequest.reject(e),Promise.resolve()}}class d{constructor(e){this.incomingCancelRequest=e}get request(){return this.incomingCancelRequest}}class l{constructor(){this.listeners=new Array}addListener(e,t){const s=t=>{this.removeListener(s),e(t)};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}emit(e){this.listeners.slice().forEach(t=>t(e))}removeAllListeners(){this.listeners=[]}removeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}on(e){return this.addListener(e)}off(e){return this.removeListener(e)}once(e){return this.addListener(e,{once:!0})}}class g{constructor(e){this.incomingInfoRequest=e}get request(){return this.incomingInfoRequest.message}accept(e){return this.incomingInfoRequest.accept(e),Promise.resolve()}reject(e){return this.incomingInfoRequest.reject(e),Promise.resolve()}}class u{constructor(e){this.parameters={};for(const t in e)e.hasOwnProperty(t)&&this.setParam(t,e[t])}setParam(e,t){e&&(this.parameters[e.toLowerCase()]=null==t?null:t.toString())}getParam(e){if(e)return this.parameters[e.toLowerCase()]}hasParam(e){return!(!e||void 0===this.parameters[e.toLowerCase()])}deleteParam(e){if(e=e.toLowerCase(),this.hasParam(e)){const t=this.parameters[e];return delete this.parameters[e],t}}clearParams(){this.parameters={}}}class p extends u{constructor(e,t,s){super(s),this.uri=e,this._displayName=t}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(e){this._displayName=e}clone(){return new p(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let e=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";e+="<"+this.uri.toString()+">";for(const t in this.parameters)this.parameters.hasOwnProperty(t)&&(e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]));return e}}class f extends u{constructor(e="sip",t,s,i,r,n){if(super(r||{}),this.headers={},!s)throw new TypeError('missing or invalid "host" parameter');for(const e in n)n.hasOwnProperty(e)&&this.setHeader(e,n[e]);this.raw={scheme:e,user:t,host:s,port:i},this.normal={scheme:e.toLowerCase(),user:t,host:s.toLowerCase(),port:i}}get scheme(){return this.normal.scheme}set scheme(e){this.raw.scheme=e,this.normal.scheme=e.toLowerCase()}get user(){return this.normal.user}set user(e){this.normal.user=this.raw.user=e}get host(){return this.normal.host}set host(e){this.raw.host=e,this.normal.host=e.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(e){this.normal.port=this.raw.port=e}setHeader(e,t){this.headers[this.headerize(e)]=t instanceof Array?t:[t]}getHeader(e){if(e)return this.headers[this.headerize(e)]}hasHeader(e){return!!e&&!!this.headers.hasOwnProperty(this.headerize(e))}deleteHeader(e){if(e=this.headerize(e),this.headers.hasOwnProperty(e)){const t=this.headers[e];return delete this.headers[e],t}}clearHeaders(){this.headers={}}clone(){return new f(this._raw.scheme,this._raw.user||"",this._raw.host,this._raw.port,JSON.parse(JSON.stringify(this.parameters)),JSON.parse(JSON.stringify(this.headers)))}toRaw(){return this._toString(this._raw)}toString(){return this._toString(this._normal)}get _normal(){return this.normal}get _raw(){return this.raw}_toString(e){let t=e.scheme+":";e.scheme.toLowerCase().match("^sips?$")||(t+="//"),e.user&&(t+=this.escapeUser(e.user)+"@"),t+=e.host,(e.port||0===e.port)&&(t+=":"+e.port);for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(t+=";"+e,null!==this.parameters[e]&&(t+="="+this.parameters[e]));const s=[];for(const e in this.headers)if(this.headers.hasOwnProperty(e))for(const t in this.headers[e])this.headers[e].hasOwnProperty(t)&&s.push(e+"="+this.headers[e][t]);return s.length>0&&(t+="?"+s.join("&")),t}escapeUser(e){let t;try{t=decodeURIComponent(e)}catch(e){throw e}return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e<i;e++)0!==e&&(r+="-"),r+=s[e].charAt(0).toUpperCase()+s[e].substring(1);return t[r]&&(r=t[r]),r}}function m(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){const s=Object.keys(e.parameters),i=Object.keys(t.parameters),r=s.filter(e=>i.includes(e));return!!r.every(s=>e.parameters[s]===t.parameters[s])&&(!!["user","ttl","method","transport"].every(s=>e.hasParam(s)&&t.hasParam(s)||!e.hasParam(s)&&!t.hasParam(s))&&!!["maddr"].every(s=>e.hasParam(s)&&t.hasParam(s)||!e.hasParam(s)&&!t.hasParam(s)))}(e,t))return!1;const s=Object.keys(e.headers),i=Object.keys(t.headers);if(0!==s.length||0!==i.length){if(s.length!==i.length)return!1;const r=s.filter(e=>i.includes(e));if(r.length!==i.length)return!1;if(!r.every(s=>e.headers[s].length&&t.headers[s].length&&e.headers[s][0]===t.headers[s][0]))return!1}return!0}function v(e,t,s){return s=s||" ",e.length>t?e:(t-=e.length,e+(s+=s.repeat(t)).slice(0,t))}class w extends Error{constructor(e,t,s,i){super(),this.message=e,this.expected=t,this.found=s,this.location=i,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,w.prototype):this.__proto__=w.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,w)}static buildMessage(e,t){function s(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,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(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,e=>"\\x0"+s(e)).replace(/[\x10-\x1F\x7F-\x9F]/g,e=>"\\x"+s(e))}function n(e){switch(e.type){case"literal":return'"'+i(e.text)+'"';case"class":const t=e.parts.map(e=>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){const t=e.map(n);let s,i;if(t.sort(),t.length>0){for(s=1,i=1;s<t.length;s++)t[s-1]!==t[s]&&(t[i]=t[s],i++);t.length=i}switch(t.length){case 1:return t[0];case 2:return t[0]+" or "+t[1];default:return t.slice(0,-1).join(", ")+", or "+t[t.length-1]}}(e)+" but "+(((o=t)?'"'+i(o)+'"':"end of input")+" found.");var o}format(e){let t="Error: "+this.message;if(this.location){let s,i=null;for(s=0;s<e.length;s++)if(e[s].source===this.location.source){i=e[s].text.split(/\r\n|\n|\r/g);break}let r=this.location.start,n=this.location.source+":"+r.line+":"+r.column;if(i){let e=this.location.end,s=v("",r.line.toString().length," "),o=i[r.line-1],a=r.line===e.line?e.column:o.length+1;t+="\n --\x3e "+n+"\n"+s+" |\n"+r.line+" | "+o+"\n"+s+" | "+v("",r.column-1," ")+v("",a-r.column,"^")}else t+="\n at "+n}return t}}const y=function(e,t){const s={},i=(t=void 0!==t?t:{}).grammarSource,r={Contact:119,Name_Addr_Header:156,Record_Route:176,Request_Response:81,SIP_URI:45,Subscription_State:186,Supported:191,Require:182,Via:194,absoluteURI:84,Call_ID:118,Content_Disposition:130,Content_Length:135,Content_Type:136,CSeq:146,displayName:122,Event:149,From:151,host:52,Max_Forwards:154,Min_SE:213,Proxy_Authenticate:157,quoted_string:40,Refer_To:178,Replaces:179,Session_Expires:210,stun_URI:217,To:192,turn_URI:223,uuid:226,WWW_Authenticate:209,challenge:158,sipfrag:230,Referred_By:231};let n=119;const o=["\r\n",b("\r\n",!1),/^[0-9]/,T([["0","9"]],!1,!1),/^[a-zA-Z]/,T([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,T([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,T([["\0","ÿ"]],!1,!1),/^["]/,T(['"'],!1,!1)," ",b(" ",!1),"\t",b("\t",!1),/^[a-zA-Z0-9]/,T([["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":"},/^[!-~]/,T([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,T([["€","￿"]],!1,!1),/^[\x80-\xBF]/,T([["€","¿"]],!1,!1),/^[a-f]/,T([["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'"'},/^[!-']/,T([["!","'"]],!1,!1),/^[*-[]/,T([["*","["]],!1,!1),/^[\]-~]/,T([["]","~"]],!1,!1),function(e){return e},/^[#-[]/,T([["#","["]],!1,!1),/^[\0-\t]/,T([["\0","\t"]],!1,!1),/^[\v-\f]/,T([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,T([["",""]],!1,!1),function(){(t=t||{data:{}}).data.uri=new f(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 f(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_\-]/,T([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,T([["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]/,T([["0","5"]],!1,!1),"2",b("2",!1),/^[0-4]/,T([["0","4"]],!1,!1),"1",b("1",!1),/^[1-9]/,T([["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,s){(t=t||{data:{}}).data.uri_params||(t.data.uri_params={}),s=null===s?void 0:s[1],t.data.uri_params[e.toLowerCase()]=s},function(e,s){e=e.join("").toLowerCase(),s=s.join(""),(t=t||{data:{}}).data.uri_headers||(t.data.uri_headers={}),t.data.uri_headers[e]?t.data.uri_headers[e].push(s):t.data.uri_headers[e]=[s]},function(){"Refer_To"===(t=t||{data:{}}).startRule&&(t.data.uri=new f(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,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e<s;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 p(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:c,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,s){(t=t||{data:{}}).data.params||(t.data.params={}),s=null===s?void 0:s[1],t.data.params[e.toLowerCase()]=s},"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 p(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 p(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,s;for(s=(t=t||{data:{}}).data.multi_header.length,e=0;e<s;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 p(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:c,offset:y().start.offset,parsed:e})},function(){(t=t||{data:{}}).data=new p(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 p(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)],a=[A('2 ""6 7!'),A('4"""5!7#'),A('4$""5!7%'),A('4&""5!7\''),A(";'.# &;("),A('4(""5!7)'),A('4*""5!7+'),A('2,""6,7-'),A('2.""6.7/'),A('40""5!71'),A('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'),A(";).# &;,"),A('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),A('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),A('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/&#0#*;$&&&#/\'$8":Z" )("\'#&\'#'),A(';.." &"'),A("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),A('%%$;2/&#0#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),A('4\\""5!7].# &;3'),A('4^""5!7_'),A('4`""5!7a'),A(';!.) &4b""5!7c'),A('%$;).• &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&&&#/"!&,)'),A('%$;).‰ &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&&&#/"!&,)'),A('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.) &;\'.# &;('),A('%$;).ī &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&&&#/"!&,)'),A("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),A("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),A("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),A("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),A("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),A('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),A('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),A("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),A("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),A("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),A("%;//0#;&/'$8\":~\" )(\"'#&'#"),A("%;&/0#;//'$8\":~\" )(\"'#&'#"),A("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),A('4""5!7€.A &4""5!7‚.5 &4ƒ""5!7„.) &;3.# &;.'),A("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),A("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:…$!!)($'#(#'#(\"'#&'#"),A(';..G &2L""6L7M.; &4†""5!7‡./ &4ƒ""5!7„.# &;3'),A('%2j""6j7k/J#4ˆ""5!7‰.5 &4Š""5!7‹.) &4Œ""5!7/#$+")("\'#&\'#'),A("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:Ž$ )($'#(#'#(\"'#&'#"),A("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),A('%3""5$7‘.) &3’""5#7“/\' 8!:”!! )'),A('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:•# )(#\'#("\'#&\'#'),A("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),A('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'),A('%$;+._ &;-.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!:–! )'),A('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),A("%;U.) &;\\.# &;X/& 8!:—! )"),A('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:˜# )(#\'#("\'#&\'#'),A('$4™""5!7š/,#0)*4™""5!7š&&&#'),A('%4$""5!7%/?#$4›""5!7œ0)*4›""5!7œ&/#$+")("\'#&\'#'),A('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),A('%%;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!: ! )'),A('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),A("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),A("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),A('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#.˜ &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7­/,#;!/#$+")("\'#&\'#.# &;!'),A('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),A('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),A(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),A('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),A('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),A('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),A('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),A('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),A('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),A('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),A('%$;j/&#0#*;j&&&#/"!&,)'),A('%$;j/&#0#*;j&&&#/"!&,)'),A(";k.) &;+.# &;-"),A('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),A('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),A('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),A("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),A("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),A('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),A(";‘.# &;r"),A("%;/G#;'/>$;s/5$;'/,$;„/#$+%)(%'#($'#(#'#(\"'#&'#"),A(";M.# &;t"),A("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),A('%;v.# &;w/J#%26""6677/,#;ƒ/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),A('%2Ð""6Ð7Ñ/:#;€/1$;w." &"/#$+#)(#\'#("\'#&\'#'),A('%24""6475/,#;{/#$+")("\'#&\'#'),A("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),A(";*.) &;+.# &;-"),A(';+. &;-.‰ &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'),A('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),A('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),A("$;~0#*;~&"),A(';+.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'),A('%%;"/‡#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),A(";.# &;‚"),A('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),A('$;+.ƒ &;-.} &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&&&#'),A("$;y0#*;y&"),A('%3’""5#7Ó/q#24""6475/b$$;!/&#0#*;!&&&#/L$2J""6J7K/=$$;!/&#0#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),A('2Õ""6Õ7Ö'),A('2×""6×7Ø'),A('2Ù""6Ù7Ú'),A('2Û""6Û7Ü'),A('2Ý""6Ý7Þ'),A('2ß""6ß7à'),A('2á""6á7â'),A('2ã""6ã7ä'),A('2å""6å7æ'),A('2ç""6ç7è'),A('2é""6é7ê'),A("%;….Y &;†.S &;ˆ.M &;‰.G &;Š.A &;‹.; &;Œ.5 &;./ &;.) &;Ž.# &;6/& 8!:ë! )"),A("%;„/G#;'/>$;’/5$;'/,$;”/#$+%)(%'#($'#(#'#(\"'#&'#"),A("%;“/' 8!:ì!! )"),A("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),A("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),A("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),A("%;:.c &%;˜/Y#$%;A/,#;˜/#$+\")(\"'#&'#06*%;A/,#;˜/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),A("%;L.# &;™/]#$%;B/,#;›/#$+\")(\"'#&'#06*%;B/,#;›/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),A("%;š.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),A("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),A(";œ.) &;.# &; "),A("%3ò\"\"5!7ó/:#;</1$;Ÿ/($8#:ô#! )(#'#(\"'#&'#"),A("%3õ\"\"5'7ö/:#;</1$;ž/($8#:÷#! )(#'#(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:ø!! )"),A('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),A('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),A(";6.) &;T.# &;H"),A("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),A(";¥.# &; "),A('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),A("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:Č!! )"),A("%;©/& 8!:č! )"),A("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),A(";«.# &;¬"),A('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;­'),A('3Ę""5\'7ę./ &3Ě""5)7ě.# &;­'),A(";6.# &;®"),A('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),A(";­.# &;6"),A("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),A(";6.# &;H"),A("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:Ğ!! )"),A("%;ž/' 8!:ğ!! )"),A('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),A('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),A("%;L.# &;™/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),A(";¹.# &; "),A("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:ĥ!! )"),A("%;ž/' 8!:Ħ!! )"),A("%$;š0#*;š&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),A(";¾"),A("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),A("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),A("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),A(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),A("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),A("%;I/' 8!:Ĭ!! )"),A("%3ĭ\"\"5&7Į/—#;</Ž$;D/…$;Å/|$$%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/&#0#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),A(";t.# &;w"),A("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),A("%;I/' 8!:ı!! )"),A("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),A('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),A('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),A('%3ń""5#7Ņ/“#;</Š$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),A('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),A("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:ŋ!! )"),A("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),A("%;™/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),A('%;L.O &;™.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),A("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),A("%;–/& 8!:Ő! )"),A('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),A('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),A("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%;™/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%$;!/&#0#*;!&&&#/' 8!:ŝ!! )"),A("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),A("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;ž/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;ž/($8#:ū#! )(#'#(\"'#&'#.# &; "),A('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'),A(';1." &"'),A('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),A("%;L.# &;™/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),A(";¹.# &; "),A("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),A("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),A(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),A("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),A("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),A("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),A("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),A("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),A("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),A('%3’""5#7Ó.# &;6/\' 8!:Ƌ!! )'),A('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),A('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),A("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),A('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),A('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),A(";¾"),A('%;ž/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),A(";ô.# &; "),A('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),A('%;ž/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),A("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),A("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),A("$;%0#*;%&"),A("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),A('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),A('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),A("%;\\.) &;X.# &;‚/' 8!:Ƣ!! )"),A(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),A('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?'),A('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),A('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),A('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),A("%;Ą/‡#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),A("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),A("%;ă/,#;ă/#$+\")(\"'#&'#"),A("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),A("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),A('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),A(";™.# &;L"),A("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),A("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let c=0,h=0;const d=[{line:1,column:1}];let l,g=0,u=[],m=0;if(void 0!==t.startRule){if(!(t.startRule in r))throw new Error("Can't start parsing from rule \""+t.startRule+'".');n=r[t.startRule]}function v(){return e.substring(h,c)}function y(){return C(h,c)}function b(e,t){return{type:"literal",text:e,ignoreCase:t}}function T(e,t,s){return{type:"class",parts:e,inverted:t,ignoreCase:s}}function S(t){let s,i=d[t];if(i)return i;for(s=t-1;!d[s];)s--;for(i=d[s],i={line:i.line,column:i.column};s<t;)10===e.charCodeAt(s)?(i.line++,i.column=1):i.column++,s++;return d[t]=i,i}function C(e,t){const s=S(e),r=S(t);return{source:i,start:{offset:e,line:s.line,column:s.column},end:{offset:t,line:r.line,column:r.column}}}function E(e){c<g||(c>g&&(g=c,u=[]),u.push(e))}function A(e){return e.split("").map(e=>e.charCodeAt(0)-32)}if(t.data={},l=function t(i){const r=a[i];let n=0;const d=[];let l=r.length;const g=[],u=[];let p;for(;;){for(;n<l;)switch(r[n]){case 0:u.push(o[r[n+1]]),n+=2;break;case 1:u.push(void 0),n++;break;case 2:u.push(null),n++;break;case 3:u.push(s),n++;break;case 4:u.push([]),n++;break;case 5:u.push(c),n++;break;case 6:u.pop(),n++;break;case 7:c=u.pop(),n++;break;case 8:u.length-=r[n+1],n+=2;break;case 9:u.splice(-2,1),n++;break;case 10:u[u.length-2].push(u.pop()),n++;break;case 11:u.push(u.splice(u.length-r[n+1],r[n+1])),n+=2;break;case 12:u.push(e.substring(u.pop(),c)),n++;break;case 13:g.push(l),d.push(n+3+r[n+1]+r[n+2]),u[u.length-1]?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 14:g.push(l),d.push(n+3+r[n+1]+r[n+2]),u[u.length-1]===s?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 15:g.push(l),d.push(n+3+r[n+1]+r[n+2]),u[u.length-1]!==s?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 16:u[u.length-1]!==s?(g.push(l),d.push(n),l=n+2+r[n+1],n+=2):n+=2+r[n+1];break;case 17:g.push(l),d.push(n+3+r[n+1]+r[n+2]),e.length>c?(l=n+3+r[n+1],n+=3):(l=n+3+r[n+1]+r[n+2],n+=3+r[n+1]);break;case 18:g.push(l),d.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length)===o[r[n+1]]?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 19:g.push(l),d.push(n+4+r[n+2]+r[n+3]),e.substr(c,o[r[n+1]].length).toLowerCase()===o[r[n+1]]?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 20:g.push(l),d.push(n+4+r[n+2]+r[n+3]),o[r[n+1]].test(e.charAt(c))?(l=n+4+r[n+2],n+=4):(l=n+4+r[n+2]+r[n+3],n+=4+r[n+2]);break;case 21:u.push(e.substr(c,r[n+1])),c+=r[n+1],n+=2;break;case 22:u.push(o[r[n+1]]),c+=o[r[n+1]].length,n+=2;break;case 23:u.push(s),0===m&&E(o[r[n+1]]),n+=2;break;case 24:h=u[u.length-1-r[n+1]],n+=2;break;case 25:h=c,n++;break;case 26:p=r.slice(n+4,n+4+r[n+3]).map(function(e){return u[u.length-1-e]}),u.splice(u.length-r[n+2],r[n+2],o[r[n+1]].apply(null,p)),n+=4+r[n+3];break;case 27:u.push(t(r[n+1])),n+=2;break;case 28:m++,n++;break;case 29:m--,n++;break;default:throw new Error("Invalid opcode: "+r[n]+".")}if(!(g.length>0))break;l=g.pop(),n=d.pop()}return u[0]}(n),l!==s&&c===e.length)return l;throw l!==s&&c<e.length&&E({type:"end"}),_=u,I=g<e.length?e.charAt(g):null,R=g<e.length?C(g,g+1):C(g,g),new w(w.buildMessage(_,I),_,I,R);var _,I,R};var b;!function(e){e.parse=function(e,t){const s={startRule:t};try{y(e,s)}catch(e){s.data=-1}return s.data},e.nameAddrHeaderParse=function(t){const s=e.parse(t,"Name_Addr_Header");return-1!==s?s:void 0},e.URIParse=function(t){const s=e.parse(t,"SIP_URI");return-1!==s?s:void 0}}(b=b||(b={}));const T={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 S(e,t=32){let s="";for(let i=0;i<e;i++){s+=Math.floor(Math.random()*t).toString(t)}return s}function C(e){return T[e]||""}function E(){return S(10)}function A(e){const t={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},s=e.toLowerCase().replace(/_/g,"-").split("-"),i=s.length;let r="";for(let e=0;e<i;e++)0!==e&&(r+="-"),r+=s[e].charAt(0).toUpperCase()+s[e].substring(1);return t[r]&&(r=t[r]),r}function _(e){return encodeURIComponent(e).replace(/%[A-F\d]{2}/g,"U").length}class I{constructor(){this.headers={}}addHeader(e,t){const s={raw:t};e=A(e),this.headers[e]?this.headers[e].push(s):this.headers[e]=[s]}getHeader(e){const t=this.headers[A(e)];if(t)return t[0]?t[0].raw:void 0}getHeaders(e){const t=this.headers[A(e)],s=[];if(!t)return[];for(const e of t)s.push(e.raw);return s}hasHeader(e){return!!this.headers[A(e)]}parseHeader(e,t=0){if(e=A(e),!this.headers[e])return;if(t>=this.headers[e].length)return;const s=this.headers[e][t],i=s.raw;if(s.parsed)return s.parsed;const r=b.parse(i,e.replace(/-/g,"_"));return-1===r?void this.headers[e].splice(t,1):(s.parsed=r,r)}s(e,t=0){return this.parseHeader(e,t)}setHeader(e,t){this.headers[A(e)]=[{raw:t}]}toString(){return this.data}}class R extends I{constructor(){super()}}class $ extends I{constructor(){super()}}class D{constructor(e,t,s,i,r,n,o){this.headers={},this.extraHeaders=[],this.options=D.getDefaultOptions(),r&&(this.options=Object.assign(Object.assign({},this.options),r),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())),n&&n.length&&(this.extraHeaders=n.slice()),o&&(this.body={body:o.content,contentType:o.contentType}),this.method=e,this.ruri=t.clone(),this.fromURI=s.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:E(),this.from=D.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=i.clone(),this.toTag=this.options.toTag,this.to=D.makeNameAddrHeader(this.toURI,this.options.toDisplayName,this.toTag),this.callId=this.options.callId?this.options.callId:this.options.callIdPrefix+S(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")}static getDefaultOptions(){return{callId:"",callIdPrefix:"",cseq:1,toDisplayName:"",toTag:"",fromDisplayName:"",fromTag:"",forceRport:!1,hackViaTcp:!1,optionTags:["outbound"],routeSet:[],userAgentString:"sip.js",viaHost:""}}static makeNameAddrHeader(e,t,s){const i={};return s&&(i.tag=s),new p(e,t,i)}getHeader(e){const t=this.headers[A(e)];if(t){if(t[0])return t[0]}else{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return e.substring(e.indexOf(":")+1).trim()}}getHeaders(e){const t=[],s=this.headers[A(e)];if(s)for(const e of s)t.push(e);else{const s=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)s.test(e)&&t.push(e.substring(e.indexOf(":")+1).trim())}return t}hasHeader(e){if(this.headers[A(e)])return!0;{const t=new RegExp("^\\s*"+e+"\\s*:","i");for(const e of this.extraHeaders)if(t.test(e))return!0}return!1}setHeader(e,t){this.headers[A(e)]=t instanceof Array?t:[t]}setViaHeader(e,t){this.options.hackViaTcp&&(t="TCP");let s="SIP/2.0/"+t;s+=" "+this.options.viaHost+";branch="+e,this.options.forceRport&&(s+=";rport"),this.setHeader("via",s),this.branch=e}toString(){let e="";e+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const t in this.headers)if(this.headers[t])for(const s of this.headers[t])e+=t+": "+s+"\r\n";for(const t of this.extraHeaders)e+=t.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: "+_(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: "+_(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}}function x(e){return"application/sdp"===e?"session":"render"}function k(e){const t="string"==typeof e?e:e.body,s="string"==typeof e?"application/sdp":e.contentType;return{contentDisposition:x(s),contentType:s,content:t}}function N(e){return!(!e||"string"!=typeof e.content||"string"!=typeof e.contentType||void 0!==e.contentDisposition)||"string"==typeof e.contentDisposition}function H(e){let t,s,i;if(e instanceof R&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof $&&e.body){const r=e.parseHeader("Content-Disposition");t=r?r.type:void 0,s=e.parseHeader("Content-Type"),i=e.body}if(e instanceof D&&e.body)if(t=e.getHeader("Content-Disposition"),s=e.getHeader("Content-Type"),"string"==typeof e.body){if(!s)throw new Error("Header content type header does not equal body content type.");i=e.body}else{if(s&&s!==e.body.contentType)throw new Error("Header content type header does not equal body content type.");s=e.body.contentType,i=e.body.body}if(N(e)&&(t=e.contentDisposition,s=e.contentType,i=e.content),i){if(s&&!t&&(t=x(s)),!t)throw new Error("Content disposition undefined.");if(!s)throw new Error("Content type undefined.");return{contentDisposition:t,contentType:s,content:i}}}var P,O;!function(e){e.Initial="Initial",e.Early="Early",e.AckWait="AckWait",e.Confirmed="Confirmed",e.Terminated="Terminated"}(P=P||(P={})),function(e){e.Initial="Initial",e.HaveLocalOffer="HaveLocalOffer",e.HaveRemoteOffer="HaveRemoteOffer",e.Stable="Stable",e.Closed="Closed"}(O=O||(O={}));const q=500,L=5e3,U={T1:q,T2:4e3,T4:L,TIMER_B:32e3,TIMER_D:0,TIMER_F:32e3,TIMER_H:32e3,TIMER_I:0,TIMER_J:0,TIMER_K:0,TIMER_L:32e3,TIMER_M:32e3,TIMER_N:32e3,PROVISIONAL_RESPONSE_INTERVAL:6e4};class M extends s{constructor(e){super(e||"Transaction state error.")}}var F;!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"}(F=F||(F={}));const j=[F.ACK,F.BYE,F.CANCEL,F.INFO,F.INVITE,F.MESSAGE,F.NOTIFY,F.OPTIONS,F.PRACK,F.REFER,F.REGISTER,F.SUBSCRIBE];class B{constructor(e){this.incomingMessageRequest=e}get request(){return this.incomingMessageRequest.message}accept(e){return this.incomingMessageRequest.accept(e),Promise.resolve()}reject(e){return this.incomingMessageRequest.reject(e),Promise.resolve()}}let G=class{constructor(e){this.incomingNotifyRequest=e}get request(){return this.incomingNotifyRequest.message}accept(e){return this.incomingNotifyRequest.accept(e),Promise.resolve()}reject(e){return this.incomingNotifyRequest.reject(e),Promise.resolve()}};class V{constructor(e,t){this.incomingReferRequest=e,this.session=t}get referTo(){const e=this.incomingReferRequest.message.parseHeader("refer-to");if(!(e instanceof p))throw new Error("Failed to parse Refer-To header.");return e}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const e=this.referTo.uri.getHeader("replaces");return e instanceof Array?e[0]:e}get request(){return this.incomingReferRequest.message}accept(e={statusCode:202}){return this.incomingReferRequest.accept(e),Promise.resolve()}reject(e){return this.incomingReferRequest.reject(e),Promise.resolve()}makeInviter(e){if(this.inviter)return this.inviter;const t=this.referTo.uri.clone();t.clearHeaders();const s=((e=e||{}).extraHeaders||[]).slice(),i=this.replaces;i&&s.push("Replaces: "+decodeURIComponent(i));const r=this.referredBy;return r&&s.push("Referred-By: "+r),e.extraHeaders=s,this.inviter=this.session.userAgent._makeInviter(t,e),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var K,W;!function(e){e.Initial="Initial",e.Establishing="Establishing",e.Established="Established",e.Terminating="Terminating",e.Terminated="Terminated"}(K=K||(K={}));class Y{constructor(e,t={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=K.Initial,this.delegate=t.delegate,this._stateEventEmitter=new l,this._userAgent=e}dispose(){switch(this.logger.log(`Session ${this.id} in state ${this._state} is being disposed`),delete this.userAgent._sessions[this.id],this._sessionDescriptionHandler&&this._sessionDescriptionHandler.close(),this.state){case K.Initial:case K.Establishing:break;case K.Established:return new Promise(e=>{this._bye({onAccept:()=>e(),onRedirect:()=>e(),onReject:()=>e()})});case K.Terminating:case K.Terminated:break;default:throw new Error("Unknown state.")}return Promise.resolve()}get assertedIdentity(){return this._assertedIdentity}get dialog(){return this._dialog}get id(){return this._id}get replacee(){return this._replacee}get sessionDescriptionHandler(){return this._sessionDescriptionHandler}get sessionDescriptionHandlerFactory(){return this.userAgent.configuration.sessionDescriptionHandlerFactory}get sessionDescriptionHandlerModifiers(){return this._sessionDescriptionHandlerModifiers||[]}set sessionDescriptionHandlerModifiers(e){this._sessionDescriptionHandlerModifiers=e.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(e){this._sessionDescriptionHandlerOptions=Object.assign({},e)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(e){this._sessionDescriptionHandlerModifiersReInvite=e.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(e){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},e)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(e={}){let t="Session.bye() may only be called if established session.";switch(this.state){case K.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 K.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 K.Established:{const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._bye(t,s)}case K.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 K.Terminated:t+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(t),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(e={}){if(this.state!==K.Established){const e="Session.info() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._info(t,s)}invite(e={}){if(this.logger.log("Session.invite"),this.state!==K.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new r("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=e.sessionDescriptionHandlerOptions);const t={onAccept:t=>{const s=H(t.message);if(!s)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(t,400,"Missing session description"),this.stateTransition(K.Terminated),void(this.pendingReinvite=!1);if(e.withoutSdp){const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(s,i).then(e=>{t.ack({body:e})}).catch(e=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state===K.Terminated?t.ack():(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(K.Terminated))}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}else{const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(s,i).then(()=>{t.ack()}).catch(e=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(e.message),this.state!==K.Terminated?(this.ackAndBye(t,488,"Bad Media Description"),this.stateTransition(K.Terminated)):t.ack()}).then(()=>{this.pendingReinvite=!1,e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})}},onProgress:e=>{},onRedirect:e=>{},onReject:t=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,e.withoutSdp?e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t):this.rollbackOffer().catch(e=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(e.message),this.state!==K.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated)}}).then(()=>{e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)})},onTrying:e=>{}},s=e.requestOptions||{};if(s.extraHeaders=(s.extraHeaders||[]).slice(),s.extraHeaders.push("Allow: "+j.toString()),s.extraHeaders.push("Contact: "+this._contact),e.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(t,s))}const i={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(i).then(e=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return s.body=e,this.dialog.invite(t,s)}).catch(e=>{throw this.logger.error(e.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,e})}message(e={}){if(this.state!==K.Established){const e="Session.message() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return this._message(t,s)}refer(e,t={}){if(this.state!==K.Established){const e="Session.refer() may only be called if established session.";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(e instanceof Y&&!e.dialog){const e="Session.refer() may only be called with session which is established. You are perhaps attempting to attended transfer to a target for which there is not dialog yet established. Perhaps you are attempting a 'semi-attended' tansfer? Regardless, this is not supported. The recommended approached is to check to see if the target Session is in the Established state before calling refer(); if the state is not Established you may proceed by falling back using a URI as the target (blind transfer).";return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}const s=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,s,i)}_bye(e,t){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const s=this.dialog;switch(s.sessionState){case P.Initial:case P.Early:throw new Error(`Invalid dialog state ${s.sessionState}`);case P.AckWait:return this.stateTransition(K.Terminating),new Promise(i=>{s.delegate={onAck:()=>{const r=s.bye(e,t);return this.stateTransition(K.Terminated),i(r),Promise.resolve()},onAckTimeout:()=>{const r=s.bye(e,t);this.stateTransition(K.Terminated),i(r)}}});case P.Confirmed:{const i=s.bye(e,t);return this.stateTransition(K.Terminated),Promise.resolve(i)}case P.Terminated:throw new Error(`Invalid dialog state ${s.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(e,t){return this.dialog?Promise.resolve(this.dialog.info(e,t)):Promise.reject(new Error("Session dialog undefined."))}_message(e,t){return this.dialog?Promise.resolve(this.dialog.message(e,t)):Promise.reject(new Error("Session dialog undefined."))}_refer(e,t,s){return this.dialog?(this.onNotify=e,Promise.resolve(this.dialog.refer(t,s))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(e,t,s){e.ack();const i=[];t&&i.push("Reason: "+this.getReasonHeaderValue(t,s)),e.session.bye(void 0,{extraHeaders:i})}onAckRequest(e){if(this.logger.log("Session.onAckRequest"),this.state!==K.Established&&this.state!==K.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const t=this.dialog;if(!t)throw new Error("Dialog undefined.");const s={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const t=new c(e);this.delegate.onAck(t)}switch(this.pendingReinviteAck=!1,t.signalingState){case O.Initial:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated),Promise.resolve()}case O.Stable:{const i=H(e.message);return i?"render"===i.contentDisposition?(this._renderbody=i.content,this._rendertype=i.contentType,Promise.resolve()):"session"!==i.contentDisposition?Promise.resolve():this.setAnswer(i,s).catch(e=>{this.logger.error(e.message);const s=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];t.bye(void 0,{extraHeaders:s}),this.stateTransition(K.Terminated)}):Promise.resolve()}case O.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated),Promise.resolve()}case O.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${t.signalingState}.`);const e=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return t.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated),Promise.resolve()}case O.Closed:default:throw new Error(`Invalid signaling state ${t.signalingState}.`)}}onByeRequest(e){if(this.logger.log("Session.onByeRequest"),this.state===K.Established){if(this.delegate&&this.delegate.onBye){const t=new h(e);this.delegate.onBye(t)}else e.accept();this.stateTransition(K.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(e){if(this.logger.log("Session.onInfoRequest"),this.state===K.Established)if(this.delegate&&this.delegate.onInfo){const t=new g(e);this.delegate.onInfo(t)}else e.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(e){if(this.logger.log("Session.onInviteRequest"),this.state!==K.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const t=["Contact: "+this._contact];if(e.message.hasHeader("P-Asserted-Identity")){const t=e.message.getHeader("P-Asserted-Identity");if(!t)throw new Error("Header undefined.");this._assertedIdentity=b.nameAddrHeaderParse(t)}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(s).then(s=>{const i=e.accept({statusCode:200,extraHeaders:t,body:s});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,i.message,200)}).catch(t=>{if(this.logger.error(t.message),this.logger.error("Failed to handle to re-INVITE request"),!this.dialog)throw new Error("Dialog undefined.");if(this.logger.error(this.dialog.signalingState),this.dialog.signalingState===O.Stable){const t=e.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488))}this.rollbackOffer().then(()=>{const t=e.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,t.message,488)}).catch(t=>{this.logger.error(t.message),this.logger.error("Failed to rollback offer on re-INVITE request");const s=e.reject({statusCode:488});if(this.state!==K.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const e=[];e.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:e}),this.stateTransition(K.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(e.message,s.message,488)})})}onMessageRequest(e){if(this.logger.log("Session.onMessageRequest"),this.state===K.Established)if(this.delegate&&this.delegate.onMessage){const t=new B(e);this.delegate.onMessage(t)}else e.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(e){if(this.logger.log("Session.onNotifyRequest"),this.state===K.Established){if(this.onNotify){const t=new G(e);return void this.onNotify(t)}if(this.delegate&&this.delegate.onNotify){const t=new G(e);this.delegate.onNotify(t)}else e.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(e){if(this.logger.log("Session.onPrackRequest"),this.state===K.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(e){if(this.logger.log("Session.onReferRequest"),this.state!==K.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!e.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void e.reject();const t=new V(e,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),t.accept().then(()=>t.makeInviter(this._referralInviterOptions).invite()).catch(e=>{this.logger.error(e.message)}))}generateResponseOfferAnswer(e,t){if(this.dialog)return this.generateResponseOfferAnswerInDialog(t);const s=H(e.message);return s&&"session"===s.contentDisposition?this.setOfferAndGetAnswer(s,t):this.getOffer(t)}generateResponseOfferAnswerInDialog(e){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case O.Initial:return this.getOffer(e);case O.HaveLocalOffer:return Promise.resolve(void 0);case O.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,e);case O.Stable:return this.state!==K.Established?Promise.resolve(void 0):this.getOffer(e);case O.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(e){const t=this.setupSessionDescriptionHandler(),s=e.sessionDescriptionHandlerOptions,i=e.sessionDescriptionHandlerModifiers;try{return t.getDescription(s,i).then(e=>k(e)).catch(e=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const t=e instanceof Error?e:new Error("Session.getOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.getOffer: SDH getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}rollbackOffer(){const e=this.setupSessionDescriptionHandler();if(void 0===e.rollbackDescription)return Promise.resolve();try{return e.rollbackDescription().catch(e=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const t=e instanceof Error?e:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setAnswer(e,t){const s=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,n=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new i)}catch(e){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,r,n).catch(e=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const t=e instanceof Error?e:new Error("Session.setAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setAnswer: SDH setDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setOfferAndGetAnswer(e,t){const s=this.setupSessionDescriptionHandler(),r=t.sessionDescriptionHandlerOptions,n=t.sessionDescriptionHandlerModifiers;try{if(!s.hasDescription(e.contentType))return Promise.reject(new i)}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}try{return s.setDescription(e.content,r,n).then(()=>s.getDescription(r,n)).then(e=>k(e)).catch(e=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const t=e instanceof Error?e:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(t.message),t})}catch(e){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const t=e instanceof Error?e:new Error(e);return this.logger.error(t.message),Promise.reject(t)}}setSessionDescriptionHandler(e){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=e}setupSessionDescriptionHandler(){var e;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case K.Initial:e!==K.Establishing&&e!==K.Established&&e!==K.Terminating&&e!==K.Terminated&&t();break;case K.Establishing:e!==K.Established&&e!==K.Terminating&&e!==K.Terminated&&t();break;case K.Established:e!==K.Terminating&&e!==K.Terminated&&t();break;case K.Terminating:e!==K.Terminated&&t();break;case K.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===K.Terminated&&this.dispose()}copyRequestOptions(e={}){return{extraHeaders:e.extraHeaders?e.extraHeaders.slice():void 0,body:e.body?{contentDisposition:e.body.contentDisposition||"render",contentType:e.body.contentType||"text/plain",content:e.body.content||""}:void 0}}getReasonHeaderValue(e,t){const s=e;let i=C(e);return!i&&t&&(i=t),"SIP;cause="+s+';text="'+i+'"'}referExtraHeaders(e){const t=[];return t.push("Referred-By: <"+this.userAgent.configuration.uri+">"),t.push("Contact: "+this._contact),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),t.push("Refer-To: "+e),t}referToString(e){let t;if(e instanceof f)t=e.toString();else{if(!e.dialog)throw new Error("Dialog undefined.");const s=e.remoteIdentity.friendlyName,i=e.dialog.remoteTarget.toString(),r=e.dialog.callId,n=e.dialog.remoteTag,o=e.dialog.localTag;t=`"${s}" <${i}?Replaces=${encodeURIComponent(`${r};to-tag=${n};from-tag=${o}`)}>`}return t}}!function(e){e.Required="Required",e.Supported="Supported",e.Unsupported="Unsupported"}(W=W||(W={}));const z={"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};class J extends Y{constructor(e,t){super(e),this.incomingInviteRequest=t,this.disposed=!1,this.expiresTimer=void 0,this.isCanceled=!1,this.rel100="none",this.rseq=Math.floor(1e4*Math.random()),this.userNoAnswerTimer=void 0,this.waitingForPrack=!1,this.logger=e.getLogger("sip.Invitation");const s=this.incomingInviteRequest.message,i=s.getHeader("require");i&&i.toLowerCase().includes("100rel")&&(this.rel100="required");const r=s.getHeader("supported");if(r&&r.toLowerCase().includes("100rel")&&(this.rel100="supported"),s.toTag=t.toTag,"string"!=typeof s.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{t.reject({statusCode:480}),this.stateTransition(K.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),s.hasHeader("expires")){const e=1e3*Number(s.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===K.Initial&&(t.reject({statusCode:487}),this.stateTransition(K.Terminated))},e)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=b.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=s.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=s.body,this._rendertype=s.getHeader("Content-Type")),this._id=s.callId+s.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.expiresTimer&&(clearTimeout(this.expiresTimer),this.expiresTimer=void 0),this.userNoAnswerTimer&&(clearTimeout(this.userNoAnswerTimer),this.userNoAnswerTimer=void 0),this.prackNeverArrived(),this.state){case K.Initial:case K.Establishing:return this.reject().then(()=>super.dispose());case K.Established:case K.Terminating:case K.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get autoSendAnInitialProvisionalResponse(){return"required"!==this.rel100&&this.userAgent.configuration.sendInitialProvisionalResponse}get body(){return this.incomingInviteRequest.message.body}get localIdentity(){return this.request.to}get remoteIdentity(){return this.request.from}get request(){return this.incomingInviteRequest.message}accept(e={}){if(this.logger.log("Invitation.accept"),this.state!==K.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.stateTransition(K.Establishing),this.sendAccept(e).then(({message:e,session:t})=>{t.delegate={onAck:e=>this.onAckRequest(e),onAckTimeout:()=>this.onAckTimeout(),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=t,this.stateTransition(K.Established),this._replacee&&this._replacee._bye()}).catch(e=>this.handleResponseError(e))}progress(e={}){if(this.logger.log("Invitation.progress"),this.state!==K.Initial){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||180;if(t<100||t>199)throw new TypeError("Invalid statusCode: "+t);return e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===e.statusCode?this.sendProgressTrying().then(()=>{}).catch(e=>this.handleResponseError(e)):"required"===this.rel100||"supported"===this.rel100&&e.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===W.Required?this.sendProgressReliableWaitForPrack(e).then(()=>{}).catch(e=>this.handleResponseError(e)):this.sendProgress(e).then(()=>{}).catch(e=>this.handleResponseError(e))}reject(e={}){if(this.logger.log("Invitation.reject"),this.state!==K.Initial&&this.state!==K.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}const t=e.statusCode||480,s=e.reasonPhrase?e.reasonPhrase:C(t),i=e.extraHeaders||[];if(t<300||t>699)throw new TypeError("Invalid statusCode: "+t);const r=e.body?k(e.body):void 0;return t<400?this.incomingInviteRequest.redirect([],{statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}):this.incomingInviteRequest.reject({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r}),this.stateTransition(K.Terminated),Promise.resolve()}_onCancel(e){if(this.logger.log("Invitation._onCancel"),this.state===K.Initial||this.state===K.Establishing){if(this.delegate&&this.delegate.onCancel){const t=new d(e);this.delegate.onCancel(t)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(K.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(e){if(!this.dialog)throw new Error("Dialog undefined.");const t=H(e.message);if(!t||"session"!==t.contentDisposition)return Promise.resolve(void 0);const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case O.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case O.Stable:return this.setAnswer(t,s).then(()=>{});case O.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case O.HaveRemoteOffer:return this.setOfferAndGetAnswer(t,s);case O.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(e){let t=480;if(e instanceof Error?this.logger.error(e.message):this.logger.error(e),e instanceof i?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),t=415):e instanceof n?this.logger.error("A session description handler occurred while sending response"):e instanceof o?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):e instanceof M&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===K.Initial||this.state===K.Establishing)try{this.incomingInviteRequest.reject({statusCode:t}),this.stateTransition(K.Terminated)}catch(e){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),e}if(!this.isCanceled)throw e;this.logger.warn("An error occurred while attempting to formulate and send a response to an incoming INVITE. However a CANCEL was received and processed while doing so which can (and often does) result in errors occurring as the session terminates in the meantime. Said error is being ignored.")}onAckTimeout(){if(this.logger.log("Invitation.onAckTimeout"),!this.dialog)throw new Error("Dialog undefined.");this.logger.log("No ACK received for an extended period of time, terminating session"),this.dialog.bye(),this.stateTransition(K.Terminated)}sendAccept(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,t)).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:s})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.accept({statusCode:200,body:e,extraHeaders:s})))}sendProgress(e={}){const t=e.statusCode||180,s=e.reasonPhrase,i=(e.extraHeaders||[]).slice(),r=e.body?k(e.body):void 0;if(183===t&&!r)return this.sendProgressWithSDP(e);try{const e=this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:r});return this._dialog=e.session,Promise.resolve(e)}catch(e){return Promise.reject(e)}}sendProgressWithSDP(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:e})).then(e=>(this._dialog=e.session,e))}sendProgressReliable(e={}){return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push("Require: 100rel"),e.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(e)}sendProgressReliableWaitForPrack(e={}){const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},s=e.statusCode||183,i=e.reasonPhrase,r=(e.extraHeaders||[]).slice();let n;return r.push("Require: 100rel"),r.push("RSeq: "+this.rseq++),new Promise((e,a)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,t).then(e=>(n=e,this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n}))).then(t=>{let c,h;this._dialog=t.session,t.session.delegate={onPrack:s=>{c=s,clearTimeout(d),clearTimeout(u),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(c).then(s=>{try{h=c.accept({statusCode:200,body:s}),this.prackArrived(),e({prackRequest:c,prackResponse:h,progressResponse:t})}catch(e){a(e)}}).catch(e=>a(e)))}};const d=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(u),this.reject({statusCode:504}).then(()=>a(new o)).catch(e=>a(e)))},64*U.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:s,reasonPhrase:i,extraHeaders:r,body:n})}catch(e){return this.waitingForPrack=!1,void a(e)}u=setTimeout(l,g*=2)};let g=U.T1,u=setTimeout(l,g)}).catch(e=>{this.waitingForPrack=!1,a(e)})})}sendProgressTrying(){try{const e=this.incomingInviteRequest.trying();return Promise.resolve(e)}catch(e){return Promise.reject(e)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((e,t)=>{this.waitingForPrackResolve=e,this.waitingForPrackReject=t}),this.waitingForPrackPromise}prackArrived(){this.waitingForPrackResolve&&this.waitingForPrackResolve(),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}prackNeverArrived(){this.waitingForPrackReject&&this.waitingForPrackReject(new o),this.waitingForPrackPromise=void 0,this.waitingForPrackResolve=void 0,this.waitingForPrackReject=void 0}}class Z extends Y{constructor(e,t,s={}){super(e,s),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=e.getLogger("sip.Inviter"),this.earlyMedia=void 0!==s.earlyMedia?s.earlyMedia:this.earlyMedia,this.fromTag=E(),this.inviteWithoutSdp=void 0!==s.inviteWithoutSdp?s.inviteWithoutSdp:this.inviteWithoutSdp;const i=Object.assign({},s);i.params=Object.assign({},s.params);const r=s.anonymous||!1,n=e.contact.toString({anonymous:r,outbound:r?!e.contact.tempGruu:!e.contact.pubGruu});r&&e.configuration.uri&&(i.params.fromDisplayName="Anonymous",i.params.fromUri="sip:anonymous@anonymous.invalid");let o=e.userAgentCore.configuration.aor;if(i.params.fromUri&&(o="string"==typeof i.params.fromUri?b.URIParse(i.params.fromUri):i.params.fromUri),!o)throw new TypeError("Invalid from URI: "+i.params.fromUri);let a=t;if(i.params.toUri&&(a="string"==typeof i.params.toUri?b.URIParse(i.params.toUri):i.params.toUri),!a)throw new TypeError("Invalid to URI: "+i.params.toUri);const c=Object.assign({},i.params);c.fromTag=this.fromTag;const h=(i.extraHeaders||[]).slice();r&&e.configuration.uri&&(h.push("P-Preferred-Identity: "+e.configuration.uri.toString()),h.push("Privacy: id")),h.push("Contact: "+n),h.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.configuration.sipExtension100rel===W.Required&&h.push("Require: 100rel"),e.configuration.sipExtensionReplaces===W.Required&&h.push("Require: replaces"),i.extraHeaders=h;this.outgoingRequestMessage=e.userAgentCore.makeOutgoingRequestMessage(F.INVITE,t,o,a,c,h,undefined),this._contact=n,this._referralInviterOptions=i,this._renderbody=s.renderbody,this._rendertype=s.rendertype,s.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=s.sessionDescriptionHandlerModifiers),s.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=s.sessionDescriptionHandlerOptions),s.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=s.sessionDescriptionHandlerModifiersReInvite),s.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=s.sessionDescriptionHandlerOptionsReInvite),this._id=this.outgoingRequestMessage.callId+this.fromTag,this.userAgent._sessions[this._id]=this}dispose(){if(this.disposed)return Promise.resolve();switch(this.disposed=!0,this.disposeEarlyMedia(),this.state){case K.Initial:case K.Establishing:return this.cancel().then(()=>super.dispose());case K.Established:case K.Terminating:case K.Terminated:return super.dispose();default:throw new Error("Unknown state.")}}get body(){return this.outgoingRequestMessage.body}get localIdentity(){return this.outgoingRequestMessage.from}get remoteIdentity(){return this.outgoingRequestMessage.to}get request(){return this.outgoingRequestMessage}cancel(e={}){if(this.logger.log("Inviter.cancel"),this.state!==K.Initial&&this.state!==K.Establishing){const e=new Error(`Invalid session state ${this.state}`);return this.logger.error(e.message),Promise.reject(e)}if(this.isCanceled=!0,this.stateTransition(K.Terminating),this.outgoingInviteRequest){let t;e.statusCode&&e.reasonPhrase&&(t=function(e,t){if(e&&e<200||e>699)throw new TypeError("Invalid statusCode: "+e);if(e)return"SIP;cause="+e+';text="'+(C(e)||t)+'"'}(e.statusCode,e.reasonPhrase)),this.outgoingInviteRequest.cancel(t,e)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(K.Terminated);return Promise.resolve()}invite(e={}){if(this.logger.log("Inviter.invite"),this.state!==K.Initial)return super.invite(e);if(e.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=e.sessionDescriptionHandlerModifiers),e.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=e.sessionDescriptionHandlerOptions),e.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(K.Establishing),Promise.resolve(this.sendInvite(e));const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(t).then(t=>(this.outgoingRequestMessage.body={body:t.content,contentType:t.contentType},this.stateTransition(K.Establishing),this.sendInvite(e))).catch(e=>{throw this.logger.log(e.message),this.state!==K.Terminated&&this.stateTransition(K.Terminated),e})}sendInvite(e={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:t=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(t)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(t),void this.stateTransition(K.Terminated)):(this.notifyReferer(t),void this.onAccept(t).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t)})),onProgress:t=>{this.isCanceled||(this.notifyReferer(t),this.onProgress(t).catch(()=>{this.disposeEarlyMedia()}).then(()=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)}))},onRedirect:t=>{this.notifyReferer(t),this.onRedirect(t),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t)},onReject:t=>{this.notifyReferer(t),this.onReject(t),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t)},onTrying:t=>{this.notifyReferer(t),this.onTrying(t),e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(e=>{e.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(e){if(!this._referred)return;if(!(this._referred instanceof Y))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!e.message.statusCode)throw new Error("Status code undefined.");if(!e.message.reasonPhrase)throw new Error("Reason phrase undefined.");const t=`SIP/2.0 ${e.message.statusCode} ${e.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:t}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(e){if(this.logger.log("Inviter.onAccept"),this.state!==K.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const t=e.message,s=e.session;switch(t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=b.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity"))),s.delegate={onAck:e=>this.onAckRequest(e),onBye:e=>this.onByeRequest(e),onInfo:e=>this.onInfoRequest(e),onInvite:e=>this.onInviteRequest(e),onMessage:e=>this.onMessageRequest(e),onNotify:e=>this.onNotifyRequest(e),onPrack:e=>this.onPrackRequest(e),onRefer:e=>this.onReferRequest(e)},this._dialog=s,s.signalingState){case O.Initial:case O.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(K.Terminated),Promise.reject(new Error("Bad Media Description"));case O.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,t).then(t=>{e.ack({body:t}),this.stateTransition(K.Established)}).catch(t=>{throw this.ackAndBye(e,488,"Invalid session description"),this.stateTransition(K.Terminated),t})}case O.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const t=this.earlyMediaSessionDescriptionHandlers.get(s.id);if(!t)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(t),this.earlyMediaSessionDescriptionHandlers.delete(s.id),e.ack(),this.stateTransition(K.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==s){if(this.earlyMedia){const e="You have set the 'earlyMedia' option to 'true' which requires that your INVITE requests do not fork and yet this INVITE request did in fact fork. Consequentially and not surprisingly the end point which accepted the INVITE (confirmed dialog) does not match the end point with which early media has been setup (early dialog) and thus this session is unable to proceed. In accordance with the SIP specifications, the SIP servers your end point is connected to determine if an INVITE forks and the forking behavior of those servers cannot be controlled by this library. If you wish to use early media with this library you must configure those servers accordingly. Alternatively you may set the 'earlyMedia' to 'false' which will allow this library to function with any INVITE requests which do fork.";this.logger.error(e)}const t=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(K.Terminated),Promise.reject(t)}return e.ack(),this.stateTransition(K.Established),Promise.resolve()}const t=s.answer;if(!t)throw new Error("Answer is undefined.");const i={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(t,i).then(()=>{let t;this._renderbody&&this._rendertype&&(t={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),e.ack(t),this.stateTransition(K.Established)}).catch(t=>{throw this.logger.error(t.message),this.ackAndBye(e,488,"Not Acceptable Here"),this.stateTransition(K.Terminated),t})}case O.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(e){var t;if(this.logger.log("Inviter.onProgress"),this.state!==K.Establishing)return this.logger.error(`Progress received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));if(!this.outgoingInviteRequest)throw new Error("Outgoing INVITE request undefined.");const s=e.message,i=e.session;s.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=b.nameAddrHeaderParse(s.getHeader("P-Asserted-Identity")));const r=s.getHeader("require"),n=s.getHeader("rseq"),o=!!(r&&r.includes("100rel")&&n?Number(n):void 0),a=[];switch(o&&a.push("RAck: "+s.getHeader("rseq")+" "+s.getHeader("cseq")),i.signalingState){case O.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),e.prack({extraHeaders:a})),Promise.resolve();case O.HaveLocalOffer:return o&&e.prack({extraHeaders:a}),Promise.resolve();case O.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const r=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(t=this.delegate)||void 0===t?void 0:t.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(r,!0),this.earlyMediaSessionDescriptionHandlers.set(i.id,r),r.setDescription(s.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>r.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(t=>{const s={contentDisposition:"session",contentType:t.contentType,content:t.body};e.prack({extraHeaders:a,body:s})}).catch(e=>{throw this.stateTransition(K.Terminated),e})}case O.Stable:if(o&&e.prack({extraHeaders:a}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=i;const e=i.answer;if(!e)throw new Error("Answer is undefined.");const t={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,t).catch(e=>{throw this.stateTransition(K.Terminated),e})}return Promise.resolve();case O.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(e){this.logger.log("Inviter.onRedirect"),this.state===K.Establishing||this.state===K.Terminating?this.stateTransition(K.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(e){this.logger.log("Inviter.onReject"),this.state===K.Establishing||this.state===K.Terminating?this.stateTransition(K.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(e){this.logger.log("Inviter.onTrying"),this.state===K.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var X,Q,ee,te,se,ie,re;!function(e){e.Initial="Initial",e.Registered="Registered",e.Unregistered="Unregistered",e.Terminated="Terminated"}(X=X||(X={}));class ne{constructor(e,t={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=X.Initial,this._waiting=!1,this._stateEventEmitter=new l,this._waitingEventEmitter=new l,this.userAgent=e;const s=e.configuration.uri.clone();if(s.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},ne.defaultOptions()),{registrar:s}),ne.stripUndefinedProperties(t)),this.options.extraContactHeaderParams=(this.options.extraContactHeaderParams||[]).slice(),this.options.extraHeaders=(this.options.extraHeaders||[]).slice(),!this.options.registrar)throw new Error("Registrar undefined.");if(this.options.registrar=this.options.registrar.clone(),this.options.regId&&!this.options.instanceId?this.options.instanceId=this.userAgent.instanceId:!this.options.regId&&this.options.instanceId&&(this.options.regId=1),this.options.instanceId&&-1===b.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const i=this.options.registrar,r=this.options.params&&this.options.params.fromUri||e.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||e.configuration.uri,o=this.options.params||{},a=(t.extraHeaders||[]).slice();if(this.request=e.userAgentCore.makeOutgoingRequestMessage(F.REGISTER,i,r,n,o,a,void 0),this.expires=this.options.expires||ne.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||ne.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=e.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];if("registrar"===e)this.logger.log("· "+e+": "+t);else this.logger.log("· "+e+": "+JSON.stringify(t))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:ne.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new f("sip","anonymous","anonymous.invalid"),refreshFrequency:ne.defaultRefreshFrequency}}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get contacts(){return this._contacts.slice()}get retryAfter(){return this._retryAfter}get state(){return this._state}get stateChange(){return this._stateEventEmitter}dispose(){return this.disposed?Promise.resolve():(this.disposed=!0,this.logger.log(`Registerer ${this.id} in state ${this.state} is being disposed`),delete this.userAgent._registerers[this.id],new Promise(e=>{const t=()=>{if(!this.waiting&&this._state===X.Registered)return this.stateChange.addListener(()=>{this.terminated(),e()},{once:!0}),void this.unregister();this.terminated(),e()};this.waiting?this.waitingChange.addListener(()=>{t()},{once:!0}):t()}))}register(e={}){if(this.state===X.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new r("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}e.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),e.requestOptions));const t=(this.options.extraHeaders||[]).slice();t.push("Contact: "+this.generateContactHeader(this.expires)),t.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),this.request.extraHeaders=t,this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{let s;t.message.hasHeader("expires")&&(s=Number(t.message.getHeader("expires"))),this._contacts=t.message.getHeaders("contact");let i,r=this._contacts.length;if(!r)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;r--;){if(i=t.message.parseHeader("contact",r),!i)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&m(i.uri,this.userAgent.contact.pubGruu)){s=Number(i.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(i.uri.user===this.userAgent.contact.uri.user){s=Number(i.getParam("expires"));break}}else if(m(i.uri,this.userAgent.contact.uri)){s=Number(i.getParam("expires"));break}i=void 0}if(void 0===i)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===s)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(i.hasParam("temp-gruu")){const e=i.getParam("temp-gruu");e&&(this.userAgent.contact.tempGruu=b.URIParse(e.replace(/"/g,"")))}if(i.hasParam("pub-gruu")){const e=i.getParam("pub-gruu");e&&(this.userAgent.contact.pubGruu=b.URIParse(e.replace(/"/g,"")))}this.registered(s),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{if(423===t.message.statusCode)return t.message.hasHeader("min-expires")?(this.expires=Number(t.message.getHeader("min-expires")),this.waitingToggle(!1),void this.register()):(this.logger.error("423 response received for REGISTER without Min-Expires, dropping response"),this.unregistered(),void this.waitingToggle(!1));this.logger.warn(`Failed to register, status code ${t.message.statusCode}`);let s=NaN;if(500===t.message.statusCode||503===t.message.statusCode){const e=t.message.getHeader("retry-after");e&&(s=Number.parseInt(e,void 0))}this._retryAfter=isNaN(s)?void 0:s,this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}unregister(e={}){if(this.state===X.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==X.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const e=new r("REGISTER request already in progress, waiting for final response");return Promise.reject(e)}this._state===X.Registered||e.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const t=(e.requestOptions&&e.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=t,e.all?(t.push("Contact: *"),t.push("Expires: 0")):t.push("Contact: "+this.generateContactHeader(0)),this.request.cseq++,this.request.setHeader("cseq",this.request.cseq+" REGISTER"),void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),this.waitingToggle(!0);const s=this.userAgent.userAgentCore.register(this.request,{onAccept:t=>{this._contacts=t.message.getHeaders("contact"),this.unregistered(),e.requestDelegate&&e.requestDelegate.onAccept&&e.requestDelegate.onAccept(t),this.waitingToggle(!1)},onProgress:t=>{e.requestDelegate&&e.requestDelegate.onProgress&&e.requestDelegate.onProgress(t)},onRedirect:t=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),e.requestDelegate&&e.requestDelegate.onRedirect&&e.requestDelegate.onRedirect(t),this.waitingToggle(!1)},onReject:t=>{this.logger.error(`Unregister rejected with status code ${t.message.statusCode}`),this.unregistered(),e.requestDelegate&&e.requestDelegate.onReject&&e.requestDelegate.onReject(t),this.waitingToggle(!1)},onTrying:t=>{e.requestDelegate&&e.requestDelegate.onTrying&&e.requestDelegate.onTrying(t)}});return Promise.resolve(s)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(e){let t=this.userAgent.contact.toString({register:!0});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(e=>{t+=";"+e}),t+=";expires="+e,t}registered(e){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*e*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*e),this._state!==X.Registered&&this.stateTransition(X.Registered)}unregistered(){this.clearTimers(),this._state!==X.Unregistered&&this.stateTransition(X.Unregistered)}terminated(){this.clearTimers(),this._state!==X.Terminated&&this.stateTransition(X.Terminated)}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case X.Initial:e!==X.Registered&&e!==X.Unregistered&&e!==X.Terminated&&t();break;case X.Registered:e!==X.Unregistered&&e!==X.Terminated&&t();break;case X.Unregistered:e!==X.Registered&&e!==X.Terminated&&t();break;case X.Terminated:t();break;default:throw new Error("Unrecognized state.")}this._state=e,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),e===X.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(e){if(this._waiting===e)throw new Error(`Invalid waiting transition from ${this._waiting} to ${e}`);this._waiting=e,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let e="An attempt was made to send a REGISTER request while a prior one was still in progress.";e+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",e+=" from the registrar for the previous one or the previous REGISTER request has timed out.",e+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",e+=" sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.",this.logger.warn("An attempt was made to send a REGISTER request while a prior one was still in progress. RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response from the registrar for the previous one or the previous REGISTER request has timed out. Note that if the transport disconnects, you still must wait for the prior request to time out before sending a new REGISTER request or alternatively dispose of the current Registerer and create a new Registerer.")}stateError(){let e=`An attempt was made to send a REGISTER request when the Registerer ${this.state===X.Terminated?"is in 'Terminated' state":"has been disposed"}.`;e+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",e+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(e)}}ne.defaultExpires=600,ne.defaultRefreshFrequency=99,function(e){e.Initial="Initial",e.NotifyWait="NotifyWait",e.Pending="Pending",e.Active="Active",e.Terminated="Terminated"}(Q=Q||(Q={})),function(e){e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Disconnected="Disconnected"}(ee=ee||(ee={})),function(e){e.Started="Started",e.Stopped="Stopped"}(te=te||(te={}));class oe{constructor(){this._dataLength=0,this._bufferLength=0,this._state=new Int32Array(4),this._buffer=new ArrayBuffer(68),this._buffer8=new Uint8Array(this._buffer,0,68),this._buffer32=new Uint32Array(this._buffer,0,17),this.start()}static hashStr(e,t=!1){return this.onePassHasher.start().appendStr(e).end(t)}static hashAsciiStr(e,t=!1){return this.onePassHasher.start().appendAsciiStr(e).end(t)}static _hex(e){const t=oe.hexChars,s=oe.hexOut;let i,r,n,o;for(o=0;o<4;o+=1)for(r=8*o,i=e[o],n=0;n<8;n+=2)s[r+1+n]=t.charAt(15&i),i>>>=4,s[r+0+n]=t.charAt(15&i),i>>>=4;return s.join("")}static _md5cycle(e,t){let s=e[0],i=e[1],r=e[2],n=e[3];s+=(i&r|~i&n)+t[0]-680876936|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[1]-389564586|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[2]+606105819|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[3]-1044525330|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[4]-176418897|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[5]+1200080426|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[6]-1473231341|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[7]-45705983|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[8]+1770035416|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[9]-1958414417|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[10]-42063|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[11]-1990404162|0,i=(i<<22|i>>>10)+r|0,s+=(i&r|~i&n)+t[12]+1804603682|0,s=(s<<7|s>>>25)+i|0,n+=(s&i|~s&r)+t[13]-40341101|0,n=(n<<12|n>>>20)+s|0,r+=(n&s|~n&i)+t[14]-1502002290|0,r=(r<<17|r>>>15)+n|0,i+=(r&n|~r&s)+t[15]+1236535329|0,i=(i<<22|i>>>10)+r|0,s+=(i&n|r&~n)+t[1]-165796510|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[6]-1069501632|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[11]+643717713|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[0]-373897302|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[5]-701558691|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[10]+38016083|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[15]-660478335|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[4]-405537848|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[9]+568446438|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[14]-1019803690|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[3]-187363961|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[8]+1163531501|0,i=(i<<20|i>>>12)+r|0,s+=(i&n|r&~n)+t[13]-1444681467|0,s=(s<<5|s>>>27)+i|0,n+=(s&r|i&~r)+t[2]-51403784|0,n=(n<<9|n>>>23)+s|0,r+=(n&i|s&~i)+t[7]+1735328473|0,r=(r<<14|r>>>18)+n|0,i+=(r&s|n&~s)+t[12]-1926607734|0,i=(i<<20|i>>>12)+r|0,s+=(i^r^n)+t[5]-378558|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[8]-2022574463|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[11]+1839030562|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[14]-35309556|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[1]-1530992060|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[4]+1272893353|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[7]-155497632|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[10]-1094730640|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[13]+681279174|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[0]-358537222|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[3]-722521979|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[6]+76029189|0,i=(i<<23|i>>>9)+r|0,s+=(i^r^n)+t[9]-640364487|0,s=(s<<4|s>>>28)+i|0,n+=(s^i^r)+t[12]-421815835|0,n=(n<<11|n>>>21)+s|0,r+=(n^s^i)+t[15]+530742520|0,r=(r<<16|r>>>16)+n|0,i+=(r^n^s)+t[2]-995338651|0,i=(i<<23|i>>>9)+r|0,s+=(r^(i|~n))+t[0]-198630844|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[7]+1126891415|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[14]-1416354905|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[5]-57434055|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[12]+1700485571|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[3]-1894986606|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[10]-1051523|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[1]-2054922799|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[8]+1873313359|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[15]-30611744|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[6]-1560198380|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[13]+1309151649|0,i=(i<<21|i>>>11)+r|0,s+=(r^(i|~n))+t[4]-145523070|0,s=(s<<6|s>>>26)+i|0,n+=(i^(s|~r))+t[11]-1120210379|0,n=(n<<10|n>>>22)+s|0,r+=(s^(n|~i))+t[2]+718787259|0,r=(r<<15|r>>>17)+n|0,i+=(n^(r|~s))+t[9]-343485551|0,i=(i<<21|i>>>11)+r|0,e[0]=s+e[0]|0,e[1]=i+e[1]|0,e[2]=r+e[2]|0,e[3]=n+e[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(oe.stateIdentity),this}appendStr(e){const t=this._buffer8,s=this._buffer32;let i,r,n=this._bufferLength;for(r=0;r<e.length;r+=1){if(i=e.charCodeAt(r),i<128)t[n++]=i;else if(i<2048)t[n++]=(i>>>6)+192,t[n++]=63&i|128;else if(i<55296||i>56319)t[n++]=(i>>>12)+224,t[n++]=i>>>6&63|128,t[n++]=63&i|128;else{if(i=1024*(i-55296)+(e.charCodeAt(++r)-56320)+65536,i>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");t[n++]=(i>>>18)+240,t[n++]=i>>>12&63|128,t[n++]=i>>>6&63|128,t[n++]=63&i|128}n>=64&&(this._dataLength+=64,oe._md5cycle(this._state,s),n-=64,s[0]=s[16])}return this._bufferLength=n,this}appendAsciiStr(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e.charCodeAt(n++);if(r<64)break;this._dataLength+=64,oe._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}appendByteArray(e){const t=this._buffer8,s=this._buffer32;let i,r=this._bufferLength,n=0;for(;;){for(i=Math.min(e.length-n,64-r);i--;)t[r++]=e[n++];if(r<64)break;this._dataLength+=64,oe._md5cycle(this._state,s),r=0}return this._bufferLength=r,this}getState(){const 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]]}}setState(e){const t=e.buffer,s=e.state,i=this._state;let r;for(this._dataLength=e.length,this._bufferLength=e.buflen,i[0]=s[0],i[1]=s[1],i[2]=s[2],i[3]=s[3],r=0;r<t.length;r+=1)this._buffer8[r]=t.charCodeAt(r)}end(e=!1){const t=this._bufferLength,s=this._buffer8,i=this._buffer32,r=1+(t>>2);let n;if(this._dataLength+=t,s[t]=128,s[t+1]=s[t+2]=s[t+3]=0,i.set(oe.buffer32Identity.subarray(r),r),t>55&&(oe._md5cycle(this._state,i),i.set(oe.buffer32Identity)),n=8*this._dataLength,n<=4294967295)i[14]=n;else{const e=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===e)return;const t=parseInt(e[2],16),s=parseInt(e[1],16)||0;i[14]=t,i[15]=s}return oe._md5cycle(this._state,i),e?this._state:oe._hex(this._state)}}function ae(e){return oe.hashStr(e)}oe.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),oe.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),oe.hexChars="0123456789abcdef",oe.hexOut=[],oe.onePassHasher=new oe,"5d41402abc4b2a76b9719d911017c592"!==oe.hashStr("hello")&&console.error("Md5 self test failed.");class ce{constructor(e,t,s,i){this.logger=e.getLogger("sipjs.digestauthentication"),this.username=s,this.password=i,this.ha1=t,this.nc=0,this.ncHex="00000000"}authenticate(e,t,s){if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return this.logger.warn("challenge with Digest algorithm different than 'MD5', authentication aborted"),!1}else this.algorithm="MD5";if(!this.realm)return this.logger.warn("challenge without Digest realm, authentication aborted"),!1;if(!this.nonce)return this.logger.warn("challenge without Digest nonce, authentication aborted"),!1;if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return this.logger.warn("challenge without Digest qop different than 'auth' or 'auth-int', authentication aborted"),!1;this.qop="auth-int"}else this.qop=void 0;return this.method=e.method,this.uri=e.ruri,this.cnonce=S(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(s),!0}toString(){const e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}updateNcHex(){const e=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-e.length)+e}calculateResponse(e){let t,s;t=this.ha1,""!==t&&void 0!==t||(t=ae(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(s=ae(this.method+":"+this.uri),this.response=ae(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+s)):"auth-int"===this.qop?(s=ae(this.method+":"+this.uri+":"+ae(e||"")),this.response=ae(t+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+s)):void 0===this.qop&&(s=ae(this.method+":"+this.uri),this.response=ae(t+":"+this.nonce+":"+s))}}!function(e){e[e.error=0]="error",e[e.warn=1]="warn",e[e.log=2]="log",e[e.debug=3]="debug"}(se=se||(se={}));class he{constructor(e,t,s){this.logger=e,this.category=t,this.label=s}error(e){this.genericLog(se.error,e)}warn(e){this.genericLog(se.warn,e)}log(e){this.genericLog(se.log,e)}debug(e){this.genericLog(se.debug,e)}genericLog(e,t){this.logger.genericLog(e,this.category,this.label,t)}get level(){return this.logger.level}set level(e){this.logger.level=e}}class de{constructor(){this.builtinEnabled=!0,this._level=se.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(e){e>=0&&e<=3?this._level=e:e>3?this._level=3:se.hasOwnProperty(e)?this._level=e:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(e))}get connector(){return this._connector}set connector(e){e?"function"==typeof e?this._connector=e:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(e)):this._connector=void 0}getLogger(e,t){if(t&&3===this.level)return new he(this,e,t);if(this.loggers[e])return this.loggers[e];{const t=new he(this,e);return this.loggers[e]=t,t}}genericLog(e,t,s,i){this.level>=e&&this.builtinEnabled&&this.print(e,t,s,i),this.connector&&this.connector(se[e],t,s,i)}print(e,t,s,i){if("string"==typeof i){const e=[new Date,t];s&&e.push(s),i=e.concat(i).join(" | ")}switch(e){case se.error:console.error(i);break;case se.warn:console.warn(i);break;case se.log:console.log(i);break;case se.debug:console.debug(i)}}}function le(e,t){const s="\r\n";if(t.statusCode<100||t.statusCode>699)throw new TypeError("Invalid statusCode: "+t.statusCode);const i=t.reasonPhrase?t.reasonPhrase:C(t.statusCode);let r="SIP/2.0 "+t.statusCode+" "+i+s;t.statusCode>=100&&t.statusCode,t.statusCode;const n="From: "+e.getHeader("From")+s,o="Call-ID: "+e.callId+s,a="CSeq: "+e.cseq+" "+e.method+s,c=e.getHeaders("via").reduce((e,t)=>e+"Via: "+t+s,"");let h="To: "+e.getHeader("to");if(t.statusCode>100&&!e.parseHeader("to").hasParam("tag")){let e=t.toTag;e||(e=E()),h+=";tag="+e}h+=s;let d="";t.supported&&(d="Supported: "+t.supported.join(", ")+s);let l="";t.userAgent&&(l="User-Agent: "+t.userAgent+s);let g="";return t.extraHeaders&&(g=t.extraHeaders.reduce((e,t)=>e+t.trim()+s,"")),r+=c,r+=n,r+=h,r+=a,r+=o,r+=d,r+=l,r+=g,t.body?(r+="Content-Type: "+t.body.contentType+s,r+="Content-Length: "+_(t.body.content)+s+s,r+=t.body.content):r+="Content-Length: 0\r\n\r\n",{message:r}}!function(e){function t(e,t){let s=t,i=0,r=0;if(e.substring(s,s+2).match(/(^\r\n)/))return-2;for(;0===i;){if(r=e.indexOf("\r\n",s),-1===r)return r;!e.substring(r+2,r+4).match(/(^\r\n)/)&&e.charAt(r+2).match(/(^\s+)/)?s=r+2:i=r}return i}function s(e,t,s,i){const r=t.indexOf(":",s),n=t.substring(s,r).trim(),o=t.substring(r+1,i).trim();let a;switch(n.toLowerCase()){case"via":case"v":e.addHeader("via",o),1===e.getHeaders("via").length?(a=e.parseHeader("Via"),a&&(e.via=a,e.viaBranch=a.branch)):a=0;break;case"from":case"f":e.setHeader("from",o),a=e.parseHeader("from"),a&&(e.from=a,e.fromTag=a.getParam("tag"));break;case"to":case"t":e.setHeader("to",o),a=e.parseHeader("to"),a&&(e.to=a,e.toTag=a.getParam("tag"));break;case"record-route":if(a=b.parse(o,"Record_Route"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("record-route",o.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",o),a=e.parseHeader("call-id"),a&&(e.callId=o);break;case"contact":case"m":if(a=b.parse(o,"Contact"),-1===a){a=void 0;break}if(!(a instanceof Array)){a=void 0;break}a.forEach(t=>{e.addHeader("contact",o.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",o),a=e.parseHeader("content-length");break;case"content-type":case"c":e.setHeader("content-type",o),a=e.parseHeader("content-type");break;case"cseq":e.setHeader("cseq",o),a=e.parseHeader("cseq"),a&&(e.cseq=a.value),e instanceof $&&(e.method=a.method);break;case"max-forwards":e.setHeader("max-forwards",o),a=e.parseHeader("max-forwards");break;case"www-authenticate":e.setHeader("www-authenticate",o),a=e.parseHeader("www-authenticate");break;case"proxy-authenticate":e.setHeader("proxy-authenticate",o),a=e.parseHeader("proxy-authenticate");break;case"refer-to":case"r":e.setHeader("refer-to",o),a=e.parseHeader("refer-to"),a&&(e.referTo=a);break;default:e.addHeader(n.toLowerCase(),o),a=0}return void 0!==a||{error:"error parsing header '"+n+"'"}}e.getHeader=t,e.parseHeader=s,e.parseMessage=function(e,i){let r=0,n=e.indexOf("\r\n");if(-1===n)return void i.warn("no CRLF found, not a SIP message, discarded");const o=e.substring(0,n),a=b.parse(o,"Request_Response");let c,h;if(-1!==a){for(a.status_code?(c=new $,c.statusCode=a.status_code,c.reasonPhrase=a.reason_phrase):(c=new R,c.method=a.method,c.ruri=a.uri),c.data=e,r=n+2;;){if(n=t(e,r),-2===n){h=r+2;break}if(-1===n)return void i.error("malformed message");const o=s(c,e,r,n);if(o&&!0!==o)return void i.error(o.error);r=n+2}return c.hasHeader("content-length")?c.body=e.substr(h,Number(c.getHeader("content-length"))):c.body=e.substring(h),c}i.warn('error parsing first line of SIP message: "'+o+'"')}}(ie=ie||(ie={}));class ge extends s{constructor(e){super(e||"Unspecified transport error.")}}class ue{constructor(e,t,s,i,r){this._transport=e,this._user=t,this._id=s,this._state=i,this.listeners=new Array,this.logger=t.loggerFactory.getLogger(r,s),this.logger.debug(`Constructing ${this.typeToString()} with id ${this.id}.`)}dispose(){this.logger.debug(`Destroyed ${this.typeToString()} with id ${this.id}.`)}get id(){return this._id}get kind(){throw new Error("Invalid kind.")}get state(){return this._state}get transport(){return this._transport}addStateChangeListener(e,t){const s=()=>{this.removeStateChangeListener(s),e()};!0===(null==t?void 0:t.once)?this.listeners.push(s):this.listeners.push(e)}notifyStateChangeListeners(){this.listeners.slice().forEach(e=>e())}removeStateChangeListener(e){this.listeners=this.listeners.filter(t=>t!==e)}logTransportError(e,t){this.logger.error(e.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(t)}send(e){return this.transport.send(e).catch(e=>{if(e instanceof ge)throw this.onTransportError(e),e;let t;throw t=e&&"string"==typeof e.message?new ge(e.message):new ge,this.onTransportError(t),t})}setState(e){this.logger.debug(`State change to "${e}" on ${this.typeToString()} with id ${this.id}.`),this._state=e,this._user.onStateChange&&this._user.onStateChange(e),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class pe extends ue{constructor(e,t,s,i,r){super(t,s,e.viaBranch,i,r),this._request=e,this.user=s}get request(){return this._request}}!function(e){e.Accepted="Accepted",e.Calling="Calling",e.Completed="Completed",e.Confirmed="Confirmed",e.Proceeding="Proceeding",e.Terminated="Terminated",e.Trying="Trying"}(re=re||(re={}));class fe extends pe{constructor(e,t,s){super(e,t,s,re.Proceeding,"sip.transaction.ist")}dispose(){this.stopProgressExtensionTimer(),this.H&&(clearTimeout(this.H),this.H=void 0),this.I&&(clearTimeout(this.I),this.I=void 0),this.L&&(clearTimeout(this.L),this.L=void 0),super.dispose()}get kind(){return"ist"}receiveRequest(e){switch(this.state){case re.Proceeding:if(e.method===F.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")}));break;case re.Accepted:if(e.method===F.INVITE)return;break;case re.Completed:if(e.method===F.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")})}if(e.method===F.ACK)return void this.stateTransition(re.Confirmed);break;case re.Confirmed:case re.Terminated:if(e.method===F.INVITE||e.method===F.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${e.method} request while in state ${this.state}.`;this.logger.warn(t)}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case re.Proceeding:if(e>=100&&e<=199)return this.lastProvisionalResponse=t,e>100&&this.startProgressExtensionTimer(),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 1xx response.")});if(e>=200&&e<=299)return this.lastFinalResponse=t,this.stateTransition(re.Accepted),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});if(e>=300&&e<=699)return this.lastFinalResponse=t,this.stateTransition(re.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send non-2xx final response.")});break;case re.Accepted:if(e>=200&&e<=299)return void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")});break;case re.Completed:case re.Confirmed:case re.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}retransmitAcceptedResponse(){this.state===re.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(e=>{this.logTransportError(e,"Failed to send 2xx response.")})}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e)}typeToString(){return"INVITE server transaction"}stateTransition(e){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case re.Proceeding:t();break;case re.Accepted:case re.Completed:this.state!==re.Proceeding&&t();break;case re.Confirmed:this.state!==re.Completed&&t();break;case re.Terminated:this.state!==re.Accepted&&this.state!==re.Completed&&this.state!==re.Confirmed&&t();break;default:t()}this.stopProgressExtensionTimer(),e===re.Accepted&&(this.L=setTimeout(()=>this.timerL(),U.TIMER_L)),e===re.Completed&&(this.H=setTimeout(()=>this.timerH(),U.TIMER_H)),e===re.Confirmed&&(this.I=setTimeout(()=>this.timerI(),U.TIMER_I)),e===re.Terminated&&this.dispose(),this.setState(e)}startProgressExtensionTimer(){void 0===this.progressExtensionTimer&&(this.progressExtensionTimer=setInterval(()=>{if(this.logger.debug(`Progress extension timer expired for INVITE server transaction ${this.id}.`),!this.lastProvisionalResponse)throw new Error("Last provisional response undefined.");this.send(this.lastProvisionalResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")})},U.PROVISIONAL_RESPONSE_INTERVAL))}stopProgressExtensionTimer(){void 0!==this.progressExtensionTimer&&(clearInterval(this.progressExtensionTimer),this.progressExtensionTimer=void 0)}timerG(){}timerH(){this.logger.debug(`Timer H expired for INVITE server transaction ${this.id}.`),this.state===re.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(re.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(re.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===re.Accepted&&this.stateTransition(re.Terminated)}}class me extends ue{constructor(e,t,s,i,r){super(t,s,me.makeId(e),i,r),this._request=e,this.user=s,e.setViaHeader(this.id,t.protocol)}static makeId(e){if("CANCEL"===e.method){if(!e.branch)throw new Error("Outgoing CANCEL request without a branch.");return e.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class ve extends me{constructor(e,t,s){super(e,t,s,re.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),U.TIMER_F),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.F&&(clearTimeout(this.F),this.F=void 0),this.K&&(clearTimeout(this.K),this.K=void 0),super.dispose()}get kind(){return"nict"}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case re.Trying:if(t>=100&&t<=199)return this.stateTransition(re.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=699)return this.stateTransition(re.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case re.Proceeding:if(t>=100&&t<=199&&this.user.receiveResponse)return this.user.receiveResponse(e);if(t>=200&&t<=699)return this.stateTransition(re.Completed),408===t?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case re.Completed:case re.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const s=`Non-INVITE client transaction received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(re.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case re.Trying:s();break;case re.Proceeding:this.state!==re.Trying&&s();break;case re.Completed:this.state!==re.Trying&&this.state!==re.Proceeding&&s();break;case re.Terminated:this.state!==re.Trying&&this.state!==re.Proceeding&&this.state!==re.Completed&&(t||s());break;default:s()}e===re.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),U.TIMER_K)),e===re.Terminated&&this.dispose(),this.setState(e)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==re.Trying&&this.state!==re.Proceeding||(this.onRequestTimeout(),this.stateTransition(re.Terminated))}timerK(){this.state===re.Completed&&this.stateTransition(re.Terminated)}}class we{constructor(e,t){this.core=e,this.dialogState=t,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(e,t){const s=t.getHeaders("record-route").reverse(),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof p))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=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.");const h=e.from.uri,d=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:n,remoteSequenceNumber:undefined,localURI:h,remoteURI:d,remoteTarget:r,routeSet:s,secure:!1}}static initialDialogStateForUserAgentServer(e,t,s=!1){const i=e.getHeaders("record-route"),r=e.parseHeader("contact");if(!r)throw new Error("Contact undefined.");if(!(r instanceof p))throw new Error("Contact not instance of NameAddrHeader.");const n=r.uri,o=e.cseq,a=e.callId,c=t,h=e.fromTag,d=e.from.uri;return{id:a+c+h,early:s,callId:a,localTag:c,remoteTag:h,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:e.to.uri,remoteURI:d,remoteTarget:n,routeSet:i,secure:!1}}dispose(){this.core.dialogs.delete(this.id)}get id(){return this.dialogState.id}get early(){return this.dialogState.early}get callId(){return this.dialogState.callId}get localTag(){return this.dialogState.localTag}get remoteTag(){return this.dialogState.remoteTag}get localSequenceNumber(){return this.dialogState.localSequenceNumber}get remoteSequenceNumber(){return this.dialogState.remoteSequenceNumber}get localURI(){return this.dialogState.localURI}get remoteURI(){return this.dialogState.remoteURI}get remoteTarget(){return this.dialogState.remoteTarget}get routeSet(){return this.dialogState.routeSet}get secure(){return this.dialogState.secure}get userAgentCore(){return this.core}confirm(){this.dialogState.early=!1}receiveRequest(e){if(e.method!==F.ACK){if(this.remoteSequenceNumber){if(e.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=e.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=e.cseq)}}recomputeRouteSet(e){this.dialogState.routeSet=e.getHeaders("record-route").reverse()}createOutgoingRequestMessage(e,t){const s=this.remoteURI,i=this.remoteTag,r=this.localURI,n=this.localTag,o=this.callId;let a;a=t&&t.cseq?t.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const c=this.remoteTarget,h=this.routeSet,d=t&&t.extraHeaders,l=t&&t.body;return this.userAgentCore.makeOutgoingRequestMessage(e,c,r,s,{callId:o,cseq:a,fromTag:n,toTag:i,routeSet:h},d,l)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(e){return e.method===F.ACK||(!(this.remoteSequenceNumber&&e.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(e,{statusCode:500}),!1))}}class ye extends me{constructor(e,t,s){super(e,t,s,re.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),U.TIMER_B),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send initial outgoing request.")})}dispose(){this.B&&(clearTimeout(this.B),this.B=void 0),this.D&&(clearTimeout(this.D),this.D=void 0),this.M&&(clearTimeout(this.M),this.M=void 0),super.dispose()}get kind(){return"ict"}ackResponse(e){const t=e.toTag;if(!t)throw new Error("To tag undefined.");const s="z9hG4bK"+Math.floor(1e7*Math.random());e.setViaHeader(s,this.transport.protocol),this.ackRetransmissionCache.set(t,e),this.send(e.toString()).catch(e=>{this.logTransportError(e,"Failed to send ACK to 2xx response.")})}receiveResponse(e){const t=e.statusCode;if(!t||t<100||t>699)throw new Error(`Invalid status code ${t}`);switch(this.state){case re.Calling:if(t>=100&&t<=199)return this.stateTransition(re.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(re.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(re.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case re.Proceeding:if(t>=100&&t<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=200&&t<=299)return this.ackRetransmissionCache.set(e.toTag,void 0),this.stateTransition(re.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(e));if(t>=300&&t<=699)return this.stateTransition(re.Completed),this.ack(e),void(this.user.receiveResponse&&this.user.receiveResponse(e));break;case re.Accepted:if(t>=200&&t<=299){if(!this.ackRetransmissionCache.has(e.toTag))return this.ackRetransmissionCache.set(e.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(e));const t=this.ackRetransmissionCache.get(e.toTag);return t?void this.send(t.toString()).catch(e=>{this.logTransportError(e,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case re.Completed:if(t>=300&&t<=699)return void this.ack(e);break;case re.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`Received unexpected ${t} response while in state ${this.state}.`;this.logger.warn(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(re.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(e){const t=this.request.ruri,s=this.request.callId,i=this.request.cseq,r=this.request.getHeader("from"),n=e.getHeader("to"),o=this.request.getHeader("via"),a=this.request.getHeader("route");if(!r)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let c=`ACK ${t} SIP/2.0\r\n`;a&&(c+=`Route: ${a}\r\n`),c+=`Via: ${o}\r\n`,c+=`To: ${n}\r\n`,c+=`From: ${r}\r\n`,c+=`Call-ID: ${s}\r\n`,c+=`CSeq: ${i} ACK\r\n`,c+="Max-Forwards: 70\r\n",c+="Content-Length: 0\r\n\r\n",this.send(c).catch(e=>{this.logTransportError(e,"Failed to send ACK to non-2xx response.")})}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case re.Calling:s();break;case re.Proceeding:this.state!==re.Calling&&s();break;case re.Accepted:case re.Completed:this.state!==re.Calling&&this.state!==re.Proceeding&&s();break;case re.Terminated:this.state!==re.Calling&&this.state!==re.Accepted&&this.state!==re.Completed&&(t||s());break;default:s()}this.B&&(clearTimeout(this.B),this.B=void 0),re.Proceeding,e===re.Completed&&(this.D=setTimeout(()=>this.timerD(),U.TIMER_D)),e===re.Accepted&&(this.M=setTimeout(()=>this.timerM(),U.TIMER_M)),e===re.Terminated&&this.dispose(),this.setState(e)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===re.Calling&&(this.onRequestTimeout(),this.stateTransition(re.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===re.Completed&&this.stateTransition(re.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===re.Accepted&&this.stateTransition(re.Terminated)}}class be{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.challenged=!1,this.stale=!1,this.logger=this.loggerFactory.getLogger("sip.user-agent-client"),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}cancel(e,t={}){if(!this.transaction)throw new Error("Transaction undefined.");if(!this.message.to)throw new Error("To undefined.");if(!this.message.from)throw new Error("From undefined.");const s=this.core.makeOutgoingRequestMessage(F.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},t.extraHeaders);return s.branch=this.message.branch,this.message.headers.Route&&(s.headers.Route=this.message.headers.Route),e&&s.setHeader("Reason",e),this.transaction.state===re.Proceeding?new be(ve,this.core,s):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===re.Proceeding&&new be(ve,this.core,s)},{once:!0}),s}authenticationGuard(e,t){const s=e.statusCode;if(!s)throw new Error("Response status code undefined.");if(401!==s&&407!==s)return!0;let i,r;if(401===s?(i=e.parseHeader("www-authenticate"),r="authorization"):(i=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!i)return this.logger.warn(s+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==i.stale))return this.logger.warn(s+" apparently in authentication loop, cannot authenticate"),!0;if(!this.credentials&&(this.credentials=this.core.configuration.authenticationFactory(),!this.credentials))return this.logger.warn("Unable to obtain credentials, cannot authenticate"),!0;if(!this.credentials.authenticate(this.message,i))return!0;this.challenged=!0,i.stale&&(this.stale=!0);let n=this.message.cseq+=1;return t&&t.localSequenceNumber&&(t.incrementLocalSequenceNumber(),n=this.message.cseq=t.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(r,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const e=new $;e.statusCode=408,e.reasonPhrase="Request Timeout",this.receiveResponse(e)}onTransportError(e){this.logger.error(e.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const t=new $;t.statusCode=503,t.reasonPhrase="Service Unavailable",this.receiveResponse(t)}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e});break;case/^2[0-9]{2}$/.test(t):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e});break;case/^3[0-9]{2}$/.test(t):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}init(){const e={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:e=>{e===re.Terminated&&(this.core.userAgentClients.delete(s),t===this._transaction&&this.dispose())},onTransportError:e=>this.onTransportError(e),receiveResponse:e=>this.receiveResponse(e)},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id+t.request.method;this.core.userAgentClients.set(s,this)}}class Te extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.BYE,s);super(ve,e.userAgentCore,i,t),e.dispose()}}class Se extends pe{constructor(e,t,s){super(e,t,s,re.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(e){switch(this.state){case re.Trying:break;case re.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of provisional response.")});break;case re.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(e=>{this.logTransportError(e,"Failed to send retransmission of final response.")});break;case re.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(e,t){if(e<100||e>699)throw new Error(`Invalid status code ${e}`);if(e>100&&e<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case re.Trying:if(this.lastResponse=t,e>=100&&e<200)return this.stateTransition(re.Proceeding),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send provisional response.")});if(e>=200&&e<=699)return this.stateTransition(re.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case re.Proceeding:if(this.lastResponse=t,e>=200&&e<=699)return this.stateTransition(re.Completed),void this.send(t).catch(e=>{this.logTransportError(e,"Failed to send final response.")});break;case re.Completed:return;case re.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const s=`Non-INVITE server transaction received unexpected ${e} response from TU while in state ${this.state}.`;throw this.logger.error(s),new Error(s)}onTransportError(e){this.user.onTransportError&&this.user.onTransportError(e),this.stateTransition(re.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(e,t=!1){const s=()=>{throw new Error(`Invalid state transition from ${this.state} to ${e}`)};switch(e){case re.Trying:s();break;case re.Proceeding:this.state!==re.Trying&&s();break;case re.Completed:this.state!==re.Trying&&this.state!==re.Proceeding&&s();break;case re.Terminated:this.state!==re.Proceeding&&this.state!==re.Completed&&(t||s());break;default:s()}e===re.Completed&&(this.J=setTimeout(()=>this.timerJ(),U.TIMER_J)),e===re.Terminated&&this.dispose(),this.setState(e)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===re.Completed&&this.stateTransition(re.Terminated)}}class Ce{constructor(e,t,s,i){this.transactionConstructor=e,this.core=t,this.message=s,this.delegate=i,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=s.toTag?s.toTag:E(),this.init()}dispose(){this.transaction.dispose()}get loggerFactory(){return this.core.loggerFactory}get transaction(){if(!this._transaction)throw new Error("Transaction undefined.");return this._transaction}accept(e={statusCode:200}){if(!this.acceptable)throw new M(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<200||t>299)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}progress(e={statusCode:180}){if(!this.progressable)throw new M(`${this.message.method} not progressable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<101||t>199)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}redirect(e,t={statusCode:302}){if(!this.redirectable)throw new M(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const s=t.statusCode;if(s<300||s>399)throw new TypeError(`Invalid statusCode: ${s}`);const i=new Array;e.forEach(e=>i.push(`Contact: ${e.toString()}`)),t.extraHeaders=(t.extraHeaders||[]).concat(i);return this.reply(t)}reject(e={statusCode:480}){if(!this.rejectable)throw new M(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<400||t>699)throw new TypeError(`Invalid statusCode: ${t}`);return this.reply(e)}trying(e){if(!this.tryingable)throw new M(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(e){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(e)}get acceptable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding||this.transaction.state===re.Accepted;if(this.transaction instanceof Se)return this.transaction.state===re.Trying||this.transaction.state===re.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding;if(this.transaction instanceof Se)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding;if(this.transaction instanceof Se)return this.transaction.state===re.Trying||this.transaction.state===re.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding;if(this.transaction instanceof Se)return this.transaction.state===re.Trying||this.transaction.state===re.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof fe)return this.transaction.state===re.Proceeding;if(this.transaction instanceof Se)return this.transaction.state===re.Trying;throw new Error("Unknown transaction type.")}reply(e){e.toTag||100===e.statusCode||(e.toTag=this.toTag),e.userAgent=e.userAgent||this.core.configuration.userAgentHeaderFieldValue,e.supported=e.supported||this.core.configuration.supportedOptionTagsResponse;const t=le(this.message,e);return this.transaction.receiveResponse(e.statusCode,t.message),t}init(){const e={loggerFactory:this.loggerFactory,onStateChange:e=>{e===re.Terminated&&(this.core.userAgentServers.delete(s),this.dispose())},onTransportError:e=>{this.logger.error(e.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(e):this.logger.error("User agent server response transport error.")}},t=new this.transactionConstructor(this.message,this.core.transport,e);this._transaction=t;const s=t.id;this.core.userAgentServers.set(t.id,this)}}class Ee extends Ce{constructor(e,t,s){super(Se,e.userAgentCore,t,s)}}class Ae extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.INFO,s);super(ve,e.userAgentCore,i,t)}}class _e extends Ce{constructor(e,t,s){super(Se,e.userAgentCore,t,s)}}class Ie extends be{constructor(e,t,s){super(ve,e,t,s)}}class Re extends Ce{constructor(e,t,s){super(Se,e,t,s)}}class $e extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.NOTIFY,s);super(ve,e.userAgentCore,i,t)}}class De extends Ce{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Se,i,t,s)}}class xe extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.PRACK,s);super(ve,e.userAgentCore,i,t),e.signalingStateTransition(i)}}class ke extends Ce{constructor(e,t,s){super(Se,e.userAgentCore,t,s),e.signalingStateTransition(t),this.dialog=e}accept(e={statusCode:200}){return e.body&&this.dialog.signalingStateTransition(e.body),super.accept(e)}}class Ne extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.INVITE,s);super(ye,e.userAgentCore,i,t),this.delegate=t,e.signalingStateTransition(i),e.reinviteUserAgentClient=this,this.dialog=e}receiveResponse(e){if(!this.authenticationGuard(e,this.dialog))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e});break;case/^1[0-9]{2}$/.test(t):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:this.dialog,prack:e=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(t):this.dialog.signalingStateTransition(e),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:e,session:this.dialog,ack:e=>this.dialog.ack(e)});break;case/^3[0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e});break;case/^[4-6][0-9]{2}$/.test(t):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e});break;default:throw new Error(`Invalid status code ${t}`)}}}class He extends Ce{constructor(e,t,s){super(fe,e.userAgentCore,t,s),e.reinviteUserAgentServer=this,this.dialog=e}accept(e={statusCode:200}){e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(this.dialog.routeSet.map(e=>`Record-Route: ${e}`));const t=super.accept(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),this.dialog.reConfirm(),i}progress(e={statusCode:180}){const t=super.progress(e),s=this.dialog,i=Object.assign(Object.assign({},t),{session:s});return e.body&&this.dialog.signalingStateTransition(e.body),i}redirect(e,t={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(e={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(e)}}class Pe extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.REFER,s);super(ve,e.userAgentCore,i,t)}}class Oe extends Ce{constructor(e,t,s){const i=void 0!==e.userAgentCore?e.userAgentCore:e;super(Se,i,t,s)}}class qe extends we{constructor(e,t,s,i){super(t,s),this.initialTransaction=e,this._signalingState=O.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=i,e instanceof fe&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(e.request),this.logger=t.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=O.Closed,this._offer=void 0,this._answer=void 0,this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.logger.log(`INVITE dialog ${this.id} destroyed`)}get sessionState(){return this.early?P.Early:this.ackWait?P.AckWait:this._signalingState===O.Closed?P.Terminated:P.Confirmed}get signalingState(){return this._signalingState}get offer(){return this._offer}get answer(){return this._answer}confirm(){this.early&&this.start2xxRetransmissionTimer(),super.confirm()}reConfirm(){this.reinviteUserAgentServer&&this.startReInvite2xxRetransmissionTimer()}ack(e={}){let t;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof ye))throw new Error("Transaction not instance of InviteClientTransaction.");t=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof ye))throw new Error("Initial transaction not instance of InviteClientTransaction.");t=this.initialTransaction}const s=this.createOutgoingRequestMessage(F.ACK,{cseq:t.request.cseq,extraHeaders:e.extraHeaders,body:e.body});return t.ackResponse(s),this.signalingStateTransition(s),{message:s}}bye(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof fe){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==re.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 Te(this,e,t)}info(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new Ae(this,e,t)}invite(e,t){if(this.logger.log(`INVITE dialog ${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 Ne(this,e,t)}message(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const s=this.createOutgoingRequestMessage(F.MESSAGE,t);return new Ie(this.core,s,e)}notify(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new $e(this,e,t)}prack(e,t){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new xe(this,e,t)}refer(e,t){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new Pe(this,e,t)}receiveRequest(e){if(this.logger.log(`INVITE dialog ${this.id} received ${e.method} request`),e.method!==F.ACK)if(this.sequenceGuard(e)){if(super.receiveRequest(e),e.method===F.INVITE){const t=()=>{const e=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${e}`);let t="RFC 5407 suggests the following to avoid this race condition... ";t+=" Note: Implementation issues are outside the scope of this document,",t+=" but the following tip is provided for avoiding race conditions of",t+=" this type. The caller can delay sending re-INVITE F6 for some period",t+=" of time (2 seconds, perhaps), after which the caller can reasonably",t+=" assume that its ACK has been received. Implementors can decouple the",t+=" actions of the user (e.g., pressing the hold button) from the actions",t+=" of the protocol (the sending of re-INVITE F6), so that the UA can",t+=" behave like this. In this case, it is the implementor's choice as to",t+=" how long to wait. In most cases, such an implementation may be",t+=" useful to prevent the type of race condition shown in this section.",t+=" This document expresses no preference about whether or not they",t+=" should wait for an ACK to be delivered. After considering the impact",t+=" on user experience, implementors should decide whether or not to wait",t+=" for a while, because the user experience depends on the",t+=" implementation and has no direct bearing on protocol behavior.",this.logger.warn("RFC 5407 suggests the following to avoid this race condition... Note: Implementation issues are outside the scope of this document, but the following tip is provided for avoiding race conditions of this type. The caller can delay sending re-INVITE F6 for some period of time (2 seconds, perhaps), after which the caller can reasonably assume that its ACK has been received. Implementors can decouple the actions of the user (e.g., pressing the hold button) from the actions of the protocol (the sending of re-INVITE F6), so that the UA can behave like this. In this case, it is the implementor's choice as to how long to wait. In most cases, such an implementation may be useful to prevent the type of race condition shown in this section. This document expresses no preference about whether or not they should wait for an ACK to be delivered. After considering the impact on user experience, implementors should decide whether or not to wait for a while, because the user experience depends on the implementation and has no direct bearing on protocol behavior.")},s=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.ackWait&&this.signalingState!==O.Stable)return this.core.replyStateless(e,{statusCode:500,extraHeaders:s}),void t();if(this.reinviteUserAgentServer)return void this.core.replyStateless(e,{statusCode:500,extraHeaders:s});if(this.reinviteUserAgentClient)return void this.core.replyStateless(e,{statusCode:491})}if(e.method===F.INVITE){const t=e.parseHeader("contact");if(!t)throw new Error("Contact undefined.");if(!(t instanceof p))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=t.uri}switch(e.method){case F.BYE:{const t=new Ee(this,e);this.delegate&&this.delegate.onBye?this.delegate.onBye(t):t.accept(),this.dispose()}break;case F.INFO:{const t=new _e(this,e);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(t):t.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case F.INVITE:{const t=new He(this,e);this.signalingStateTransition(e),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(t):t.reject({statusCode:488})}break;case F.MESSAGE:{const t=new Re(this.core,e);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case F.NOTIFY:{const t=new De(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(t):t.accept()}break;case F.PRACK:{const t=new ke(this,e);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(t):t.accept()}break;case F.REFER:{const t=new Oe(this,e);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(t):t.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${e.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof ye)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.initialTransaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==e.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${e.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(e),this.delegate&&this.delegate.onAck){const t=this.delegate.onAck({message:e});t instanceof Promise&&(this.ackProcessing=!0,t.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(e){const t=e.statusCode;if(!t)throw new Error("Status code undefined");if(t>100&&t<200){const t=e.getHeader("require"),s=e.getHeader("rseq"),i=t&&t.includes("100rel")&&s?Number(s):void 0;if(i){if(this.rseq&&this.rseq+1!==i)return!1;this.rseq=this.rseq?this.rseq+1:i}}return!0}signalingStateRollback(){this._signalingState!==O.HaveLocalOffer&&this.signalingState!==O.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=O.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(e){const t=H(e);if(t&&"session"===t.contentDisposition){if(this._signalingState===O.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),e instanceof R)switch(this._signalingState){case O.Initial:case O.Stable:this._signalingState=O.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case O.HaveLocalOffer:this._signalingState=O.Stable,this._answer=t;break;case O.HaveRemoteOffer:case O.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof $)switch(this._signalingState){case O.Initial:case O.Stable:this._signalingState=O.HaveRemoteOffer,this._offer=t,this._answer=void 0;break;case O.HaveLocalOffer:this._signalingState=O.Stable,this._answer=t;break;case O.HaveRemoteOffer:case O.Closed:break;default:throw new Error("Unexpected signaling state.")}if(e instanceof D)switch(this._signalingState){case O.Initial:case O.Stable:this._signalingState=O.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case O.HaveLocalOffer:break;case O.HaveRemoteOffer:this._signalingState=O.Stable,this._answer=t;break;case O.Closed:break;default:throw new Error("Unexpected signaling state.")}if(N(e))switch(this._signalingState){case O.Initial:case O.Stable:this._signalingState=O.HaveLocalOffer,this._offer=t,this._answer=void 0;break;case O.HaveLocalOffer:break;case O.HaveRemoteOffer:this._signalingState=O.Stable,this._answer=t;break;case O.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof fe){const e=this.initialTransaction;let t=U.T1;const s=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,U.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===re.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};e.addStateChangeListener(i)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof fe){const e=this.reinviteUserAgentServer.transaction;let t=U.T1;const s=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),e.retransmitAcceptedResponse(),t=Math.min(2*t,U.T2),this.invite2xxTimer=setTimeout(s,t)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(s,t);const i=()=>{e.state===re.Terminated&&(e.removeStateChangeListener(i),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};e.addStateChangeListener(i)}}}class Le extends be{constructor(e,t,s){super(ye,e,t,s),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=s}dispose(){this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(e){if(this.transaction.state===re.Calling)return super.onTransportError(e);this.logger.error(e.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(e){if(!this.authenticationGuard(e))return;const t=e.statusCode?e.statusCode.toString():"";if(!t)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(t):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:e}));case/^1[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const t=we.initialDialogStateForUserAgentClient(this.message,e);let s=this.earlyDialogs.get(t.id);if(!s){const e=this.transaction;if(!(e instanceof ye))throw new Error("Transaction not instance of InviteClientTransaction.");s=new qe(e,this.core,t),this.earlyDialogs.set(s.id,s)}if(!s.reliableSequenceGuard(e))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");s.signalingState!==O.Initial&&s.signalingState!==O.HaveLocalOffer||s.signalingStateTransition(e);const i=s;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:e,session:i,prack:e=>i.prack(void 0,e)})}return;case/^2[0-9]{2}$/.test(t):{if(!e.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!e.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const t=we.initialDialogStateForUserAgentClient(this.message,e);let s=this.confirmedDialogs.get(t.id);if(s){const e=this.confirmedDialogAcks.get(t.id);if(e){const t=this.transaction;if(!(t instanceof ye))throw new Error("Client transaction not instance of InviteClientTransaction.");t.ackResponse(e.message)}return}if(s=this.earlyDialogs.get(t.id),s)s.confirm(),s.recomputeRouteSet(e),this.earlyDialogs.delete(s.id),this.confirmedDialogs.set(s.id,s);else{const e=this.transaction;if(!(e instanceof ye))throw new Error("Transaction not instance of InviteClientTransaction.");s=new qe(e,this.core,t),this.confirmedDialogs.set(s.id,s)}s.signalingState!==O.Initial&&s.signalingState!==O.HaveLocalOffer||s.signalingStateTransition(e);const i=s;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:e,session:i,ack:e=>{const t=i.ack(e);return this.confirmedDialogAcks.set(i.id,t),t}});else{const e=i.ack();this.confirmedDialogAcks.set(i.id,e)}}return;case/^3[0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:e}));case/^[4-6][0-9]{2}$/.test(t):return this.earlyDialogs.forEach(e=>e.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:e}));default:throw new Error(`Invalid status code ${t}`)}}}class Ue extends Ce{constructor(e,t,s){super(fe,e,t,s),this.core=e}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(e={statusCode:200}){if(!this.acceptable)throw new M(`${this.message.method} not acceptable in state ${this.transaction.state}.`);if(!this.confirmedDialog)if(this.earlyDialog)this.earlyDialog.confirm(),this.confirmedDialog=this.earlyDialog,this.earlyDialog=void 0;else{const e=this.transaction;if(!(e instanceof fe))throw new Error("Transaction not instance of InviteClientTransaction.");const t=we.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new qe(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),s=`Contact: ${this.core.configuration.contact.toString()}`,i="Allow: "+j.toString();if(!e.body)if(this.confirmedDialog.signalingState===O.Stable)e.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===O.Initial||this.confirmedDialog.signalingState===O.HaveRemoteOffer)throw new Error("Response must have a body.");e.statusCode=e.statusCode||200,e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(i),e.extraHeaders.push(s);const r=super.accept(e),n=this.confirmedDialog,o=Object.assign(Object.assign({},r),{session:n});return e.body&&this.confirmedDialog.signalingState!==O.Stable&&this.confirmedDialog.signalingStateTransition(e.body),o}progress(e={statusCode:180}){if(!this.progressable)throw new M(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const e=this.transaction;if(!(e instanceof fe))throw new Error("Transaction not instance of InviteClientTransaction.");const t=we.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new qe(e,this.core,t)}const t=this.message.getHeaders("record-route").map(e=>`Record-Route: ${e}`),s=`Contact: ${this.core.configuration.contact}`;e.extraHeaders=e.extraHeaders||[],e.extraHeaders=e.extraHeaders.concat(t),e.extraHeaders.push(s);const i=super.progress(e),r=this.earlyDialog,n=Object.assign(Object.assign({},i),{session:r});return e.body&&this.earlyDialog.signalingState!==O.Stable&&this.earlyDialog.signalingStateTransition(e.body),n}redirect(e,t={statusCode:302}){return super.redirect(e,t)}reject(e={statusCode:486}){return super.reject(e)}}class Me extends be{constructor(e,t,s){super(ve,e,t,s)}}class Fe extends be{constructor(e,t,s){super(ve,e,t,s)}}class je extends Ce{constructor(e,t,s){super(Se,e,t,s),this.core=e}}class Be extends be{constructor(e,t,s){const i=e.createOutgoingRequestMessage(F.SUBSCRIBE,s);super(ve,e.userAgentCore,i,t),this.dialog=e}waitNotifyStop(){}receiveResponse(e){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);this.dialog.subscriptionExpires>e&&(this.dialog.subscriptionExpires=e)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(e.statusCode&&e.statusCode>=400&&e.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(e.statusCode)&&this.dialog.terminate()}super.receiveResponse(e)}}class Ge extends we{constructor(e,t,s,i,r,n){super(i,r),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=e,this._subscriptionExpires=t,this._subscriptionExpiresInitial=t,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=s,this.logger=i.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(e,t){const s=t.getHeaders("record-route"),i=t.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof p))throw new Error("Contact not instance of NameAddrHeader.");const r=i.uri,n=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:n,remoteSequenceNumber:undefined,localURI:e.from.uri,remoteURI:e.to.uri,remoteTarget:r,routeSet:s,secure:!1}}dispose(){super.dispose(),this.N&&(clearTimeout(this.N),this.N=void 0),this.refreshTimerClear(),this.logger.log(`SUBSCRIBE dialog ${this.id} destroyed`)}get autoRefresh(){return this._autoRefresh}set autoRefresh(e){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const e=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,t=this._subscriptionExpires-e;return Math.max(t,0)}set subscriptionExpires(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){const t=this.subscriptionRefresh;(void 0===t||t>=e)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const e=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,t=this._subscriptionRefresh-e;return Math.max(t,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(e){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${e.method} request`),this.sequenceGuard(e))if(super.receiveRequest(e),e.method===F.NOTIFY)this.onNotify(e);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${e.method} request`),this.core.replyStateless(e,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${e.method} request.`)}refresh(){const e="Allow: "+j.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}subscribe(e,t={}){var s;if(this.subscriptionState!==Q.Pending&&this.subscriptionState!==Q.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const i=new Be(this,e,t);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(s=t.extraHeaders)||void 0===s?void 0:s.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),U.TIMER_N)),i}terminate(){this.stateTransition(Q.Terminated),this.onTerminated()}unsubscribe(){const e="Allow: "+j.toString(),t={};return t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push(e),t.extraHeaders.push("Event: "+this.subscriptionEvent),t.extraHeaders.push("Expires: 0"),t.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,t)}onNotify(e){const t=e.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return void this.core.replyStateless(e,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const s=e.parseHeader("Subscription-State");if(!s||!s.state)return void this.core.replyStateless(e,{statusCode:489});const i=s.state,r=s.expires?Math.max(s.expires,0):void 0;switch(i){case"pending":this.stateTransition(Q.Pending,r);break;case"active":this.stateTransition(Q.Active,r);break;case"terminated":this.stateTransition(Q.Terminated,r);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new De(this,e);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(e){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(e)}onTerminated(){this.delegate&&this.delegate.onTerminated&&this.delegate.onTerminated()}refreshTimerClear(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}refreshTimerSet(){if(this.refreshTimerClear(),this.autoRefresh&&this.subscriptionExpires>0){const e=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(e/1e3),this._subscriptionRefreshLastSet=Math.floor(Date.now()/1e3),this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this.onRefresh(this.refresh())},e)}}stateTransition(e,t){const s=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${e}`)};switch(e){case Q.Initial:case Q.NotifyWait:return void s();case Q.Pending:if(this.subscriptionState!==Q.NotifyWait&&this.subscriptionState!==Q.Pending)return void s();break;case Q.Active:case Q.Terminated:if(this.subscriptionState!==Q.NotifyWait&&this.subscriptionState!==Q.Pending&&this.subscriptionState!==Q.Active)return void s();break;default:return void s()}e===Q.Pending&&t&&(this.subscriptionExpires=t),e===Q.Active&&t&&(this.subscriptionExpires=t),e===Q.Terminated&&this.dispose(),this._subscriptionState=e}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==Q.Terminated&&(this.stateTransition(Q.Terminated),this.onTerminated())}}class Ve extends be{constructor(e,t,s){const i=t.getHeader("Event");if(!i)throw new Error("Event undefined");const r=t.getHeader("Expires");if(!r)throw new Error("Expires undefined");super(ve,e,t,s),this.delegate=s,this.subscriberId=t.callId+t.fromTag+i,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(r),this.subscriptionEvent=i,this.subscriptionState=Q.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(e){const t=e.message.parseHeader("Event").event;if(!t||t!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void e.reject({statusCode:489});const s=e.message.parseHeader("Subscription-State");if(!s||!s.state)return this.logger.warn("Failed to parse subscription state."),void e.reject({statusCode:489});const i=s.state;switch(i){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${i}`),void e.reject({statusCode:489})}if("terminated"!==i){if(!e.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void e.reject({statusCode:489})}if(this.dialog)throw new Error("Dialog already created. This implementation only supports install of single subscriptions.");switch(this.waitNotifyStop(),this.subscriptionExpires=s.expires?Math.min(this.subscriptionExpires,Math.max(s.expires,0)):this.subscriptionExpires,i){case"pending":this.subscriptionState=Q.Pending;break;case"active":this.subscriptionState=Q.Active;break;case"terminated":this.subscriptionState=Q.Terminated;break;default:throw new Error(`Unrecognized state ${i}.`)}if(this.subscriptionState!==Q.Terminated){const t=Ge.initialDialogStateForSubscription(this.message,e.message);this.dialog=new Ge(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,t)}if(this.delegate&&this.delegate.onNotify){const t=e,s=this.dialog;this.delegate.onNotify({request:t,subscription:s})}else e.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),U.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(e){if(this.authenticationGuard(e)){if(e.statusCode&&e.statusCode>=200&&e.statusCode<300){const t=e.getHeader("Expires");if(t){const e=Number(t);e>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),e<this.subscriptionExpires&&(this.subscriptionExpires=e)}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)}e.statusCode&&e.statusCode>=300&&e.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(e)}}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE user agent client. Timed out waiting for NOTIFY."),this.waitNotifyStop(),this.delegate&&this.delegate.onNotifyTimeout&&this.delegate.onNotifyTimeout()}}class Ke extends Ce{constructor(e,t,s){super(Se,e,t,s),this.core=e}}const We=["application/sdp","application/dtmf-relay"];class Ye{constructor(e,t={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=e,this.delegate=t,this.dialogs=new Map,this.subscribers=new Map,this.logger=e.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(e=>e.dispose()),this.dialogs.clear(),this.subscribers.forEach(e=>e.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(e=>e.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(e=>e.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const e=this.configuration.transportAccessor();if(!e)throw new Error("Transport undefined.");return e}invite(e,t){return new Le(this,e,t)}message(e,t){return new Ie(this,e,t)}publish(e,t){return new Me(this,e,t)}register(e,t){return new Fe(this,e,t)}subscribe(e,t){return new Ve(this,e,t)}request(e,t){return new be(ve,this,e,t)}makeOutgoingRequestMessage(e,t,s,i,r,n,o){const a=this.configuration.sipjsId,c=this.configuration.displayName,h=this.configuration.viaForceRport,d=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();e===F.REGISTER&&l.push("path","gruu"),e===F.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");const g={callIdPrefix:a,forceRport:h,fromDisplayName:c,hackViaTcp:d,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},u=Object.assign(Object.assign({},g),r);return new D(e,t,s,i,u,n,o)}receiveIncomingRequestFromTransport(e){this.receiveRequestFromTransport(e)}receiveIncomingResponseFromTransport(e){this.receiveResponseFromTransport(e)}replyStateless(e,t){const s=this.configuration.userAgentHeaderFieldValue,i=this.configuration.supportedOptionTagsResponse;t=Object.assign(Object.assign({},t),{userAgent:s,supported:i});const r=le(e,t);return this.transport.send(r.message).catch(t=>{t instanceof Error&&this.logger.error(t.message),this.logger.error(`Transport error occurred sending stateless reply to ${e.method} request.`)}),r}receiveRequestFromTransport(e){const t=e.viaBranch,s=this.userAgentServers.get(t);e.method===F.ACK&&s&&s.transaction.state===re.Accepted&&s instanceof Ue?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${t}.`):e.method!==F.CANCEL?s?s.transaction.receiveRequest(e):this.receiveRequest(e):s?(this.replyStateless(e,{statusCode:200}),s.transaction instanceof fe&&s.transaction.state===re.Proceeding&&s instanceof Ue&&s.receiveCancel(e)):this.replyStateless(e,{statusCode:481})}receiveRequest(e){if(!j.includes(e.method)){const t="Allow: "+j.toString();return void this.replyStateless(e,{statusCode:405,extraHeaders:[t]})}if(!e.ruri)throw new Error("Request-URI undefined.");if("sip"!==e.ruri.scheme)return void this.replyStateless(e,{statusCode:416});const t=e.ruri,s=e=>!!e&&e.user===t.user;if(!s(this.configuration.aor)&&!(s(this.configuration.contact.uri)||s(this.configuration.contact.pubGruu)||s(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(e.method!==F.ACK&&this.replyStateless(e,{statusCode:404}));if(e.method!==F.INVITE||e.hasHeader("Contact")){if(!e.toTag){const t=e.viaBranch;if(!this.userAgentServers.has(t)){if(Array.from(this.userAgentServers.values()).some(t=>t.transaction.request.fromTag===e.fromTag&&t.transaction.request.callId===e.callId&&t.transaction.request.cseq===e.cseq))return void this.replyStateless(e,{statusCode:482})}}e.toTag?this.receiveInsideDialogRequest(e):this.receiveOutsideDialogRequest(e)}else this.replyStateless(e,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(e){if(e.method===F.NOTIFY){const t=e.parseHeader("Event");if(!t||!t.event)return void this.replyStateless(e,{statusCode:489});const s=e.callId+e.toTag+t.event,i=this.subscribers.get(s);if(i){const t=new De(this,e);return void i.onNotify(t)}}const t=e.callId+e.toTag+e.fromTag,s=this.dialogs.get(t);if(s){if(e.method===F.OPTIONS){const t="Allow: "+j.toString(),s="Accept: "+We.toString();return void this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}s.receiveRequest(e)}else e.method!==F.ACK&&this.replyStateless(e,{statusCode:481})}receiveOutsideDialogRequest(e){switch(e.method){case F.ACK:break;case F.BYE:this.replyStateless(e,{statusCode:481});break;case F.CANCEL:throw new Error(`Unexpected out of dialog request method ${e.method}.`);case F.INFO:this.replyStateless(e,{statusCode:405});break;case F.INVITE:{const t=new Ue(this,e);this.delegate.onInvite?this.delegate.onInvite(t):t.reject()}break;case F.MESSAGE:{const t=new Re(this,e);this.delegate.onMessage?this.delegate.onMessage(t):t.accept()}break;case F.NOTIFY:{const t=new De(this,e);this.delegate.onNotify?this.delegate.onNotify(t):t.reject({statusCode:405})}break;case F.OPTIONS:{const t="Allow: "+j.toString(),s="Accept: "+We.toString();this.replyStateless(e,{statusCode:200,extraHeaders:[t,s]})}break;case F.REFER:{const t=new Oe(this,e);this.delegate.onRefer?this.delegate.onRefer(t):t.reject({statusCode:405})}break;case F.REGISTER:{const t=new je(this,e);this.delegate.onRegister?this.delegate.onRegister(t):t.reject({statusCode:405})}break;case F.SUBSCRIBE:{const t=new Ke(this,e);this.delegate.onSubscribe?this.delegate.onSubscribe(t):t.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${e.method}.`)}}receiveResponseFromTransport(e){if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const t=e.viaBranch+e.method,s=this.userAgentClients.get(t);s?s.transaction.receiveResponse(e):this.logger.warn(`Discarding unmatched ${e.statusCode} response to ${e.method} ${t}.`)}}class ze{constructor(e,t,s){e.debug("SessionDescriptionHandler.constructor"),this.logger=e,this.mediaStreamFactory=t,this.sessionDescriptionHandlerConfiguration=s,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==s?void 0:s.peerConnectionConfiguration),this.initPeerConnectionEventHandlers()}get localMediaStream(){return this._localMediaStream}get remoteMediaStream(){return this._remoteMediaStream}get dataChannel(){return this._dataChannel}get peerConnection(){return this._peerConnection}get peerConnectionDelegate(){return this._peerConnectionDelegate}set peerConnectionDelegate(e){this._peerConnectionDelegate=e}static dispatchAddTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:t}))}static dispatchRemoveTrackEvent(e,t){e.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:t}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(e=>{e.track&&e.track.stop()}),this._peerConnection.getSenders().forEach(e=>{e.track&&e.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getReceivers().forEach(t=>{t.track&&(t.track.enabled=e)})}enableSenderTracks(e){const t=this.peerConnection;if(!t)throw new Error("Peer connection closed.");t.getSenders().forEach(t=>{t.track&&(t.track.enabled=e)})}getDescription(e,t){var s,i;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const r=null===(s=null==e?void 0:e.offerOptions)||void 0===s?void 0:s.iceRestart,n=void 0===(null==e?void 0:e.iceGatheringTimeout)?null===(i=this.sessionDescriptionHandlerConfiguration)||void 0===i?void 0:i.iceGatheringTimeout:null==e?void 0:e.iceGatheringTimeout;return this.getLocalMediaStream(e).then(()=>this.updateDirection(e)).then(()=>this.createDataChannel(e)).then(()=>this.createLocalOfferOrAnswer(e)).then(e=>this.applyModifiers(e,t)).then(e=>this.setLocalSessionDescription(e)).then(()=>this.waitForIceGatheringComplete(r,n)).then(()=>this.getLocalSessionDescription()).then(e=>({body:e.sdp,contentType:"application/sdp"})).catch(e=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+e),e})}hasDescription(e){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===e}iceGatheringComplete(){this.logger.debug("SessionDescriptionHandler.iceGatheringComplete"),void 0!==this.iceGatheringCompleteTimeoutId&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - clearing timeout"),clearTimeout(this.iceGatheringCompleteTimeoutId),this.iceGatheringCompleteTimeoutId=void 0),void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.iceGatheringComplete - resolving promise"),this.iceGatheringCompleteResolve&&this.iceGatheringCompleteResolve(),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0)}sendDtmf(e,t){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const s=this._peerConnection.getSenders();if(0===s.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const i=s[0].dtmf;if(!i)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const r=null==t?void 0:t.duration,n=null==t?void 0:t.interToneGap;try{i.insertDTMF(e,r,n)}catch(e){return this.logger.error(e.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+e.toString()),!0}setDescription(e,t,s){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==t?void 0:t.onDataChannel;const i="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(t).then(()=>this.applyModifiers({sdp:e,type:i},s)).then(e=>this.setRemoteSessionDescription(e)).catch(e=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+e),e})}applyModifiers(e,t){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),t&&0!==t.length?t.reduce((e,t)=>e.then(t),Promise.resolve(e)).then(e=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!e.sdp||!e.type)throw new Error("Invalid SDP.");return{sdp:e.sdp,type:e.type}}):Promise.resolve(e)}createDataChannel(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==e?void 0:e.dataChannel))return Promise.resolve();if(this._dataChannel)return Promise.resolve();switch(this._peerConnection.signalingState){case"stable":this.logger.debug("SessionDescriptionHandler.createDataChannel - creating data channel");try{return this._dataChannel=this._peerConnection.createDataChannel((null==e?void 0:e.dataChannelLabel)||"",null==e?void 0:e.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(e){return Promise.reject(e)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(e){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));switch(this._peerConnection.signalingState){case"stable":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP offer"),this._peerConnection.createOffer(null==e?void 0:e.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==e?void 0:e.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let t=Object.assign({},null==e?void 0:e.constraints);if(this.localMediaStreamConstraints){if(t.audio=t.audio||this.localMediaStreamConstraints.audio,t.video=t.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(t.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(t.video))return Promise.resolve()}else void 0===t.audio&&void 0===t.video&&(t={audio:!0});return this.localMediaStreamConstraints=t,this.mediaStreamFactory(t,this,e).then(e=>this.setLocalMediaStream(e))}setLocalMediaStream(e){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const t=this._peerConnection,s=this._localMediaStream,i=[],r=e=>{const r=e.kind;if("audio"!==r&&"video"!==r)throw new Error(`Unknown new track kind ${r}.`);const n=t.getSenders().find(e=>e.track&&e.track.kind===r);n?i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${r} track`),e()}).then(()=>n.replaceTrack(e).then(()=>{const t=s.getTracks().find(e=>e.kind===r);t&&(t.stop(),s.removeTrack(t),ze.dispatchRemoveTrackEvent(s,t)),s.addTrack(e),ze.dispatchAddTrackEvent(s,e)}).catch(e=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${r} track`),e}))):i.push(new Promise(e=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${r} track`),e()}).then(()=>{try{t.addTrack(e,s)}catch(e){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${r} track`),e}s.addTrack(e),ze.dispatchAddTrackEvent(s,e)}))},n=e.getAudioTracks();n.length&&r(n[0]);const o=e.getVideoTracks();return o.length&&r(o[0]),i.reduce((e,t)=>e.then(()=>t),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=this._peerConnection.localDescription;return e?Promise.resolve(e):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(e){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(e)}setRemoteSessionDescription(e){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const t=e.sdp;let s;switch(this._peerConnection.signalingState){case"stable":s="offer";break;case"have-local-offer":s="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return t?this._peerConnection.setRemoteDescription({sdp:t,type:s}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(e){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const t=this._remoteMediaStream;t.getTrackById(e.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${e.kind} track`):"audio"===e.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getAudioTracks().forEach(e=>{e.stop(),t.removeTrack(e),ze.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),ze.dispatchAddTrackEvent(t,e)):"video"===e.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${e.kind} track`),t.getVideoTracks().forEach(e=>{e.stop(),t.removeTrack(e),ze.dispatchRemoveTrackEvent(t,e)}),t.addTrack(e),ze.dispatchAddTrackEvent(t,e))}updateDirection(e){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");{const t=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")}};this._peerConnection.getTransceivers().forEach(e=>{if(e.direction){const s=t(e.direction);e.direction!==s&&(e.direction=s)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const t=(()=>{const e=this._peerConnection.remoteDescription;if(!e)throw new Error("Failed to read remote offer");const t=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(e.sdp);if(t)switch(t[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"})(),s=(()=>{switch(t){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(e=>{e.direction&&"stopped"!==e.direction&&e.direction!==s&&(e.direction=s)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(e=!1,t=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):e||"complete"!==this._peerConnection.iceGatheringState?(void 0!==this.iceGatheringCompletePromise&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - rejecting prior waiting promise"),this.iceGatheringCompleteReject&&this.iceGatheringCompleteReject(new Error("Promise superseded.")),this.iceGatheringCompletePromise=void 0,this.iceGatheringCompleteResolve=void 0,this.iceGatheringCompleteReject=void 0),this.iceGatheringCompletePromise=new Promise((e,s)=>{this.iceGatheringCompleteResolve=e,this.iceGatheringCompleteReject=s,t>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+t),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},t))}),this.iceGatheringCompletePromise):(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - already complete"),Promise.resolve())}initPeerConnectionEventHandlers(){if(this.logger.debug("SessionDescriptionHandler.initPeerConnectionEventHandlers"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection;e.onconnectionstatechange=t=>{var s;const i=e.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(t)},e.ondatachannel=e=>{var t;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=e.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(e)},e.onicecandidate=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(e)},e.onicecandidateerror=e=>{var t;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(e)},e.oniceconnectionstatechange=t=>{var s;const i=e.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(t)},e.onicegatheringstatechange=t=>{var s;const i=e.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${i}`),"complete"===i&&this.iceGatheringComplete(),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(t)},e.onnegotiationneeded=e=>{var t;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(e)},e.onsignalingstatechange=t=>{var s;const i=e.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${i}`),(null===(s=this._peerConnectionDelegate)||void 0===s?void 0:s.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(t)},e.ontrack=e=>{var t;const s=e.track.kind,i=e.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${s} ${i}`),this.setRemoteTrack(e.track),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.ontrack)&&this._peerConnectionDelegate.ontrack(e)}}}function Je(e){return(t,s)=>{void 0===e&&(e=e=>e.audio||e.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,e):Promise.resolve(new MediaStream));const i={iceGatheringTimeout:void 0!==(null==s?void 0:s.iceGatheringTimeout)?null==s?void 0:s.iceGatheringTimeout:5e3,peerConnectionConfiguration:Object.assign(Object.assign({},{bundlePolicy:"balanced",certificates:void 0,iceCandidatePoolSize:0,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",rtcpMuxPolicy:"require"}),null==s?void 0:s.peerConnectionConfiguration)},r=t.userAgent.getLogger("sip.SessionDescriptionHandler");return new ze(r,e,i)}}class Ze{constructor(e,t){if(this._state=ee.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new l,this.logger=e,t){const e=t,s=null==e?void 0:e.wsServers,i=null==e?void 0:e.maxReconnectionAttempts;if(void 0!==s){const e='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}s&&!t.server&&("string"==typeof s&&(t.server=s),s instanceof Array&&(t.server=s[0]))}this.configuration=Object.assign(Object.assign({},Ze.defaultOptions),t);const s=this.configuration.server,i=b.parse(s,"absoluteURI");if(-1===i)throw this.logger.error(`Invalid WebSocket Server URL "${s}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(i.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${s}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=i.scheme.toUpperCase()}dispose(){return this.disconnect()}get protocol(){return this._protocol}get server(){return this.configuration.server}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get ws(){return this._ws}connect(){return this._connect()}disconnect(){return this._disconnect()}isConnected(){return this.state===ee.Connected}send(e){return this._send(e)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case ee.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ee.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case ee.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ee.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case ee.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ee.Connecting)}catch(e){if(e instanceof a)return Promise.reject(e);throw e}break;case ee.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(ee.Connecting)}catch(e){if(e instanceof a)return Promise.reject(e);throw e}break;default:throw new Error("Unknown state")}let e;try{e=new WebSocket(this.server,"sip"),e.binaryType="arraybuffer",e.addEventListener("close",t=>this.onWebSocketClose(t,e)),e.addEventListener("error",t=>this.onWebSocketError(t,e)),e.addEventListener("open",t=>this.onWebSocketOpen(t,e)),e.addEventListener("message",t=>this.onWebSocketMessage(t,e)),this._ws=e}catch(e){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(e.toString()),new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.transitionState(ee.Disconnected,e)})}return this.connectPromise=new Promise((t,s)=>{this.connectResolve=t,this.connectReject=s,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),e.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case ee.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ee.Disconnecting)}catch(e){if(e instanceof a)return Promise.reject(e);throw e}break;case ee.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(ee.Disconnecting)}catch(e){if(e instanceof a)return Promise.reject(e);throw e}break;case ee.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ee.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case ee.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(ee.Disconnecting));if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");return Promise.resolve();default:throw new Error("Unknown state")}if(!this._ws)throw new Error("WebSocket must be defined.");const e=this._ws;return this.disconnectPromise=new Promise((t,s)=>{this.disconnectResolve=t,this.disconnectReject=s;try{e.close(1e3)}catch(e){throw this.logger.error("WebSocket close failed."),this.logger.error(e.toString()),e}}),this.disconnectPromise}_send(e){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+e+"\n"),this._state!==ee.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(e)}catch(e){return e instanceof Error?Promise.reject(e):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(e,t){if(t!==this._ws)return;const s=`WebSocket closed ${this.server} (code: ${e.code})`,i=this.disconnectPromise?void 0:new Error(s);i&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(s),this._ws=void 0,this.transitionState(ee.Disconnected,i)}onWebSocketError(e,t){t===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(e,t){if(t!==this._ws)return;const s=e.data;let i;if(/^(\r\n)+$/.test(s))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(s){if("string"!=typeof s){try{i=(new TextDecoder).decode(new Uint8Array(s))}catch(e){return this.logger.error(e.toString()),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"+i+"\n")}else i=s,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+i+"\n");if(this.state===ee.Connected){if(this.onMessage)try{this.onMessage(i)}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onMessage callback"),e}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(e,t){t===this._ws&&this._state===ee.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(ee.Connected))}transitionLoopDetectedError(e){let t="A state transition loop has been detected.";return t+=` An attempt to transition from ${this._state} to ${e} before the prior transition completed.`,t+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(t),new a("Loop detected.")}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(e);switch(this.transitioningState=!0,this._state){case ee.Connecting:e!==ee.Connected&&e!==ee.Disconnecting&&e!==ee.Disconnected&&s();break;case ee.Connected:e!==ee.Disconnecting&&e!==ee.Disconnected&&s();break;case ee.Disconnecting:e!==ee.Connecting&&e!==ee.Disconnected&&s();break;case ee.Disconnected:e!==ee.Connecting&&s();break;default:throw new Error("Unknown state.")}const i=this._state;this._state=e;const r=this.connectResolve,n=this.connectReject;i===ee.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,a=this.disconnectReject;if(i===ee.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 ${i} to ${this._state}`),this._stateEventEmitter.emit(this._state),e===ee.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onConnect callback"),e}if(i===ee.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{t?this.onDisconnect(t):this.onDisconnect()}catch(e){throw this.logger.error(e.toString()),this.logger.error("Exception thrown by onDisconnect callback"),e}if(i===ee.Connecting){if(!r)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");e===ee.Connected?r():n(t||new Error("Connect aborted."))}if(i===ee.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!a)throw new Error("Disconnect reject undefined.");e===ee.Disconnected?o():a(t||new Error("Disconnect aborted."))}this.transitioningState=!1}clearKeepAliveTimeout(){this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveDebounceTimeout=void 0}sendKeepAlive(){return this.keepAliveDebounceTimeout?Promise.resolve():(this.keepAliveDebounceTimeout=setTimeout(()=>{this.clearKeepAliveTimeout()},1e3*this.configuration.keepAliveDebounce),this.send("\r\n\r\n"))}startSendingKeepAlives(){this.configuration.keepAliveInterval&&!this.keepAliveInterval&&(this.keepAliveInterval=setInterval(()=>{this.sendKeepAlive(),this.startSendingKeepAlives()},(e=>{const t=.8*e;return 1e3*(Math.random()*(e-t)+t)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}Ze.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class Xe{constructor(e={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=te.Stopped,this._stateEventEmitter=new l,this.delegate=e.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Xe.defaultOptions()),{sipjsId:S(5)}),{uri:new f("sip","anonymous."+S(6),"anonymous.invalid")}),{viaHost:S(12)+".invalid"}),Xe.stripUndefinedProperties(e)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const e=1,t=254,s=Math.floor(Math.random()*(t-e+1)+e);this.options.viaHost="192.0.2."+s}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new de,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=se.error;break;case"warn":this.loggerFactory.level=se.warn;break;case"log":this.loggerFactory.level=se.log;break;case"debug":this.loggerFactory.level=se.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(e=>{const t=this.options[e];switch(e){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+e+": "+t);break;case"authorizationPassword":this.logger.log("· "+e+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+e+": "+t.name);break;default:this.logger.log("· "+e+": "+JSON.stringify(t))}})),this.options.transportOptions){const t=this.options.transportOptions,s=t.maxReconnectionAttempts,i=t.reconnectionTimeout;if(void 0!==s){const e='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==i){const e='The transport option "reconnectionTimeout" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}void 0===e.reconnectionDelay&&void 0!==i&&(this.options.reconnectionDelay=i),void 0===e.reconnectionAttempts&&void 0!==s&&(this.options.reconnectionAttempts=s)}if(void 0!==e.reconnectionDelay){const e='The user agent option "reconnectionDelay" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(void 0!==e.reconnectionAttempts){const e='The user agent option "reconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(e)}if(this._transport=new this.options.transportConstructor(this.getLogger("sip.Transport"),this.options.transportOptions),this.initTransportCallbacks(),this._contact=this.initContact(),this._instanceId=this.options.instanceId?this.options.instanceId:Xe.newUUID(),-1===b.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(e){return b.URIParse(e)}static defaultOptions(){return{allowLegacyNotifications:!1,authorizationHa1:"",authorizationPassword:"",authorizationUsername:"",delegate:{},contactName:"",contactParams:{transport:"ws"},displayName:"",forceRport:!1,gracefulShutdown:!0,hackAllowUnregisteredOptionTags:!1,hackIpInContact:!1,hackViaTcp:!1,instanceId:"",instanceIdAlwaysAdded:!1,logBuiltinEnabled:!0,logConfiguration:!0,logConnector:()=>{},logLevel:"log",noAnswerTimeout:60,preloadedRouteSet:[],reconnectionAttempts:0,reconnectionDelay:4,sendInitialProvisionalResponse:!0,sessionDescriptionHandlerFactory:Je(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:W.Unsupported,sipExtensionReplaces:W.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:Ze,transportOptions:{},uri:new f("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){const e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(16*Math.random());return("x"===e?t:t%4+8).toString(16)});return e}static stripUndefinedProperties(e){return Object.keys(e).reduce((t,s)=>(void 0!==e[s]&&(t[s]=e[s]),t),{})}get configuration(){return this.options}get contact(){return this._contact}get instanceId(){return this._instanceId}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get transport(){return this._transport}get userAgentCore(){return this._userAgentCore}getLogger(e,t){return this.loggerFactory.getLogger(e,t)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===te.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===te.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(te.Started),this.transport.connect())}async stop(){if(this.state===te.Stopped)return this.logger.warn("User agent already stopped"),Promise.resolve();if(this.logger.log(`Stopping ${this.configuration.uri}`),!this.options.gracefulShutdown)return this.logger.log("Dispose of transport"),this.transport.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(te.Stopped),Promise.resolve();const e=Object.assign({},this._publishers),t=Object.assign({},this._registerers),s=Object.assign({},this._sessions),i=Object.assign({},this._subscriptions),r=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const e in t)t[e]&&await t[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._registerers[e],t});this.logger.log("Dispose of sessions");for(const e in s)s[e]&&await s[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._sessions[e],t});this.logger.log("Dispose of subscriptions");for(const e in i)i[e]&&await i[e].dispose().catch(t=>{throw this.logger.error(t.message),delete this._subscriptions[e],t});this.logger.log("Dispose of publishers");for(const t in e)e[t]&&await e[t].dispose().catch(e=>{throw this.logger.error(e.message),delete this._publishers[t],e});this.logger.log("Dispose of transport"),await r.dispose().catch(e=>{throw this.logger.error(e.message),e}),this.logger.log("Dispose of core"),n.dispose(),this.transitionState(te.Stopped)}_makeInviter(e,t){return new Z(this,e,t)}attemptReconnection(e=1){const t=this.options.reconnectionAttempts,s=this.options.reconnectionDelay;e>t?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${e} of ${t} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${e} of ${t} - succeeded`)}).catch(s=>{this.logger.error(s.message),this.logger.log(`Reconnection attempt ${e} of ${t} - failed`),this.attemptReconnection(++e)})},1===e?0:1e3*s))}initContact(){const e=""!==this.options.contactName?this.options.contactName:S(8),t=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new f("sip",e,this.options.viaHost,void 0,t),toString:(e={})=>{const s=e.anonymous||!1,i=e.outbound||!1,r=e.register||!1;let n="<";return n+=s?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${t.transport?t.transport:"ws"}`:r?this.contact.uri:this.contact.pubGruu||this.contact.uri,i&&(n+=";ob"),n+=">",this.options.instanceIdAlwaysAdded&&(n+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),n}}}initCore(){let e=[];e.push("outbound"),this.options.sipExtension100rel===W.Supported&&e.push("100rel"),this.options.sipExtensionReplaces===W.Supported&&e.push("replaces"),this.options.sipExtensionExtraSupported&&e.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(e=e.filter(e=>z[e])),e=Array.from(new Set(e));const t=e.slice();(this.contact.pubGruu||this.contact.tempGruu)&&t.push("gruu");const s={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:e,supportedOptionTagsResponse:t,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const e=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,t=this.options.authorizationPassword?this.options.authorizationPassword:void 0,s=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new ce(this.getLoggerFactory(),s,e,t)},transportAccessor:()=>this.transport},i={onInvite:e=>{var t;const s=new J(this,e);if(e.delegate={onCancel:e=>{s._onCancel(e)},onTransportError:e=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},e.trying(),this.options.sipExtensionReplaces!==W.Unsupported){const t=e.message.parseHeader("replaces");if(t){const e=t.call_id;if("string"!=typeof e)throw new Error("Type of call id is not string");const i=t.replaces_to_tag;if("string"!=typeof i)throw new Error("Type of to tag is not string");const r=t.replaces_from_tag;if("string"!=typeof r)throw new Error("type of from tag is not string");const n=e+i+r,o=this.userAgentCore.dialogs.get(n);if(!o)return void s.reject({statusCode:481});if(!o.early&&!0===t.early_only)return void s.reject({statusCode:486});const a=this._sessions[e+r]||this._sessions[e+i]||void 0;if(!a)throw new Error("Session does not exist.");s._replacee=a}}if(null===(t=this.delegate)||void 0===t?void 0:t.onInvite)return s.autoSendAnInitialProvisionalResponse?void s.progress().then(()=>{var e;if(void 0===(null===(e=this.delegate)||void 0===e?void 0:e.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(s)}):void this.delegate.onInvite(s);s.reject({statusCode:486})},onMessage:e=>{if(this.delegate&&this.delegate.onMessage){const t=new B(e);this.delegate.onMessage(t)}else e.accept()},onNotify:e=>{if(this.delegate&&this.delegate.onNotify){const t=new G(e);this.delegate.onNotify(t)}else this.options.allowLegacyNotifications?e.accept():e.reject({statusCode:481})},onRefer:e=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(e):e.reject({statusCode:405})},onRegister:e=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(e):e.reject({statusCode:405})},onSubscribe:e=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(e):e.reject({statusCode:405})}};return new Ye(s,i)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=e=>this.onTransportDisconnect(e),this.transport.onMessage=e=>this.onTransportMessage(e)}onTransportConnect(){this.state!==te.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(e){this.state!==te.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(e),e&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(e){const t=ie.parseMessage(e,this.getLogger("sip.Parser"));if(!t)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===te.Stopped&&t instanceof R)return void this.logger.warn(`Received ${t.method} request while stopped. Dropping.`);const s=()=>{const e=["from","to","call_id","cseq","via"];for(const s of e)if(!t.hasHeader(s))return this.logger.warn(`Missing mandatory header field : ${s}.`),!1;return!0};if(t instanceof R){if(!s())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!t.toTag&&t.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(t,{statusCode:482});const e=_(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.userAgentCore.replyStateless(t,{statusCode:400})}if(t instanceof $){if(!s())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(t.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(t.via.host!==this.options.viaHost||void 0!==t.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const e=_(t.body),i=t.getHeader("content-length");if(i&&e<Number(i))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(t instanceof R)this.userAgentCore.receiveIncomingRequestFromTransport(t);else{if(!(t instanceof $))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(t)}}transitionState(e,t){const s=()=>{throw new Error(`Invalid state transition from ${this._state} to ${e}`)};switch(this._state){case te.Started:e!==te.Stopped&&s();break;case te.Stopped:e!==te.Started&&s();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${e}`),this._state=e,this._stateEventEmitter.emit(this._state)}}class Qe{constructor(e){this.listeners=[],this.keyListeners={},this.data={...e},this.proxy=new Proxy(this.data,{set:(e,t,s)=>(e[t]!==s&&(e[t]=s,this.notify(),this.notifyKey(t,s)),!0)})}getState(){return this.proxy}setState(e){let t=!1;for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)){const i=this.data[s],r=e[s];i!==r&&(this.data[s]=r,t=!0,this.notifyKey(s,r))}t&&this.notify()}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e)}}subscribeKey(e,t){return this.keyListeners[e]||(this.keyListeners[e]=[]),this.keyListeners[e].push(t),()=>{this.keyListeners[e]=this.keyListeners[e].filter(e=>e!==t)}}notify(){const e=this.getState();for(const t of this.listeners)t(e)}notifyKey(e,t){const s=this.keyListeners[e];s&&s.forEach(e=>e(t))}}var et,tt,st,it,rt,nt,ot;!function(e){e[e.IDLE=1]="IDLE",e[e.BUSY=2]="BUSY",e[e.RINGING=3]="RINGING",e[e.OFFLINE=0]="OFFLINE"}(et||(et={})),function(e){e.OUTGOING="outgoing",e.INCOMING="incoming",e.CONSULT="consult"}(tt||(tt={})),function(e){e.WEB_RTC_CONNECTING="connecting",e.WEB_RTC_CONNECTED="connected",e.WEB_RTC_DISCONNECTING="disconnecting",e.WEB_RTC_DISCONNECTED="disconnected",e.WEB_RTC_REGISTERED="registered",e.WEB_RTC_UNREGISTERED="unregistered",e.WEB_RTC_TERMINATED="terminated",e.WEB_RTC_REGISTER_FAILED="register_failed",e.WEB_RTC_INCOMING_CALL="incoming_call",e.WEB_RTC_ANSWER_SUCCESS="answer_success",e.WEB_RTC_ANSWER_FAILED="answer_failed",e.WEB_RTC_CALL_ENDED="call_ended",e.OUTGOING_LADING="outgoing_login",e.INCOMING_LADING="incoming_login",e.WEB_RTC_SEND_DTMF="send_dtmf"}(st||(st={})),function(e){e.OUT_INCOMING_CALL="out_call_incoming_call",e.OUT_FAILED="out_call_failed",e.OUT_RINGING="out_call_ringing",e.OUT_OFF_ANSWER="out_call_answer",e.OUT_HANGUP="out_call_hangup",e.CONSULT_RINGING="consult_ringing",e.CONSULT_OFF_HOOK="consult_off_hook",e.CONSULT_FAILED="consult_failed",e.CONSULT_INCOMING="consult_incoming",e.CONSULT_CALL_IN_SUCCESS="consult_call_in_success",e.OTHER_SIDE_CONSULT_HANGUP="other_side_consult_hangup",e.OUR_SIDE_CONSULT_HANGUP="Our_side_consult_hangup",e.AGENT_STATE="agent_state",e.MUTE_SUCCESS="mute_success",e.MUTE_FAILED="mute_failed",e.UNMUTE_SUCCESS="unmute_success",e.UNMUTE_FAILED="unmute_failed",e.CONSULT_TRANSFER_SUCCESS="consult_transfer_success",e.CONSULT_TRANSFER_FAILED="consult_transfer_failed",e.CONSULT_TRANSFER_OFF_HOOK="consult_transfer_off_hook",e.INCOMING_CALL="incoming_call",e.INCOMING_CALL_OFF_HOOK="incoming_call_off_hook",e.INCOMING_CALL_END="incoming_call_end"}(it||(it={})),function(e){e[e.OUT_CALL=100]="OUT_CALL",e[e.AGENT_STATE=101]="AGENT_STATE",e[e.OUT_CALL_INCOMING_CALL=102]="OUT_CALL_INCOMING_CALL",e[e.OUT_CALL_RINGING=103]="OUT_CALL_RINGING",e[e.OUT_CALL_ANSWER=104]="OUT_CALL_ANSWER",e[e.CALL_HOLD=105]="CALL_HOLD",e[e.CALL_UNHOLD=106]="CALL_UNHOLD",e[e.OUT_CALL_END=107]="OUT_CALL_END",e[e.CONSULT_REQUEST=108]="CONSULT_REQUEST",e[e.CONSULT_RINGING=109]="CONSULT_RINGING",e[e.CONSULT_ANSWER=110]="CONSULT_ANSWER",e[e.CONSULT_FAIL=111]="CONSULT_FAIL",e[e.MUTE=112]="MUTE",e[e.UNMUTE=113]="UNMUTE",e[e.CONSULT_CALL_IN=114]="CONSULT_CALL_IN",e[e.CONSULT_CALL_IN_SUCCESS=115]="CONSULT_CALL_IN_SUCCESS",e[e.CONSULT_TRANSFER=116]="CONSULT_TRANSFER",e[e.CONSULT_TRANSFER_FAILED=118]="CONSULT_TRANSFER_FAILED",e[e.CONSULT_TRANSFER_OFF_HOOK=117]="CONSULT_TRANSFER_OFF_HOOK",e[e.INCOMING_CALL=119]="INCOMING_CALL",e[e.INCOMING_CALL_OFF_HOOK=120]="INCOMING_CALL_OFF_HOOK",e[e.INCOMING_CALL_END=121]="INCOMING_CALL_END"}(rt||(rt={})),function(e){e.EVENT_ALL="event_all",e.NOTIFICATION_CLICK="notification_click",e.UPDATE_ANSWER_DEVICE="update_answer_device",e.PHONE_BAR_OPERATION="phone_bar_operation"}(nt||(nt={})),function(e){e.RINGING="客户振铃",e.HOLD="通话保持",e.AGENT_RINGING="振铃中",e.CALLING="通话中",e.CONSULTING="正在咨询",e.CONSULT_CALL_IN="咨询来电",e.INCOMING_CALL="客户来电"}(ot||(ot={}));const at=function(e){return{all:e=e||new Map,on:function(t,s){var i=e.get(t);i?i.push(s):e.set(t,[s])},off:function(t,s){var i=e.get(t);i&&(s?i.splice(i.indexOf(s)>>>0,1):e.set(t,[]))},emit:function(t,s){var i=e.get(t);i&&i.slice().map(function(e){e(s)}),(i=e.get("*"))&&i.slice().map(function(e){e(t,s)})}}}(),ct={on(e,t){at.on(e,t)},off(e,t){at.off(e,t)},emit(e,t){at.emit(e,t),at.emit(nt.EVENT_ALL,{event:e,data:t})},clearAllListeners(){at.all.clear()}},ht={isCalling:!1,direction:null,outCallIsAnswer:!1,incomingIsAnswer:!1,isHold:!1,displayText:"",isMuted:!1,consultIsAnswer:!1,actionConfigs:[],answerDevice:1};const dt=new class extends Qe{updateIsCalling(e){this.setState({isCalling:e})}updateDirection(e){this.setState({direction:e})}updateOutCallIsAnswer(e){this.setState({outCallIsAnswer:e})}updateIsHold(e){this.getState().isHold=e}updateDisplayText(e){this.setState({displayText:e})}updateActionConfigs(e){let t=[...e];1!==this.get("answerDevice")&&(t=t.filter(e=>"answer"!==e&&"hangup"!==e&&"reject"!==e)),this.setState({actionConfigs:t}),ct.emit(nt.PHONE_BAR_OPERATION,t)}updateConsultIsAnswer(e){this.setState({consultIsAnswer:e})}updateIsMuted(e){this.setState({isMuted:e})}updateIncomingIsAnswer(e){this.setState({incomingIsAnswer:e})}updateAnswerDevice(e){this.setState({answerDevice:e}),ct.emit(nt.UPDATE_ANSWER_DEVICE,e)}reset(){this.setState({...ht})}getCallInfo(){return this.getState()}get(e){return this.getState()[e]}}(ht);class lt extends Error{response;request;options;constructor(e,t,s){const i=`${e.status||0===e.status?e.status:""} ${e.statusText||""}`.trim();super(`Request failed with ${i?`status code ${i}`:"an unknown error"}: ${t.method} ${t.url}`),this.name="HTTPError",this.response=e,this.request=t,this.options=s}}class gt extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name="TimeoutError",this.request=e}}const ut=(()=>{let e=!1,t=!1;const s="function"==typeof globalThis.ReadableStream,i="function"==typeof globalThis.Request;if(s&&i)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")}catch(e){if(e instanceof Error&&"unsupported BodyInit type"===e.message)return!1;throw e}return e&&!t})(),pt="function"==typeof globalThis.AbortController,ft="function"==typeof globalThis.AbortSignal&&"function"==typeof globalThis.AbortSignal.any,mt="function"==typeof globalThis.ReadableStream,vt="function"==typeof globalThis.FormData,wt=["get","post","put","patch","head","delete"],yt={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},bt=2147483647,Tt=(new TextEncoder).encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,St=Symbol("stop"),Ct={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},Et={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},At=(e,t)=>{const s=(e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(const[s,i]of e)t+=Tt,t+=(new TextEncoder).encode(`Content-Disposition: form-data; name="${s}"`).length,t+="string"==typeof i?(new TextEncoder).encode(i).length:i.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if("string"==typeof e)return(new TextEncoder).encode(e).length;if(e instanceof URLSearchParams)return(new TextEncoder).encode(e.toString()).length;if("byteLength"in e)return e.byteLength;if("object"==typeof e&&null!==e)try{const t=JSON.stringify(e);return(new TextEncoder).encode(t).length}catch{return 0}return 0})(e.body);let i=0;return new Request(e,{duplex:"half",body:new ReadableStream({async start(r){const n=e.body instanceof ReadableStream?e.body.getReader():new Response("").body.getReader();await async function e(){const{done:o,value:a}=await n.read();if(o)return t&&t({percent:1,transferredBytes:i,totalBytes:Math.max(s,i)},new Uint8Array),void r.close();i+=a.byteLength;let c=0===s?0:i/s;(s<i||1===c)&&(c=.99),t&&t({percent:Number(c.toFixed(2)),transferredBytes:i,totalBytes:s},a),r.enqueue(a),await e()}()}})})},_t=e=>null!==e&&"object"==typeof e,It=(...e)=>{for(const t of e)if((!_t(t)||Array.isArray(t))&&void 0!==t)throw new TypeError("The `options` argument must be an object");return xt({},...e)},Rt=(e={},t={})=>{const s=new globalThis.Headers(e),i=t instanceof globalThis.Headers,r=new globalThis.Headers(t);for(const[e,t]of r.entries())i&&"undefined"===t||void 0===t?s.delete(e):s.set(e,t);return s};function $t(e,t,s){return Object.hasOwn(t,s)&&void 0===t[s]?[]:xt(e[s]??[],t[s]??[])}const Dt=(e={},t={})=>({beforeRequest:$t(e,t,"beforeRequest"),beforeRetry:$t(e,t,"beforeRetry"),afterResponse:$t(e,t,"afterResponse"),beforeError:$t(e,t,"beforeError")}),xt=(...e)=>{let t={},s={},i={};for(const r of e)if(Array.isArray(r))Array.isArray(t)||(t=[]),t=[...t,...r];else if(_t(r)){for(let[e,s]of Object.entries(r))_t(s)&&e in t&&(s=xt(t[e],s)),t={...t,[e]:s};_t(r.hooks)&&(i=Dt(i,r.hooks),t.hooks=i),_t(r.headers)&&(s=Rt(s,r.headers),t.headers=s)}return t},kt=e=>wt.includes(e)?e.toUpperCase():e,Nt={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:e=>.3*2**(e-1)*1e3},Ht=(e={})=>{if("number"==typeof e)return{...Nt,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Nt,...e}};class Pt{static create(e,t){const s=new Pt(e,t),i=async()=>{if("number"==typeof s._options.timeout&&s._options.timeout>bt)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await s._fetch();for(const t of s._options.hooks.afterResponse){const i=await t(s.request,s._options,s._decorateResponse(e.clone()));i instanceof globalThis.Response&&(e=i)}if(s._decorateResponse(e),!e.ok&&s._options.throwHttpErrors){let t=new lt(e,s.request,s._options);for(const e of s._options.hooks.beforeError)t=await e(t);throw t}if(s._options.onDownloadProgress){if("function"!=typeof s._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!mt)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return((e,t)=>{const s=Number(e.headers.get("content-length"))||0;let i=0;return 204===e.status?(t&&t({percent:1,totalBytes:s,transferredBytes:i},new Uint8Array),new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new Response(new ReadableStream({async start(r){const n=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:s},new Uint8Array),await async function e(){const{done:o,value:a}=await n.read();o?r.close():(t&&(i+=a.byteLength,t({percent:0===s?0:i/s,transferredBytes:i,totalBytes:s},a)),r.enqueue(a),await e())}()}}),{status:e.status,statusText:e.statusText,headers:e.headers})})(e.clone(),s._options.onDownloadProgress)}return e},r=(s._options.retry.methods.includes(s.request.method.toLowerCase())?s._retry(i):i()).finally(async()=>{s.request.bodyUsed||await(s.request.body?.cancel())});for(const[e,i]of Object.entries(yt))r[e]=async()=>{s.request.headers.set("accept",s.request.headers.get("accept")||i);const n=await r;if("json"===e){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(t.parseJson)return t.parseJson(await n.text())}return n[e]()};return r}request;abortController;_retryCount=0;_input;_options;constructor(e,t={}){if(this._input=e,this._options={...t,headers:Rt(this._input.headers,t.headers),hooks:Dt({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:kt(t.method??this._input.method??"GET"),prefixUrl:String(t.prefixUrl||""),retry:Ht(t.retry),throwHttpErrors:!1!==t.throwHttpErrors,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(pt&&ft){const e=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=e?AbortSignal.any([e,this.abortController.signal]):this.abortController.signal}if(ut&&(this._options.duplex="half"),void 0!==this._options.json&&(this._options.body=this._options.stringifyJson?.(this._options.json)??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const e="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);!(vt&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(t,{...this.request}),this._options)}if(this._options.onUploadProgress){if("function"!=typeof this._options.onUploadProgress)throw new TypeError("The `onUploadProgress` option must be a function");if(!ut)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=At(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount>this._options.retry.limit||e instanceof gt)throw e;if(e instanceof lt){if(!this._options.retry.statusCodes.includes(e.response.status))throw e;const t=e.response.headers.get("Retry-After")??e.response.headers.get("RateLimit-Reset")??e.response.headers.get("X-RateLimit-Reset")??e.response.headers.get("X-Rate-Limit-Reset");if(t&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=1e3*Number(t);Number.isNaN(e)?e=Date.parse(t)-Date.now():e>=Date.parse("2024-01-01")&&(e-=Date.now());const s=this._options.retry.maxRetryAfter??e;return e<s?e:s}if(413===e.response.status)throw e}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const s=Math.min(this._calculateRetryDelay(t),bt);if(this._retryCount<1)throw t;await async function(e,{signal:t}){return new Promise((s,i)=>{function r(){clearTimeout(n),i(t.reason)}t&&(t.throwIfAborted(),t.addEventListener("abort",r,{once:!0}));const n=setTimeout(()=>{t?.removeEventListener("abort",r),s()},e)})}(s,{signal:this._options.signal});for(const e of this._options.hooks.beforeRetry){if(await e({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===St)return}return this._retry(e)}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const t=await e(this.request,this._options);if(t instanceof Request){this.request=t;break}if(t instanceof Response)return t}const e=((e,t)=>{const s={};for(const i in t)i in Et||i in Ct||i in e||(s[i]=t[i]);return s})(this.request,this._options),t=this.request;return this.request=t.clone(),!1===this._options.timeout?this._options.fetch(t,e):async function(e,t,s,i){return new Promise((r,n)=>{const o=setTimeout(()=>{s&&s.abort(),n(new gt(e))},i.timeout);i.fetch(e,t).then(r).catch(n).then(()=>{clearTimeout(o)})})}(t,e,this.abortController,this._options)}}
2
2
  /*! MIT License © Sindre Sorhus */const Ot=e=>{const t=(t,s)=>Pt.create(t,It(e,s));for(const s of wt)t[s]=(t,i)=>Pt.create(t,It(e,i,{method:s}));return t.create=e=>Ot(It(e)),t.extend=t=>("function"==typeof t&&(t=t(e??{})),Ot(It(e,t))),t.stop=St,t};var qt,Lt=Ot(),Ut="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Mt={exports:{}};
3
3
  /**
4
4
  * [js-md5]{@link https://github.com/emn178/js-md5}
@@ -15,12 +15,12 @@ qt=Mt,function(){var s="input is invalid type",i="object"==typeof window,r=i?win
15
15
  * Copyright 2019 Google LLC
16
16
  * SPDX-License-Identifier: BSD-3-Clause
17
17
  */
18
- const Gt=globalThis,Vt=Gt.ShadowRoot&&(void 0===Gt.ShadyCSS||Gt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Kt=Symbol(),Wt=new WeakMap;let Yt=class{constructor(e,t,s){if(this._$cssResult$=!0,s!==Kt)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Vt&&void 0===e){const s=void 0!==t&&1===t.length;s&&(e=Wt.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),s&&Wt.set(t,e))}return e}toString(){return this.cssText}};const Jt=(e,...t)=>{const s=1===e.length?e[0]:t.reduce((t,s,i)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[i+1],e[0]);return new Yt(s,e,Kt)},zt=Vt?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const s of e.cssRules)t+=s.cssText;return(e=>new Yt("string"==typeof e?e:e+"",void 0,Kt))(t)})(e):e,{is:Zt,defineProperty:Xt,getOwnPropertyDescriptor:Qt,getOwnPropertyNames:es,getOwnPropertySymbols:ts,getPrototypeOf:ss}=Object,is=globalThis,rs=is.trustedTypes,ns=rs?rs.emptyScript:"",os=is.reactiveElementPolyfillSupport,as=(e,t)=>e,cs={toAttribute(e,t){switch(t){case Boolean:e=e?ns:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let s=e;switch(t){case Boolean:s=null!==e;break;case Number:s=null===e?null:Number(e);break;case Object:case Array:try{s=JSON.parse(e)}catch(e){s=null}}return s}},hs=(e,t)=>!Zt(e,t),ds={attribute:!0,type:String,converter:cs,reflect:!1,useDefault:!1,hasChanged:hs};
18
+ const Gt=globalThis,Vt=Gt.ShadowRoot&&(void 0===Gt.ShadyCSS||Gt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Kt=Symbol(),Wt=new WeakMap;let Yt=class{constructor(e,t,s){if(this._$cssResult$=!0,s!==Kt)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Vt&&void 0===e){const s=void 0!==t&&1===t.length;s&&(e=Wt.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),s&&Wt.set(t,e))}return e}toString(){return this.cssText}};const zt=(e,...t)=>{const s=1===e.length?e[0]:t.reduce((t,s,i)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[i+1],e[0]);return new Yt(s,e,Kt)},Jt=Vt?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const s of e.cssRules)t+=s.cssText;return(e=>new Yt("string"==typeof e?e:e+"",void 0,Kt))(t)})(e):e,{is:Zt,defineProperty:Xt,getOwnPropertyDescriptor:Qt,getOwnPropertyNames:es,getOwnPropertySymbols:ts,getPrototypeOf:ss}=Object,is=globalThis,rs=is.trustedTypes,ns=rs?rs.emptyScript:"",os=is.reactiveElementPolyfillSupport,as=(e,t)=>e,cs={toAttribute(e,t){switch(t){case Boolean:e=e?ns:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let s=e;switch(t){case Boolean:s=null!==e;break;case Number:s=null===e?null:Number(e);break;case Object:case Array:try{s=JSON.parse(e)}catch(e){s=null}}return s}},hs=(e,t)=>!Zt(e,t),ds={attribute:!0,type:String,converter:cs,reflect:!1,useDefault:!1,hasChanged:hs};
19
19
  /**
20
20
  * @license
21
21
  * Copyright 2017 Google LLC
22
22
  * SPDX-License-Identifier: BSD-3-Clause
23
- */Symbol.metadata??=Symbol("metadata"),is.litPropertyMetadata??=new WeakMap;let ls=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=ds){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const s=Symbol(),i=this.getPropertyDescriptor(e,s,t);void 0!==i&&Xt(this.prototype,e,i)}}static getPropertyDescriptor(e,t,s){const{get:i,set:r}=Qt(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:i,set(t){const n=i?.call(this);r?.call(this,t),this.requestUpdate(e,n,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??ds}static _$Ei(){if(this.hasOwnProperty(as("elementProperties")))return;const e=ss(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(as("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(as("properties"))){const e=this.properties,t=[...es(e),...ts(e)];for(const s of t)this.createProperty(s,e[s])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,s]of t)this.elementProperties.set(e,s)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const s=this._$Eu(e,t);void 0!==s&&this._$Eh.set(s,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const s=new Set(e.flat(1/0).reverse());for(const e of s)t.unshift(zt(e))}else void 0!==e&&t.push(zt(e));return t}static _$Eu(e,t){const s=t.attribute;return!1===s?void 0:"string"==typeof s?s:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const s of t.keys())this.hasOwnProperty(s)&&(e.set(s,this[s]),delete this[s]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(Vt)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const s of t){const t=document.createElement("style"),i=Gt.litNonce;void 0!==i&&t.setAttribute("nonce",i),t.textContent=s.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,s){this._$AK(e,s)}_$ET(e,t){const s=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,s);if(void 0!==i&&!0===s.reflect){const r=(void 0!==s.converter?.toAttribute?s.converter:cs).toAttribute(t,s.type);this._$Em=e,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(e,t){const s=this.constructor,i=s._$Eh.get(e);if(void 0!==i&&this._$Em!==i){const e=s.getPropertyOptions(i),r="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:cs;this._$Em=i;const n=r.fromAttribute(t,e.type);this[i]=n??this._$Ej?.get(i)??n,this._$Em=null}}requestUpdate(e,t,s){if(void 0!==e){const i=this.constructor,r=this[e];if(s??=i.getPropertyOptions(e),!((s.hasChanged??hs)(r,t)||s.useDefault&&s.reflect&&r===this._$Ej?.get(e)&&!this.hasAttribute(i._$Eu(e,s))))return;this.C(e,t,s)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:s,reflect:i,wrapped:r},n){s&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,n??t??this[e]),!0!==r||void 0!==n)||(this._$AL.has(e)||(this.hasUpdated||s||(t=void 0),this._$AL.set(e,t)),!0===i&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,s]of e){const{wrapped:e}=s,i=this[t];!0!==e||this._$AL.has(t)||void 0===i||this.C(t,void 0,s,i)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};ls.elementStyles=[],ls.shadowRootOptions={mode:"open"},ls[as("elementProperties")]=new Map,ls[as("finalized")]=new Map,os?.({ReactiveElement:ls}),(is.reactiveElementVersions??=[]).push("2.1.1");
23
+ */Symbol.metadata??=Symbol("metadata"),is.litPropertyMetadata??=new WeakMap;let ls=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=ds){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const s=Symbol(),i=this.getPropertyDescriptor(e,s,t);void 0!==i&&Xt(this.prototype,e,i)}}static getPropertyDescriptor(e,t,s){const{get:i,set:r}=Qt(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:i,set(t){const n=i?.call(this);r?.call(this,t),this.requestUpdate(e,n,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??ds}static _$Ei(){if(this.hasOwnProperty(as("elementProperties")))return;const e=ss(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(as("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(as("properties"))){const e=this.properties,t=[...es(e),...ts(e)];for(const s of t)this.createProperty(s,e[s])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,s]of t)this.elementProperties.set(e,s)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const s=this._$Eu(e,t);void 0!==s&&this._$Eh.set(s,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const s=new Set(e.flat(1/0).reverse());for(const e of s)t.unshift(Jt(e))}else void 0!==e&&t.push(Jt(e));return t}static _$Eu(e,t){const s=t.attribute;return!1===s?void 0:"string"==typeof s?s:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const s of t.keys())this.hasOwnProperty(s)&&(e.set(s,this[s]),delete this[s]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(Vt)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const s of t){const t=document.createElement("style"),i=Gt.litNonce;void 0!==i&&t.setAttribute("nonce",i),t.textContent=s.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,s){this._$AK(e,s)}_$ET(e,t){const s=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,s);if(void 0!==i&&!0===s.reflect){const r=(void 0!==s.converter?.toAttribute?s.converter:cs).toAttribute(t,s.type);this._$Em=e,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(e,t){const s=this.constructor,i=s._$Eh.get(e);if(void 0!==i&&this._$Em!==i){const e=s.getPropertyOptions(i),r="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:cs;this._$Em=i;const n=r.fromAttribute(t,e.type);this[i]=n??this._$Ej?.get(i)??n,this._$Em=null}}requestUpdate(e,t,s){if(void 0!==e){const i=this.constructor,r=this[e];if(s??=i.getPropertyOptions(e),!((s.hasChanged??hs)(r,t)||s.useDefault&&s.reflect&&r===this._$Ej?.get(e)&&!this.hasAttribute(i._$Eu(e,s))))return;this.C(e,t,s)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:s,reflect:i,wrapped:r},n){s&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,n??t??this[e]),!0!==r||void 0!==n)||(this._$AL.has(e)||(this.hasUpdated||s||(t=void 0),this._$AL.set(e,t)),!0===i&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,s]of e){const{wrapped:e}=s,i=this[t];!0!==e||this._$AL.has(t)||void 0===i||this.C(t,void 0,s,i)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};ls.elementStyles=[],ls.shadowRootOptions={mode:"open"},ls[as("elementProperties")]=new Map,ls[as("finalized")]=new Map,os?.({ReactiveElement:ls}),(is.reactiveElementVersions??=[]).push("2.1.1");
24
24
  /**
25
25
  * @license
26
26
  * Copyright 2017 Google LLC
@@ -31,7 +31,7 @@ const gs=globalThis,us=gs.trustedTypes,ps=us?us.createPolicy("lit-html",{createH
31
31
  * @license
32
32
  * Copyright 2017 Google LLC
33
33
  * SPDX-License-Identifier: BSD-3-Clause
34
- */},Js=globalThis;class zs extends ls{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Ys(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ks}}zs._$litElement$=!0,zs.finalized=!0,Js.litElementHydrateSupport?.({LitElement:zs});const Zs=Js.litElementPolyfillSupport;Zs?.({LitElement:zs}),(Js.litElementVersions??=[]).push("4.2.1");
34
+ */},zs=globalThis;class Js extends ls{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Ys(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ks}}Js._$litElement$=!0,Js.finalized=!0,zs.litElementHydrateSupport?.({LitElement:Js});const Zs=zs.litElementPolyfillSupport;Zs?.({LitElement:Js}),(zs.litElementVersions??=[]).push("4.2.1");
35
35
  /**
36
36
  * @license
37
37
  * Copyright 2017 Google LLC
@@ -57,7 +57,7 @@ const Xs=e=>(t,s)=>{void 0!==s?s.addInitializer(()=>{customElements.define(e,t)}
57
57
  * @license
58
58
  * Copyright 2017 Google LLC
59
59
  * SPDX-License-Identifier: BSD-3-Clause
60
- */let ri=class extends zs{constructor(){super(...arguments),this.type="info",this.content="",this.duration=3e3}static{this.styles=Jt`
60
+ */let ri=class extends Js{constructor(){super(...arguments),this.type="info",this.content="",this.duration=3e3}static{this.styles=zt`
61
61
  :host {
62
62
  display: block;
63
63
  margin-top: 10px;
@@ -110,13 +110,13 @@ const Xs=e=>(t,s)=>{void 0!==s?s.addInitializer(()=>{customElements.define(e,t)}
110
110
  :host([type='loading']) {
111
111
  background: #595959;
112
112
  }
113
- `}connectedCallback(){super.connectedCallback(),setTimeout(()=>{this.remove()},this.duration+300)}render(){return xs`<div>${this.content}</div>`}};Bt([ti({type:String})],ri.prototype,"type",void 0),Bt([ti({type:String})],ri.prototype,"content",void 0),Bt([ti({type:Number})],ri.prototype,"duration",void 0),ri=Bt([Xs("my-message")],ri);const ni=(e,t,s=3e3)=>{let i=document.querySelector("#message-container");i||(i=document.createElement("div"),i.id="message-container",Object.assign(i.style,{position:"fixed",top:"14px",left:"50%",transform:"translateX(-50%)",zIndex:"9999"}),document.body.appendChild(i));const r=document.createElement("my-message");r.setAttribute("type",e),r.setAttribute("content",t),r.setAttribute("duration",String(s)),r.style.setProperty("--fade-delay",s/1e3+"s"),i.appendChild(r)},oi=(e,t=3e3)=>ni("success",e,t),ai=(e,t=3e3)=>ni("error",e,t),ci=(e,t=3e3)=>ni("warning",e,t),hi="/v1/aicc/bmserver",di="/v1/aicc/ccs";let li="",gi="",ui="";async function pi(e,t){const s=function(){const e=jt(gi,ui);return Lt.create({prefixUrl:`${li}/api`,timeout:!1,headers:{Authorization:e},hooks:{afterResponse:[async(e,t,s)=>{const i=await s.clone().json();if(0!==i.code)throw ai(i.msg),new Error(JSON.stringify(i)||"请求失败");return s.json=async()=>i,s}]}})}(),i=e.replace(/^\/+/,"");return s.post(i,{json:t}).json()}const fi={agentInfo:{},isRtcReconnecting:!1,sessionId:"",enableBrowserAlert:!1,autoStateTimer:null};const mi=new class extends Qe{updateRttObject(e){this.setState({rttObject:e})}}({rttObject:{rtt:null,jitter:null,packetsLost:null,packetsReceived:null,packetsSent:null,sendBitrate:null,recvBitrate:null,codec:null}});class vi{constructor(e,t){this.config=e,this.eventCallback=t,this.userAgent=null,this.registerer=null,this.activeSession=null,this.callTimeoutTimer=null,this.incomingInvitation=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimer=null,this.isOffline=!1,this.autoAnswerTimer=null,this.handleMessage=e=>{},this.handleNetworkInfoChange=e=>{0===(e.rttObject?.rtt||0)?this.isOffline||(this.isOffline=!0,this.handleOffline()):this.isOffline&&(this.isOffline=!1,this.handleOnline())},this.handleOffline=()=>{console.warn("[SIPClient] 网络断开,准备销毁 SIP 客户端",(new Date).toLocaleString()),this.destroy()},this.handleOnline=()=>{console.warn("[SIPClient] 网络恢复,准备重新启动 SIP 客户端",(new Date).toLocaleString()),this.reconnect()},mi.subscribe(this.handleNetworkInfoChange)}async start(){const e=Xe.makeURI(`sip:${this.config.user}@${this.config.server}`);if(!e)throw new Error("无效的SIP配置");const t={uri:e,authorizationUsername:this.config.user,authorizationPassword:this.config.password,transportOptions:{server:this.config.webSocket,connectionTimeout:30,keepAliveInterval:0},sessionDescriptionHandlerFactoryOptions:{alwaysAcquireMediaFirst:!0,peerConnectionConfiguration:{iceServers:[]},iceGatheringTimeout:400},logBuiltinEnabled:!1};this.userAgent=new Xe(t),this.setupEventListeners(),await this.userAgent.start(),await this.register()}setupEventListeners(){this.userAgent&&(this.userAgent.transport.stateChange.addListener(e=>{let t;switch(e){case ee.Connecting:t=st.WEB_RTC_CONNECTING;break;case ee.Connected:t=st.WEB_RTC_CONNECTED,this.reconnectAttempts=0,fi.isRtcReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);break;case ee.Disconnecting:t=st.WEB_RTC_DISCONNECTING;break;case ee.Disconnected:{t=st.WEB_RTC_DISCONNECTED;const e=dt.get("answerDevice");if(!fi.isRtcReconnecting&&this.reconnectAttempts<this.maxReconnectAttempts&&1===e){this.reconnectAttempts++;const e=1e3*this.reconnectAttempts;console.warn(`SIP WebSocket 断开,第 ${this.reconnectAttempts} 次尝试重连,${e}ms 后重试...`),this.reconnectTimer=setTimeout(()=>{this.reconnect()},e)}else this.reconnectAttempts>=this.maxReconnectAttempts&&console.error("SIP 重连失败:已达到最大重试次数");break}default:t="unknown"}this.eventCallback?.({type:t})}),this.userAgent.transport.stateChange.addListener(e=>{}),this.userAgent.delegate={onInvite:e=>{this.handleIncomingCall(e)}})}async register(){if(this.userAgent){this.registerer=new ne(this.userAgent),this.registerer?.stateChange.addListener(e=>{let t;switch(e){case X.Initial:t="initial";break;case X.Registered:t=st.WEB_RTC_REGISTERED;break;case X.Unregistered:t=st.WEB_RTC_UNREGISTERED;break;case X.Terminated:t=st.WEB_RTC_TERMINATED;break;default:t="unknown"}this.eventCallback?.({type:t})});try{await this.registerer.register()}catch(e){this.eventCallback?.({type:st.WEB_RTC_REGISTER_FAILED,data:e})}}}attachRemoteAudio(e){const t=e.sessionDescriptionHandler;if(t){const e=t.peerConnection;if(!e)return;const s=new MediaStream;e.getReceivers().forEach(e=>{e.track&&"audio"===e.track.kind&&s.addTrack(e.track)});let i=document.getElementById("sip-remote-audio");i||(i=document.createElement("audio"),i.id="sip-remote-audio",i.autoplay=!0,i.style.display="none",document.body.appendChild(i)),i.srcObject=s,i.play().catch(e=>{console.error("音频播放失败,需要用户交互触发",e)})}}handleSessionState(e,t,s){e.stateChange.addListener(t=>{switch(t){case K.Established:clearTimeout(this.callTimeoutTimer),this.activeSession=e,this.attachRemoteAudio(e);break;case K.Terminating:break;case K.Terminated:this.activeSession=null,clearTimeout(this.callTimeoutTimer);case K.Establishing:}})}handleIncomingCall(e){this.incomingInvitation=e,this.handleSessionState(e,!1);const{soft_device_auto_answer:t,auto_answer_time:s}=fi.agentInfo,i=dt.get("direction"),r=1===t;if(i===tt.OUTGOING)this.answerCall();else if(r&&i===tt.INCOMING){const e=Number(s)||0;e>0?this.autoAnswerTimer=setTimeout(()=>{this.answerCall(),this.autoAnswerTimer=null},e):this.answerCall()}}async makeCall(e){if(dt.getState().isCalling)throw new Error("正在呼叫中,请勿重复点击");if(!this.userAgent)throw dt.updateIsCalling(!1),dt.updateDirection(null),new Error("SIP客户端未初始化");dt.updateIsCalling(!0),dt.updateDirection(tt.OUTGOING);const t=Xe.makeURI(`sip:${e}@${this.config.server}`);if(!t)throw new Error("无效的被叫号码");const s=new Z(this.userAgent,t);this.handleSessionState(s,!0,e);try{this.activeSession=s,await s.invite(),this.config.callTimeout&&(this.callTimeoutTimer=setTimeout(()=>{s.state!==K.Established&&(this.hangup(),this.eventCallback?.({type:"error",data:{message:"呼叫超时未接通"}}))},this.config.callTimeout))}catch(e){this.eventCallback?.({type:"error",data:{message:"呼叫失败",detail:e}}),dt.updateIsCalling(!1),dt.updateDirection(null)}}async answerCall(){if(!this.incomingInvitation)throw new Error("无来电可接听");this.autoAnswerTimer&&(clearTimeout(this.autoAnswerTimer),this.autoAnswerTimer=null);try{console.log((new Date).toLocaleString()),await this.incomingInvitation.accept(),console.log((new Date).toLocaleString()),this.activeSession=this.incomingInvitation,this.incomingInvitation=null}catch(e){this.eventCallback?.({type:st.WEB_RTC_ANSWER_FAILED,data:{detail:e}})}}async rejectInCall(){if(this.incomingInvitation)try{await this.incomingInvitation.reject(),this.incomingInvitation=null,dt.updateDirection(null),dt.updateIsCalling(!1),clearTimeout(this.callTimeoutTimer)}catch(e){this.eventCallback?.({type:"error",data:{message:"拒接失败",detail:e}})}}sendDTMF(e){if(!this.activeSession)throw new Error("当前没有活跃的通话");const t=this.activeSession.sessionDescriptionHandler;t&&"function"==typeof t.sendDtmf?(t.sendDtmf(e),this.eventCallback?.({type:st.WEB_RTC_SEND_DTMF,data:{tone:e}})):console.warn("DTMF发送不支持或未初始化")}async hangup(){if(this.activeSession){clearTimeout(this.callTimeoutTimer);const e=this.activeSession;if(!e)return;const t=e.state;try{t===K.Established?await e.bye():t===K.Establishing&&(e instanceof Z?await e.cancel():e instanceof z&&await e.reject()),clearTimeout(this.callTimeoutTimer)}catch(e){console.error("挂断失败",e)}finally{this.activeSession=null}}}async rejectOutCall(){this.activeSession instanceof z&&(await this.activeSession.reject(),this.activeSession=null)}async destroy(){if(clearTimeout(this.callTimeoutTimer),this.activeSession&&await this.hangup(),this.registerer){try{await this.registerer.unregister()}catch(e){console.warn("注销失败",e)}this.registerer=null}this.userAgent&&(await this.userAgent.stop(),this.userAgent=null)}async reconnect(){if(!fi.isRtcReconnecting){fi.isRtcReconnecting=!0;try{await this.destroy(),await this.start(),console.log("重连成功"),this.isOffline=!1}catch(e){console.error("重连失败",e)}finally{fi.isRtcReconnecting=!1}}}async getNetworkStats(){if(this.activeSession){const e=this.activeSession.sessionDescriptionHandler?.peerConnection;if(!e)return null;const t=await e.getStats(),s={};return t.forEach(e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&null!=e.currentRoundTripTime&&(s.rtt=+(1e3*e.currentRoundTripTime).toFixed(2)),"inbound-rtp"===e.type&&"audio"===e.kind&&(s.jitter=+(1e3*e.jitter).toFixed(2),s.packetsLost=e.packetsLost,s.packetsReceived=e.packetsReceived,e.bytesReceived&&e.timestamp&&(s.recvBitrate=+(e.bytesReceived/1024).toFixed(2))),"outbound-rtp"===e.type&&"audio"===e.kind&&(s.packetsSent=e.packetsSent,e.bytesSent&&e.timestamp&&(s.sendBitrate=+(e.bytesSent/1024).toFixed(2))),"codec"===e.type&&e.mimeType&&(s.codec=e.mimeType)}),{...s,rtt:s?.rtt||40}}try{const e=Date.now();await pi(`${hi}/config/ping`,{});const t=Date.now();return{rtt:t-e||1}}catch(e){console.log(e)}}}const wi={statusColor:{[et.IDLE]:"#1D92E9",[et.BUSY]:"#F5212D",[et.OFFLINE]:"#8c8c8c",[et.RINGING]:"#e9b91d"}},yi=["call_number"],bi=[],Ti=["hangup"],Si=["hold","hangup","unhold","mute","unmute","transfer","consult","satisfaction","dtmf"],Ci=["consult_transfer"],Ei=["hangup"],Ai=["answer","reject"],_i=["hangup","consult","transfer","hold","unhold","mute","unmute","satisfaction","dtmf"];let Ii=class extends zs{static{this.styles=Jt`
113
+ `}connectedCallback(){super.connectedCallback(),setTimeout(()=>{this.remove()},this.duration+300)}render(){return xs`<div>${this.content}</div>`}};Bt([ti({type:String})],ri.prototype,"type",void 0),Bt([ti({type:String})],ri.prototype,"content",void 0),Bt([ti({type:Number})],ri.prototype,"duration",void 0),ri=Bt([Xs("my-message")],ri);const ni=(e,t,s=3e3)=>{let i=document.querySelector("#message-container");i||(i=document.createElement("div"),i.id="message-container",Object.assign(i.style,{position:"fixed",top:"14px",left:"50%",transform:"translateX(-50%)",zIndex:"9999"}),document.body.appendChild(i));const r=document.createElement("my-message");r.setAttribute("type",e),r.setAttribute("content",t),r.setAttribute("duration",String(s)),r.style.setProperty("--fade-delay",s/1e3+"s"),i.appendChild(r)},oi=(e,t=3e3)=>ni("success",e,t),ai=(e,t=3e3)=>ni("error",e,t),ci=(e,t=3e3)=>ni("warning",e,t),hi="/v1/aicc/bmserver",di="/v1/aicc/ccs";let li="",gi="",ui="";async function pi(e,t){const s=function(){const e=jt(gi,ui);return Lt.create({prefixUrl:`${li}/api`,timeout:!1,headers:{Authorization:e},hooks:{afterResponse:[async(e,t,s)=>{const i=await s.clone().json();if(0!==i.code)throw ai(i.msg),new Error(JSON.stringify(i)||"请求失败");return s.json=async()=>i,s}]}})}(),i=e.replace(/^\/+/,"");return s.post(i,{json:t}).json()}const fi={agentInfo:{},isRtcReconnecting:!1,sessionId:"",enableBrowserAlert:!1,autoStateTimer:null};const mi=new class extends Qe{updateRttObject(e){this.setState({rttObject:e})}}({rttObject:{rtt:null,jitter:null,packetsLost:null,packetsReceived:null,packetsSent:null,sendBitrate:null,recvBitrate:null,codec:null}});class vi{constructor(e,t){this.config=e,this.eventCallback=t,this.userAgent=null,this.registerer=null,this.activeSession=null,this.callTimeoutTimer=null,this.incomingInvitation=null,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.reconnectTimer=null,this.isOffline=!1,this.autoAnswerTimer=null,this.handleMessage=e=>{},this.handleNetworkInfoChange=e=>{0===(e.rttObject?.rtt||0)?this.isOffline||(this.isOffline=!0,this.handleOffline()):this.isOffline&&(this.isOffline=!1,this.handleOnline())},this.handleOffline=()=>{console.warn("[SIPClient] 网络断开,准备销毁 SIP 客户端",(new Date).toLocaleString()),this.destroy()},this.handleOnline=()=>{console.warn("[SIPClient] 网络恢复,准备重新启动 SIP 客户端",(new Date).toLocaleString()),this.reconnect()},mi.subscribe(this.handleNetworkInfoChange)}async start(){const e=Xe.makeURI(`sip:${this.config.user}@${this.config.server}`);if(!e)throw new Error("无效的SIP配置");const t={uri:e,authorizationUsername:this.config.user,authorizationPassword:this.config.password,transportOptions:{server:this.config.webSocket,connectionTimeout:30,keepAliveInterval:0},sessionDescriptionHandlerFactoryOptions:{alwaysAcquireMediaFirst:!0,peerConnectionConfiguration:{iceServers:[]},iceGatheringTimeout:400},logBuiltinEnabled:!1};this.userAgent=new Xe(t),this.setupEventListeners(),await this.userAgent.start(),await this.register()}setupEventListeners(){this.userAgent&&(this.userAgent.transport.stateChange.addListener(e=>{let t;switch(e){case ee.Connecting:t=st.WEB_RTC_CONNECTING;break;case ee.Connected:t=st.WEB_RTC_CONNECTED,this.reconnectAttempts=0,fi.isRtcReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);break;case ee.Disconnecting:t=st.WEB_RTC_DISCONNECTING;break;case ee.Disconnected:{t=st.WEB_RTC_DISCONNECTED;const e=dt.get("answerDevice");if(!fi.isRtcReconnecting&&this.reconnectAttempts<this.maxReconnectAttempts&&1===e){this.reconnectAttempts++;const e=1e3*this.reconnectAttempts;console.warn(`SIP WebSocket 断开,第 ${this.reconnectAttempts} 次尝试重连,${e}ms 后重试...`),this.reconnectTimer=setTimeout(()=>{this.reconnect()},e)}else this.reconnectAttempts>=this.maxReconnectAttempts&&console.error("SIP 重连失败:已达到最大重试次数");break}default:t="unknown"}this.eventCallback?.({type:t})}),this.userAgent.transport.stateChange.addListener(e=>{}),this.userAgent.delegate={onInvite:e=>{this.handleIncomingCall(e)}})}async register(){if(this.userAgent){this.registerer=new ne(this.userAgent),this.registerer?.stateChange.addListener(e=>{let t;switch(e){case X.Initial:t="initial";break;case X.Registered:t=st.WEB_RTC_REGISTERED;break;case X.Unregistered:t=st.WEB_RTC_UNREGISTERED;break;case X.Terminated:t=st.WEB_RTC_TERMINATED;break;default:t="unknown"}this.eventCallback?.({type:t})});try{await this.registerer.register()}catch(e){this.eventCallback?.({type:st.WEB_RTC_REGISTER_FAILED,data:e})}}}attachRemoteAudio(e){const t=e.sessionDescriptionHandler;if(t){const e=t.peerConnection;if(!e)return;const s=new MediaStream;e.getReceivers().forEach(e=>{e.track&&"audio"===e.track.kind&&s.addTrack(e.track)});let i=document.getElementById("sip-remote-audio");i||(i=document.createElement("audio"),i.id="sip-remote-audio",i.autoplay=!0,i.style.display="none",document.body.appendChild(i)),i.srcObject=s,i.play().catch(e=>{console.error("音频播放失败,需要用户交互触发",e)})}}handleSessionState(e,t,s){e.stateChange.addListener(t=>{switch(t){case K.Established:clearTimeout(this.callTimeoutTimer),this.activeSession=e,this.attachRemoteAudio(e);break;case K.Terminating:break;case K.Terminated:this.activeSession=null,clearTimeout(this.callTimeoutTimer);case K.Establishing:}})}handleIncomingCall(e){this.incomingInvitation=e,this.handleSessionState(e,!1);const{soft_device_auto_answer:t,auto_answer_time:s}=fi.agentInfo,i=dt.get("direction"),r=1===t;if(i===tt.OUTGOING)this.answerCall();else if(r&&i===tt.INCOMING){const e=Number(s)||0;e>0?this.autoAnswerTimer=setTimeout(()=>{this.answerCall(),this.autoAnswerTimer=null},e):this.answerCall()}}async makeCall(e){if(dt.getState().isCalling)throw new Error("正在呼叫中,请勿重复点击");if(!this.userAgent)throw dt.updateIsCalling(!1),dt.updateDirection(null),new Error("SIP客户端未初始化");dt.updateIsCalling(!0),dt.updateDirection(tt.OUTGOING);const t=Xe.makeURI(`sip:${e}@${this.config.server}`);if(!t)throw new Error("无效的被叫号码");const s=new Z(this.userAgent,t);this.handleSessionState(s,!0,e);try{this.activeSession=s,await s.invite(),this.config.callTimeout&&(this.callTimeoutTimer=setTimeout(()=>{s.state!==K.Established&&(this.hangup(),this.eventCallback?.({type:"error",data:{message:"呼叫超时未接通"}}))},this.config.callTimeout))}catch(e){this.eventCallback?.({type:"error",data:{message:"呼叫失败",detail:e}}),dt.updateIsCalling(!1),dt.updateDirection(null)}}async answerCall(){if(!this.incomingInvitation)throw new Error("无来电可接听");this.autoAnswerTimer&&(clearTimeout(this.autoAnswerTimer),this.autoAnswerTimer=null);try{console.log((new Date).toLocaleString()),await this.incomingInvitation.accept(),console.log((new Date).toLocaleString()),this.activeSession=this.incomingInvitation,this.incomingInvitation=null}catch(e){this.eventCallback?.({type:st.WEB_RTC_ANSWER_FAILED,data:{detail:e}})}}async rejectInCall(){if(this.incomingInvitation)try{await this.incomingInvitation.reject(),this.incomingInvitation=null,dt.updateDirection(null),dt.updateIsCalling(!1),clearTimeout(this.callTimeoutTimer)}catch(e){this.eventCallback?.({type:"error",data:{message:"拒接失败",detail:e}})}}sendDTMF(e){if(!this.activeSession)throw new Error("当前没有活跃的通话");const t=this.activeSession.sessionDescriptionHandler;t&&"function"==typeof t.sendDtmf?(t.sendDtmf(e),this.eventCallback?.({type:st.WEB_RTC_SEND_DTMF,data:{tone:e}})):console.warn("DTMF发送不支持或未初始化")}async hangup(){if(this.activeSession){clearTimeout(this.callTimeoutTimer);const e=this.activeSession;if(!e)return;const t=e.state;try{t===K.Established?await e.bye():t===K.Establishing&&(e instanceof Z?await e.cancel():e instanceof J&&await e.reject()),clearTimeout(this.callTimeoutTimer)}catch(e){console.error("挂断失败",e)}finally{this.activeSession=null}}}async rejectOutCall(){this.activeSession instanceof J&&(await this.activeSession.reject(),this.activeSession=null)}async destroy(){if(clearTimeout(this.callTimeoutTimer),this.activeSession&&await this.hangup(),this.registerer){try{await this.registerer.unregister()}catch(e){console.warn("注销失败",e)}this.registerer=null}this.userAgent&&(await this.userAgent.stop(),this.userAgent=null)}async reconnect(){if(!fi.isRtcReconnecting){fi.isRtcReconnecting=!0;try{await this.destroy(),await this.start(),console.log("重连成功"),this.isOffline=!1}catch(e){console.error("重连失败",e)}finally{fi.isRtcReconnecting=!1}}}async getNetworkStats(){if(this.activeSession){const e=this.activeSession.sessionDescriptionHandler?.peerConnection;if(!e)return null;const t=await e.getStats(),s={};return t.forEach(e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&null!=e.currentRoundTripTime&&(s.rtt=+(1e3*e.currentRoundTripTime).toFixed(2)),"inbound-rtp"===e.type&&"audio"===e.kind&&(s.jitter=+(1e3*e.jitter).toFixed(2),s.packetsLost=e.packetsLost,s.packetsReceived=e.packetsReceived,e.bytesReceived&&e.timestamp&&(s.recvBitrate=+(e.bytesReceived/1024).toFixed(2))),"outbound-rtp"===e.type&&"audio"===e.kind&&(s.packetsSent=e.packetsSent,e.bytesSent&&e.timestamp&&(s.sendBitrate=+(e.bytesSent/1024).toFixed(2))),"codec"===e.type&&e.mimeType&&(s.codec=e.mimeType)}),{...s,rtt:s?.rtt||40}}try{const e=Date.now();await pi(`${hi}/config/ping`,{});const t=Date.now();return{rtt:t-e||1}}catch(e){console.log(e)}}}const wi={statusColor:{[et.IDLE]:"#1D92E9",[et.BUSY]:"#F5212D",[et.OFFLINE]:"#8c8c8c",[et.RINGING]:"#e9b91d"}},yi=["call_number"],bi=[],Ti=["hangup"],Si=["hold","hangup","unhold","mute","unmute","transfer","consult","satisfaction","dtmf"],Ci=["consult_transfer"],Ei=["hangup"],Ai=["answer","reject"],_i=["hangup","consult","transfer","hold","unhold","mute","unmute","satisfaction","dtmf"];let Ii=class extends Js{static{this.styles=zt`
114
114
  .timer-text {
115
115
  width: 70px;
116
116
  font-size: 14px;
117
117
  color: #fff;
118
118
  }
119
- `}constructor(){super(),this.intervalId=null,this.elapsedSeconds=0,this.displayTime="00:00:00",this.start()}formatTime(e){const t=e=>e.toString().padStart(2,"0"),s=Math.floor(e/3600),i=Math.floor(e%3600/60),r=e%60;return`${t(s)}:${t(i)}:${t(r)}`}updateTime(){this.elapsedSeconds++,this.displayTime=this.formatTime(this.elapsedSeconds)}start(){null===this.intervalId&&(this.intervalId=window.setInterval(()=>this.updateTime(),1e3))}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}reset(){this.stop(),this.elapsedSeconds=0,this.displayTime=this.formatTime(this.elapsedSeconds),this.start()}render(){return xs`<div class="timer-text">${this.displayTime}</div>`}};Bt([si()],Ii.prototype,"displayTime",void 0),Ii=Bt([Xs("timer-component")],Ii);let Ri=class extends zs{constructor(){super(...arguments),this.content="",this.placement="bottom",this.delay=0,this.color="#3356ec",this.visible=!1,this.showTooltip=()=>{this.delay>0?this.timeoutId=window.setTimeout(()=>{this.visible=!0},this.delay):this.visible=!0},this.hideTooltip=()=>{this.timeoutId&&clearTimeout(this.timeoutId),this.visible=!1}}static{this.styles=Jt`
119
+ `}constructor(){super(),this.intervalId=null,this.elapsedSeconds=0,this.displayTime="00:00:00",this.start()}formatTime(e){const t=e=>e.toString().padStart(2,"0"),s=Math.floor(e/3600),i=Math.floor(e%3600/60),r=e%60;return`${t(s)}:${t(i)}:${t(r)}`}updateTime(){this.elapsedSeconds++,this.displayTime=this.formatTime(this.elapsedSeconds)}start(){null===this.intervalId&&(this.intervalId=window.setInterval(()=>this.updateTime(),1e3))}stop(){null!==this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}reset(){this.stop(),this.elapsedSeconds=0,this.displayTime=this.formatTime(this.elapsedSeconds),this.start()}render(){return xs`<div class="timer-text">${this.displayTime}</div>`}};Bt([si()],Ii.prototype,"displayTime",void 0),Ii=Bt([Xs("timer-component")],Ii);let Ri=class extends Js{constructor(){super(...arguments),this.content="",this.placement="bottom",this.delay=0,this.color="#3356ec",this.visible=!1,this.showTooltip=()=>{this.delay>0?this.timeoutId=window.setTimeout(()=>{this.visible=!0},this.delay):this.visible=!0},this.hideTooltip=()=>{this.timeoutId&&clearTimeout(this.timeoutId),this.visible=!1}}static{this.styles=zt`
120
120
  :host {
121
121
  position: relative;
122
122
  display: inline-block;
@@ -165,7 +165,7 @@ const Xs=e=>(t,s)=>{void 0!==s?s.addInitializer(()=>{customElements.define(e,t)}
165
165
  <div class="tooltip ${this.placement} ${this.visible?"visible":""}" style="background: ${this.color}">
166
166
  ${this.content}
167
167
  </div>
168
- `}};Bt([ti({type:String})],Ri.prototype,"content",void 0),Bt([ti({type:String})],Ri.prototype,"placement",void 0),Bt([ti({type:Number})],Ri.prototype,"delay",void 0),Bt([ti({type:String})],Ri.prototype,"color",void 0),Bt([ti({type:Boolean})],Ri.prototype,"visible",void 0),Bt([function(e,t){return(s,i,r)=>{const n=t=>t.renderRoot?.querySelector(e)??null;if(t){const{get:e,set:t}="object"==typeof i?s:r??(()=>{const e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return ii(s,i,{get(){let s=e.call(this);return void 0===s&&(s=n(this),(null!==s||this.hasUpdated)&&t.call(this,s)),s}})}return ii(s,i,{get(){return n(this)}})}}("slot")],Ri.prototype,"slotElement",void 0),Ri=Bt([Xs("my-tooltip")],Ri);let $i=class extends zs{constructor(){super(...arguments),this.placement="bottom",this.triggerType="click",this.visible=!1,this.hideTimer=null,this.onTogglePopover=e=>{e.stopPropagation(),this.visible=!this.visible,this.visible&&this.updatePosition()},this.showPopover=()=>{this.clearHideTimer(),this.visible=!0,this.updatePosition()},this.hidePopoverDelayed=()=>{this.clearHideTimer(),this.hideTimer=setTimeout(()=>{this.visible=!1},200)},this.clearHideTimer=()=>{this.hideTimer&&(clearTimeout(this.hideTimer),this.hideTimer=null)},this.onOutsideClick=e=>{this.contains(e.target)||(this.visible=!1)}}static{this.styles=Jt`
168
+ `}};Bt([ti({type:String})],Ri.prototype,"content",void 0),Bt([ti({type:String})],Ri.prototype,"placement",void 0),Bt([ti({type:Number})],Ri.prototype,"delay",void 0),Bt([ti({type:String})],Ri.prototype,"color",void 0),Bt([ti({type:Boolean})],Ri.prototype,"visible",void 0),Bt([function(e,t){return(s,i,r)=>{const n=t=>t.renderRoot?.querySelector(e)??null;if(t){const{get:e,set:t}="object"==typeof i?s:r??(()=>{const e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return ii(s,i,{get(){let s=e.call(this);return void 0===s&&(s=n(this),(null!==s||this.hasUpdated)&&t.call(this,s)),s}})}return ii(s,i,{get(){return n(this)}})}}("slot")],Ri.prototype,"slotElement",void 0),Ri=Bt([Xs("my-tooltip")],Ri);let $i=class extends Js{constructor(){super(...arguments),this.placement="bottom",this.triggerType="click",this.visible=!1,this.hideTimer=null,this.onTogglePopover=e=>{e.stopPropagation(),this.visible=!this.visible,this.visible&&this.updatePosition()},this.showPopover=()=>{this.clearHideTimer(),this.visible=!0,this.updatePosition()},this.hidePopoverDelayed=()=>{this.clearHideTimer(),this.hideTimer=setTimeout(()=>{this.visible=!1},200)},this.clearHideTimer=()=>{this.hideTimer&&(clearTimeout(this.hideTimer),this.hideTimer=null)},this.onOutsideClick=e=>{this.contains(e.target)||(this.visible=!1)}}static{this.styles=zt`
169
169
  :host {
170
170
  display: inline-block;
171
171
  position: relative;
@@ -251,7 +251,7 @@ const Xs=e=>(t,s)=>{void 0!==s?s.addInitializer(()=>{customElements.define(e,t)}
251
251
  <div class="arrow" data-placement="${this.placement}"></div>
252
252
  <slot name="content"></slot>
253
253
  </div>
254
- `}};Bt([ti({type:String})],$i.prototype,"placement",void 0),Bt([ti({type:String})],$i.prototype,"triggerType",void 0),Bt([si()],$i.prototype,"visible",void 0),$i=Bt([Xs("my-popover")],$i);let Di=class extends zs{constructor(){super(...arguments),this.placeholder="",this.disabled=!1,this.allowClear=!1,this.value="",this.focused=!1}static{this.styles=Jt`
254
+ `}};Bt([ti({type:String})],$i.prototype,"placement",void 0),Bt([ti({type:String})],$i.prototype,"triggerType",void 0),Bt([si()],$i.prototype,"visible",void 0),$i=Bt([Xs("my-popover")],$i);let Di=class extends Js{constructor(){super(...arguments),this.placeholder="",this.disabled=!1,this.allowClear=!1,this.value="",this.focused=!1}static{this.styles=zt`
255
255
  :host {
256
256
  display: inline-block;
257
257
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, serif;
@@ -339,11 +339,12 @@ const Xs=e=>(t,s)=>{void 0!==s?s.addInitializer(()=>{customElements.define(e,t)}
339
339
  </span>
340
340
  <span class="suffix"><slot name="suffix"></slot></span>
341
341
  </div>
342
- `}};Bt([ti({type:String})],Di.prototype,"placeholder",void 0),Bt([ti({type:Boolean})],Di.prototype,"disabled",void 0),Bt([ti({type:Boolean})],Di.prototype,"allowClear",void 0),Bt([ti({type:String})],Di.prototype,"value",void 0),Bt([ti({attribute:!1})],Di.prototype,"onPressEnter",void 0),Bt([si()],Di.prototype,"focused",void 0),Di=Bt([Xs("my-input")],Di);let xi=class extends zs{constructor(){super(...arguments),this.placeholder="请选择",this.value=null,this.width="200px",this.open=!1,this.animating=!1,this.selectedContent=null,this.handleOutsideClick=e=>{this.contains(e.target)||this.closeDropdown()}}static{this.styles=Jt`
342
+ `}};Bt([ti({type:String})],Di.prototype,"placeholder",void 0),Bt([ti({type:Boolean})],Di.prototype,"disabled",void 0),Bt([ti({type:Boolean})],Di.prototype,"allowClear",void 0),Bt([ti({type:String})],Di.prototype,"value",void 0),Bt([ti({attribute:!1})],Di.prototype,"onPressEnter",void 0),Bt([si()],Di.prototype,"focused",void 0),Di=Bt([Xs("my-input")],Di);let xi=class extends Js{constructor(){super(...arguments),this.placeholder="请选择",this.value=null,this.width="200px",this.open=!1,this.animating=!1,this.selectedContent=null,this.handleOutsideClick=e=>{this.contains(e.target)||this.closeDropdown()}}static{this.styles=zt`
343
343
  :host {
344
344
  position: relative;
345
345
  display: inline-block;
346
346
  font-family: sans-serif;
347
+ z-index: 999999999;
347
348
  }
348
349
  .select-box {
349
350
  border-bottom: 1px solid #d9d9d9;
@@ -419,7 +420,7 @@ const Xs=e=>(t,s)=>{void 0!==s?s.addInitializer(()=>{customElements.define(e,t)}
419
420
  </div>
420
421
 
421
422
  ${this.open?xs`<div class="dropdown ${this.animating?"show":""}">${this.renderSelectOptions()}</div>`:Ns}
422
- `}};Bt([ti({type:String})],xi.prototype,"placeholder",void 0),Bt([ti({type:String})],xi.prototype,"value",void 0),Bt([ti({type:String})],xi.prototype,"width",void 0),Bt([si()],xi.prototype,"open",void 0),Bt([si()],xi.prototype,"animating",void 0),Bt([si()],xi.prototype,"selectedContent",void 0),xi=Bt([Xs("my-select")],xi);let ki=class extends zs{constructor(){super(...arguments),this.isDialerVisible=!1,this.inputValue="",this.keys=["1","2","3","4","5","6","7","8","9","*","0","#"],this.handleDocumentClick=e=>{(e.composedPath?.()||[]).includes(this)||(this.isDialerVisible=!1)},this.handleValueSize=()=>this.inputValue.length<10?26:this.inputValue.length>=10&&this.inputValue.length<20?24:this.inputValue.length>=21&&this.inputValue.length<25?18:this.inputValue.length>25?14:16}static{this.styles=Jt`
423
+ `}};Bt([ti({type:String})],xi.prototype,"placeholder",void 0),Bt([ti({type:String})],xi.prototype,"value",void 0),Bt([ti({type:String})],xi.prototype,"width",void 0),Bt([si()],xi.prototype,"open",void 0),Bt([si()],xi.prototype,"animating",void 0),Bt([si()],xi.prototype,"selectedContent",void 0),xi=Bt([Xs("my-select")],xi);let ki=class extends Js{constructor(){super(...arguments),this.isDialerVisible=!1,this.inputValue="",this.keys=["1","2","3","4","5","6","7","8","9","*","0","#"],this.handleDocumentClick=e=>{(e.composedPath?.()||[]).includes(this)||(this.isDialerVisible=!1)},this.handleValueSize=()=>this.inputValue.length<10?26:this.inputValue.length>=10&&this.inputValue.length<20?24:this.inputValue.length>=21&&this.inputValue.length<25?18:this.inputValue.length>25?14:16}static{this.styles=zt`
423
424
  .key-body {
424
425
  position: absolute;
425
426
  border: 1px solid rgba(0, 0, 0, 0.2);
@@ -479,7 +480,7 @@ const Xs=e=>(t,s)=>{void 0!==s?s.addInitializer(()=>{customElements.define(e,t)}
479
480
  </div>
480
481
  </div>
481
482
  `:Ns}
482
- `}};Bt([si()],ki.prototype,"isDialerVisible",void 0),Bt([si()],ki.prototype,"inputValue",void 0),ki=Bt([Xs("my-phone-dialer")],ki);let Ni=class extends zs{constructor(){super(...arguments),this.visible=!1,this.showFooter=!0,this.width="520px",this.title=""}static{this.styles=Jt`
483
+ `}};Bt([si()],ki.prototype,"isDialerVisible",void 0),Bt([si()],ki.prototype,"inputValue",void 0),ki=Bt([Xs("my-phone-dialer")],ki);let Ni=class extends Js{constructor(){super(...arguments),this.visible=!1,this.showFooter=!0,this.width="520px",this.title=""}static{this.styles=zt`
483
484
  .mask {
484
485
  position: fixed;
485
486
  z-index: 9999999;