ysyt-agent-sdk 1.1.19 → 1.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ysyt-agent-sdk.cjs.js +17 -17
- package/dist/ysyt-agent-sdk.esm.js +14 -14
- package/dist/ysyt-agent-sdk.umd.js +22 -22
- package/package.json +1 -1
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var A=require("crypto"),e=require("buffer");class t extends Error{constructor(A){super(A),Object.setPrototypeOf(this,new.target.prototype)}}class s extends t{constructor(A){super(A||"Unsupported content type.")}}class i extends t{constructor(A){super(A||"Request pending.")}}class n extends t{constructor(A){super(A||"Unspecified session description handler error.")}}class o extends t{constructor(){super("The session has terminated.")}}class r extends t{constructor(A){super(A||"An error occurred during state transition.")}}class a{constructor(A){this.incomingAckRequest=A}get request(){return this.incomingAckRequest.message}}class V{constructor(A){this.incomingByeRequest=A}get request(){return this.incomingByeRequest.message}accept(A){return this.incomingByeRequest.accept(A),Promise.resolve()}reject(A){return this.incomingByeRequest.reject(A),Promise.resolve()}}class c{constructor(A){this.incomingCancelRequest=A}get request(){return this.incomingCancelRequest}}class l{constructor(){this.listeners=new Array}addListener(A,e){const t=e=>{this.removeListener(t),A(e)};!0===(null==e?void 0:e.once)?this.listeners.push(t):this.listeners.push(A)}emit(A){this.listeners.slice().forEach(e=>e(A))}removeAllListeners(){this.listeners=[]}removeListener(A){this.listeners=this.listeners.filter(e=>e!==A)}on(A){return this.addListener(A)}off(A){return this.removeListener(A)}once(A){return this.addListener(A,{once:!0})}}class h{constructor(A){this.incomingInfoRequest=A}get request(){return this.incomingInfoRequest.message}accept(A){return this.incomingInfoRequest.accept(A),Promise.resolve()}reject(A){return this.incomingInfoRequest.reject(A),Promise.resolve()}}class g{constructor(A){this.parameters={};for(const e in A)A.hasOwnProperty(e)&&this.setParam(e,A[e])}setParam(A,e){A&&(this.parameters[A.toLowerCase()]=null==e?null:e.toString())}getParam(A){if(A)return this.parameters[A.toLowerCase()]}hasParam(A){return!(!A||void 0===this.parameters[A.toLowerCase()])}deleteParam(A){if(A=A.toLowerCase(),this.hasParam(A)){const e=this.parameters[A];return delete this.parameters[A],e}}clearParams(){this.parameters={}}}class q extends g{constructor(A,e,t){super(t),this.uri=A,this._displayName=e}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(A){this._displayName=A}clone(){return new q(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let A=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";A+="<"+this.uri.toString()+">";for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(A+=";"+e,null!==this.parameters[e]&&(A+="="+this.parameters[e]));return A}}class d extends g{constructor(A="sip",e,t,s,i,n){if(super(i||{}),this.headers={},!t)throw new TypeError('missing or invalid "host" parameter');for(const A in n)n.hasOwnProperty(A)&&this.setHeader(A,n[A]);this.raw={scheme:A,user:e,host:t,port:s},this.normal={scheme:A.toLowerCase(),user:e,host:t.toLowerCase(),port:s}}get scheme(){return this.normal.scheme}set scheme(A){this.raw.scheme=A,this.normal.scheme=A.toLowerCase()}get user(){return this.normal.user}set user(A){this.normal.user=this.raw.user=A}get host(){return this.normal.host}set host(A){this.raw.host=A,this.normal.host=A.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(A){this.normal.port=this.raw.port=A}setHeader(A,e){this.headers[this.headerize(A)]=e instanceof Array?e:[e]}getHeader(A){if(A)return this.headers[this.headerize(A)]}hasHeader(A){return!!A&&!!this.headers.hasOwnProperty(this.headerize(A))}deleteHeader(A){if(A=this.headerize(A),this.headers.hasOwnProperty(A)){const e=this.headers[A];return delete this.headers[A],e}}clearHeaders(){this.headers={}}clone(){return new d(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(A){let e=A.scheme+":";A.scheme.toLowerCase().match("^sips?$")||(e+="//"),A.user&&(e+=this.escapeUser(A.user)+"@"),e+=A.host,(A.port||0===A.port)&&(e+=":"+A.port);for(const A in this.parameters)this.parameters.hasOwnProperty(A)&&(e+=";"+A,null!==this.parameters[A]&&(e+="="+this.parameters[A]));const t=[];for(const A in this.headers)if(this.headers.hasOwnProperty(A))for(const e in this.headers[A])this.headers[A].hasOwnProperty(e)&&t.push(A+"="+this.headers[A][e]);return t.length>0&&(e+="?"+t.join("&")),e}escapeUser(A){let e;try{e=decodeURIComponent(A)}catch(A){throw A}return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(A){const e={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},t=A.toLowerCase().replace(/_/g,"-").split("-"),s=t.length;let i="";for(let A=0;A<s;A++)0!==A&&(i+="-"),i+=t[A].charAt(0).toUpperCase()+t[A].substring(1);return e[i]&&(i=e[i]),i}}function p(A,e){if(A.scheme!==e.scheme)return!1;if(A.user!==e.user||A.host!==e.host||A.port!==e.port)return!1;if(!function(A,e){const t=Object.keys(A.parameters),s=Object.keys(e.parameters),i=t.filter(A=>s.includes(A));return!!i.every(t=>A.parameters[t]===e.parameters[t])&&(!!["user","ttl","method","transport"].every(t=>A.hasParam(t)&&e.hasParam(t)||!A.hasParam(t)&&!e.hasParam(t))&&!!["maddr"].every(t=>A.hasParam(t)&&e.hasParam(t)||!A.hasParam(t)&&!e.hasParam(t)))}(A,e))return!1;const t=Object.keys(A.headers),s=Object.keys(e.headers);if(0!==t.length||0!==s.length){if(t.length!==s.length)return!1;const i=t.filter(A=>s.includes(A));if(i.length!==s.length)return!1;if(!i.every(t=>A.headers[t].length&&e.headers[t].length&&A.headers[t][0]===e.headers[t][0]))return!1}return!0}function u(A,e,t){return t=t||" ",A.length>e?A:(e-=A.length,A+(t+=t.repeat(e)).slice(0,e))}class m extends Error{constructor(A,e,t,s){super(),this.message=A,this.expected=e,this.found=t,this.location=s,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,m.prototype):this.__proto__=m.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,m)}static buildMessage(A,e){function t(A){return A.charCodeAt(0).toString(16).toUpperCase()}function s(A){return A.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,A=>"\\x0"+t(A)).replace(/[\x10-\x1F\x7F-\x9F]/g,A=>"\\x"+t(A))}function i(A){return A.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,A=>"\\x0"+t(A)).replace(/[\x10-\x1F\x7F-\x9F]/g,A=>"\\x"+t(A))}function n(A){switch(A.type){case"literal":return'"'+s(A.text)+'"';case"class":const e=A.parts.map(A=>Array.isArray(A)?i(A[0])+"-"+i(A[1]):i(A));return"["+(A.inverted?"^":"")+e+"]";case"any":return"any character";case"end":return"end of input";case"other":return A.description}}return"Expected "+function(A){const e=A.map(n);let t,s;if(e.sort(),e.length>0){for(t=1,s=1;t<e.length;t++)e[t-1]!==e[t]&&(e[s]=e[t],s++);e.length=s}switch(e.length){case 1:return e[0];case 2:return e[0]+" or "+e[1];default:return e.slice(0,-1).join(", ")+", or "+e[e.length-1]}}(A)+" but "+(((o=e)?'"'+s(o)+'"':"end of input")+" found.");var o}format(A){let e="Error: "+this.message;if(this.location){let t,s=null;for(t=0;t<A.length;t++)if(A[t].source===this.location.source){s=A[t].text.split(/\r\n|\n|\r/g);break}let i=this.location.start,n=this.location.source+":"+i.line+":"+i.column;if(s){let A=this.location.end,t=u("",i.line.toString().length," "),o=s[i.line-1],r=i.line===A.line?A.column:o.length+1;e+="\n --\x3e "+n+"\n"+t+" |\n"+i.line+" | "+o+"\n"+t+" | "+u("",i.column-1," ")+u("",r-i.column,"^")}else e+="\n at "+n}return e}}const C=function(A,e){const t={},s=(e=void 0!==e?e:{}).grammarSource,i={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",E("\r\n",!1),/^[0-9]/,I([["0","9"]],!1,!1),/^[a-zA-Z]/,I([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,I([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,I([["\0","ÿ"]],!1,!1),/^["]/,I(['"'],!1,!1)," ",E(" ",!1),"\t",E("\t",!1),/^[a-zA-Z0-9]/,I([["a","z"],["A","Z"],["0","9"]],!1,!1),";",E(";",!1),"/",E("/",!1),"?",E("?",!1),":",E(":",!1),"@",E("@",!1),"&",E("&",!1),"=",E("=",!1),"+",E("+",!1),"$",E("$",!1),",",E(",",!1),"-",E("-",!1),"_",E("_",!1),".",E(".",!1),"!",E("!",!1),"~",E("~",!1),"*",E("*",!1),"'",E("'",!1),"(",E("(",!1),")",E(")",!1),"%",E("%",!1),function(){return" "},function(){return":"},/^[!-~]/,I([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,I([["",""]],!1,!1),/^[\x80-\xBF]/,I([["","¿"]],!1,!1),/^[a-f]/,I([["a","f"]],!1,!1),"`",E("`",!1),"<",E("<",!1),">",E(">",!1),"\\",E("\\",!1),"[",E("[",!1),"]",E("]",!1),"{",E("{",!1),"}",E("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,I([["!","'"]],!1,!1),/^[*-[]/,I([["*","["]],!1,!1),/^[\]-~]/,I([["]","~"]],!1,!1),function(A){return A},/^[#-[]/,I([["#","["]],!1,!1),/^[\0-\t]/,I([["\0","\t"]],!1,!1),/^[\v-\f]/,I([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,I([["",""]],!1,!1),function(){(e=e||{data:{}}).data.uri=new d(e.data.scheme,e.data.user,e.data.host,e.data.port),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port},function(){(e=e||{data:{}}).data.uri=new d(e.data.scheme,e.data.user,e.data.host,e.data.port,e.data.uri_params,e.data.uri_headers),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port,delete e.data.uri_params,"SIP_URI"===e.startRule&&(e.data=e.data.uri)},"sips",E("sips",!0),"sip",E("sip",!0),function(A){(e=e||{data:{}}).data.scheme=A},function(){(e=e||{data:{}}).data.user=decodeURIComponent(u().slice(0,-1))},function(){(e=e||{data:{}}).data.password=u()},function(){return(e=e||{data:{}}).data.host=u(),e.data.host},function(){return(e=e||{data:{}}).data.host_type="domain",u()},/^[a-zA-Z0-9_\-]/,I([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,I([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(e=e||{data:{}}).data.host_type="IPv6",u()},"::",E("::",!1),function(){return(e=e||{data:{}}).data.host_type="IPv6",u()},function(){return(e=e||{data:{}}).data.host_type="IPv4",u()},"25",E("25",!1),/^[0-5]/,I([["0","5"]],!1,!1),"2",E("2",!1),/^[0-4]/,I([["0","4"]],!1,!1),"1",E("1",!1),/^[1-9]/,I([["1","9"]],!1,!1),function(A){return e=e||{data:{}},A=parseInt(A.join("")),e.data.port=A,A},"transport=",E("transport=",!0),"udp",E("udp",!0),"tcp",E("tcp",!0),"sctp",E("sctp",!0),"tls",E("tls",!0),function(A){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.transport=A.toLowerCase()},"user=",E("user=",!0),"phone",E("phone",!0),"ip",E("ip",!0),function(A){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.user=A.toLowerCase()},"method=",E("method=",!0),function(A){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.method=A},"ttl=",E("ttl=",!0),function(A){(e=e||{data:{}}).data.params||(e.data.params={}),e.data.params.ttl=A},"maddr=",E("maddr=",!0),function(A){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.maddr=A},"lr",E("lr",!0),function(){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.lr=void 0},function(A,t){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),t=null===t?void 0:t[1],e.data.uri_params[A.toLowerCase()]=t},function(A,t){A=A.join("").toLowerCase(),t=t.join(""),(e=e||{data:{}}).data.uri_headers||(e.data.uri_headers={}),e.data.uri_headers[A]?e.data.uri_headers[A].push(t):e.data.uri_headers[A]=[t]},function(){"Refer_To"===(e=e||{data:{}}).startRule&&(e.data.uri=new d(e.data.scheme,e.data.user,e.data.host,e.data.port,e.data.uri_params,e.data.uri_headers),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port,delete e.data.uri_params)},"//",E("//",!1),function(){(e=e||{data:{}}).data.scheme=u()},E("SIP",!0),function(){(e=e||{data:{}}).data.sip_version=u()},"INVITE",E("INVITE",!1),"ACK",E("ACK",!1),"VXACH",E("VXACH",!1),"OPTIONS",E("OPTIONS",!1),"BYE",E("BYE",!1),"CANCEL",E("CANCEL",!1),"REGISTER",E("REGISTER",!1),"SUBSCRIBE",E("SUBSCRIBE",!1),"NOTIFY",E("NOTIFY",!1),"REFER",E("REFER",!1),"PUBLISH",E("PUBLISH",!1),function(){return(e=e||{data:{}}).data.method=u(),e.data.method},function(A){(e=e||{data:{}}).data.status_code=parseInt(A.join(""))},function(){(e=e||{data:{}}).data.reason_phrase=u()},function(){(e=e||{data:{}}).data=u()},function(){var A,t;for(t=(e=e||{data:{}}).data.multi_header.length,A=0;A<t;A++)if(null===e.data.multi_header[A].parsed){e.data=null;break}null!==e.data?e.data=e.data.multi_header:e.data=-1},function(){var A;(e=e||{data:{}}).data.multi_header||(e.data.multi_header=[]);try{A=new q(e.data.uri,e.data.displayName,e.data.params),delete e.data.uri,delete e.data.displayName,delete e.data.params}catch(e){A=null}e.data.multi_header.push({position:a,offset:C().start.offset,parsed:A})},function(A){'"'===(A=u().trim())[0]&&(A=A.substring(1,A.length-1)),(e=e||{data:{}}).data.displayName=A},"q",E("q",!0),function(A){(e=e||{data:{}}).data.params||(e.data.params={}),e.data.params.q=A},"expires",E("expires",!0),function(A){(e=e||{data:{}}).data.params||(e.data.params={}),e.data.params.expires=A},function(A){return parseInt(A.join(""))},"0",E("0",!1),function(){return parseFloat(u())},function(A,t){(e=e||{data:{}}).data.params||(e.data.params={}),t=null===t?void 0:t[1],e.data.params[A.toLowerCase()]=t},"render",E("render",!0),"session",E("session",!0),"icon",E("icon",!0),"alert",E("alert",!0),function(){"Content_Disposition"===(e=e||{data:{}}).startRule&&(e.data.type=u().toLowerCase())},"handling",E("handling",!0),"optional",E("optional",!0),"required",E("required",!0),function(A){(e=e||{data:{}}).data=parseInt(A.join(""))},function(){(e=e||{data:{}}).data=u()},"text",E("text",!0),"image",E("image",!0),"audio",E("audio",!0),"video",E("video",!0),"application",E("application",!0),"message",E("message",!0),"multipart",E("multipart",!0),"x-",E("x-",!0),function(A){(e=e||{data:{}}).data.value=parseInt(A.join(""))},function(A){(e=e||{data:{}}).data=A},function(A){(e=e||{data:{}}).data.event=A.toLowerCase()},function(){var A=(e=e||{data:{}}).data.tag;e.data=new q(e.data.uri,e.data.displayName,e.data.params),A&&e.data.setParam("tag",A)},"tag",E("tag",!0),function(A){(e=e||{data:{}}).data.tag=A},function(A){(e=e||{data:{}}).data=parseInt(A.join(""))},function(A){(e=e||{data:{}}).data=A},function(){(e=e||{data:{}}).data=new q(e.data.uri,e.data.displayName,e.data.params)},"digest",E("Digest",!0),"realm",E("realm",!0),function(A){(e=e||{data:{}}).data.realm=A},"domain",E("domain",!0),"nonce",E("nonce",!0),function(A){(e=e||{data:{}}).data.nonce=A},"opaque",E("opaque",!0),function(A){(e=e||{data:{}}).data.opaque=A},"stale",E("stale",!0),"true",E("true",!0),function(){(e=e||{data:{}}).data.stale=!0},"false",E("false",!0),function(){(e=e||{data:{}}).data.stale=!1},"algorithm",E("algorithm",!0),"md5",E("MD5",!0),"md5-sess",E("MD5-sess",!0),function(A){(e=e||{data:{}}).data.algorithm=A.toUpperCase()},"qop",E("qop",!0),"auth-int",E("auth-int",!0),"auth",E("auth",!0),function(A){(e=e||{data:{}}).data.qop||(e.data.qop=[]),e.data.qop.push(A.toLowerCase())},function(A){(e=e||{data:{}}).data.value=parseInt(A.join(""))},function(){var A,t;for(t=(e=e||{data:{}}).data.multi_header.length,A=0;A<t;A++)if(null===e.data.multi_header[A].parsed){e.data=null;break}null!==e.data?e.data=e.data.multi_header:e.data=-1},function(){var A;(e=e||{data:{}}).data.multi_header||(e.data.multi_header=[]);try{A=new q(e.data.uri,e.data.displayName,e.data.params),delete e.data.uri,delete e.data.displayName,delete e.data.params}catch(e){A=null}e.data.multi_header.push({position:a,offset:C().start.offset,parsed:A})},function(){(e=e||{data:{}}).data=new q(e.data.uri,e.data.displayName,e.data.params)},function(){(e=e||{data:{}}).data.replaces_from_tag&&e.data.replaces_to_tag||(e.data=-1)},function(){(e=e||{data:{}}).data={call_id:e.data}},"from-tag",E("from-tag",!0),function(A){(e=e||{data:{}}).data.replaces_from_tag=A},"to-tag",E("to-tag",!0),function(A){(e=e||{data:{}}).data.replaces_to_tag=A},"early-only",E("early-only",!0),function(){(e=e||{data:{}}).data.early_only=!0},function(A,e){return e},function(A,e){return function(A,e){return[A].concat(e)}(A,e)},function(A){"Require"===(e=e||{data:{}}).startRule&&(e.data=A||[])},function(A){(e=e||{data:{}}).data.value=parseInt(A.join(""))},"active",E("active",!0),"pending",E("pending",!0),"terminated",E("terminated",!0),function(){(e=e||{data:{}}).data.state=u()},"reason",E("reason",!0),function(A){e=e||{data:{}},void 0!==A&&(e.data.reason=A)},function(A){e=e||{data:{}},void 0!==A&&(e.data.expires=A)},"retry_after",E("retry_after",!0),function(A){e=e||{data:{}},void 0!==A&&(e.data.retry_after=A)},"deactivated",E("deactivated",!0),"probation",E("probation",!0),"rejected",E("rejected",!0),"timeout",E("timeout",!0),"giveup",E("giveup",!0),"noresource",E("noresource",!0),"invariant",E("invariant",!0),function(A){"Supported"===(e=e||{data:{}}).startRule&&(e.data=A||[])},function(){var A=(e=e||{data:{}}).data.tag;e.data=new q(e.data.uri,e.data.displayName,e.data.params),A&&e.data.setParam("tag",A)},"ttl",E("ttl",!0),function(A){(e=e||{data:{}}).data.ttl=A},"maddr",E("maddr",!0),function(A){(e=e||{data:{}}).data.maddr=A},"received",E("received",!0),function(A){(e=e||{data:{}}).data.received=A},"branch",E("branch",!0),function(A){(e=e||{data:{}}).data.branch=A},"rport",E("rport",!0),function(A){e=e||{data:{}},void 0!==A&&(e.data.rport=A.join(""))},function(A){(e=e||{data:{}}).data.protocol=A},E("UDP",!0),E("TCP",!0),E("TLS",!0),E("SCTP",!0),function(A){(e=e||{data:{}}).data.transport=A},function(){(e=e||{data:{}}).data.host=u()},function(A){(e=e||{data:{}}).data.port=parseInt(A.join(""))},function(A){return parseInt(A.join(""))},function(A){"Session_Expires"===(e=e||{data:{}}).startRule&&(e.data.deltaSeconds=A)},"refresher",E("refresher",!1),"uas",E("uas",!1),"uac",E("uac",!1),function(A){"Session_Expires"===(e=e||{data:{}}).startRule&&(e.data.refresher=A)},function(A){"Min_SE"===(e=e||{data:{}}).startRule&&(e.data=A)},"stuns",E("stuns",!0),"stun",E("stun",!0),function(A){(e=e||{data:{}}).data.scheme=A},function(A){(e=e||{data:{}}).data.host=A},"?transport=",E("?transport=",!1),"turns",E("turns",!0),"turn",E("turn",!0),function(A){(e=e||{data:{}}).data.transport=A},function(){(e=e||{data:{}}).data=u()},"Referred-By",E("Referred-By",!1),"b",E("b",!1),"cid",E("cid",!1)],r=[B('2 ""6 7!'),B('4"""5!7#'),B('4$""5!7%'),B('4&""5!7\''),B(";'.# &;("),B('4(""5!7)'),B('4*""5!7+'),B('2,""6,7-'),B('2.""6.7/'),B('40""5!71'),B('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'),B(";).# &;,"),B('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),B('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),B('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),B(';.." &"'),B("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),B('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),B('4\\""5!7].# &;3'),B('4^""5!7_'),B('4`""5!7a'),B(';!.) &4b""5!7c'),B('%$;). &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&&&#/"!&,)'),B('%$;). &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&&&#/"!&,)'),B('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.) &;\'.# &;('),B('%$;).ī &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&&&#/"!&,)'),B("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),B("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),B("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),B("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),B("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),B('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),B('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),B("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),B("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),B("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),B("%;//0#;&/'$8\":~\" )(\"'#&'#"),B("%;&/0#;//'$8\":~\" )(\"'#&'#"),B("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),B('4""5!7.A &4""5!7.5 &4""5!7.) &;3.# &;.'),B("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),B("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:
$!!)($'#(#'#(\"'#&'#"),B(';..G &2L""6L7M.; &4""5!7./ &4""5!7.# &;3'),B('%2j""6j7k/J#4""5!7.5 &4""5!7.) &4""5!7/#$+")("\'#&\'#'),B("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:$ )($'#(#'#(\"'#&'#"),B("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),B('%3""5$7.) &3""5#7/\' 8!:!! )'),B('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:# )(#\'#("\'#&\'#'),B("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),B('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'),B('%$;+._ &;-.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!:! )'),B('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),B("%;U.) &;\\.# &;X/& 8!:! )"),B('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:# )(#\'#("\'#&\'#'),B('$4""5!7/,#0)*4""5!7&&&#'),B('%4$""5!7%/?#$4""5!70)*4""5!7&/#$+")("\'#&\'#'),B('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),B('%%;Z/³#28""6879/¤$;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2""67/,#;[/#$+")("\'#&\'#.ծ &%2""67/,#;Z/#$+")("\'#&\'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2""67/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),B('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),B("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),B("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),B('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#. &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7/,#;!/#$+")("\'#&\'#.# &;!'),B('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),B('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),B(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),B('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),B('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),B('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),B('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),B('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),B('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),B('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),B('%$;j/�#*;j&&&#/"!&,)'),B('%$;j/�#*;j&&&#/"!&,)'),B(";k.) &;+.# &;-"),B('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),B('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),B('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),B("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),B("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),B('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),B(";.# &;r"),B("%;/G#;'/>$;s/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),B(";M.# &;t"),B("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),B('%;v.# &;w/J#%26""6677/,#;/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),B('%2Ð""6Ð7Ñ/:#;/1$;w." &"/#$+#)(#\'#("\'#&\'#'),B('%24""6475/,#;{/#$+")("\'#&\'#'),B("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),B(";*.) &;+.# &;-"),B(';+. &;-. &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'),B('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),B('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),B("$;~0#*;~&"),B(';+.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'),B('%%;"/#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),B(";.# &;"),B('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),B('$;+. &;-.} &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&&&#'),B("$;y0#*;y&"),B('%3""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),B('2Õ""6Õ7Ö'),B('2×""6×7Ø'),B('2Ù""6Ù7Ú'),B('2Û""6Û7Ü'),B('2Ý""6Ý7Þ'),B('2ß""6ß7à'),B('2á""6á7â'),B('2ã""6ã7ä'),B('2å""6å7æ'),B('2ç""6ç7è'),B('2é""6é7ê'),B("%;
.Y &;.S &;.M &;.G &;.A &;.; &;.5 &;./ &;.) &;.# &;6/& 8!:ë! )"),B("%;/G#;'/>$;/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),B("%;/' 8!:ì!! )"),B("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),B("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),B("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),B("%;:.c &%;/Y#$%;A/,#;/#$+\")(\"'#&'#06*%;A/,#;/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),B("%;L.# &;/]#$%;B/,#;/#$+\")(\"'#&'#06*%;B/,#;/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),B("%;.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),B("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),B(";.) &;.# &; "),B("%3ò\"\"5!7ó/:#;</1$;/($8#:ô#! )(#'#(\"'#&'#"),B("%3õ\"\"5'7ö/:#;</1$;/($8#:÷#! )(#'#(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:ø!! )"),B('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),B('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),B(";6.) &;T.# &;H"),B("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),B(";¥.# &; "),B('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),B("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:Č!! )"),B("%;©/& 8!:č! )"),B("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),B(";«.# &;¬"),B('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;'),B('3Ę""5\'7ę./ &3Ě""5)7ě.# &;'),B(";6.# &;®"),B('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),B(";.# &;6"),B("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),B(";6.# &;H"),B("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:Ğ!! )"),B("%;/' 8!:ğ!! )"),B('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),B('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),B("%;L.# &;/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),B(";¹.# &; "),B("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:ĥ!! )"),B("%;/' 8!:Ħ!! )"),B("%$;0#*;&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),B(";¾"),B("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),B("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),B("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),B(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),B("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),B("%;I/' 8!:Ĭ!! )"),B("%3ĭ\"\"5&7Į/#;</$;D/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),B(";t.# &;w"),B("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),B("%;I/' 8!:ı!! )"),B("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),B('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),B('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),B('%3ń""5#7Ņ/#;</$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),B('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),B("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),B("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),B("%;/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),B('%;L.O &;.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),B("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),B("%;/& 8!:Ő! )"),B('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),B('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),B("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%;/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:ŝ!! )"),B("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),B("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;/($8#:ū#! )(#'#(\"'#&'#.# &; "),B('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'),B(';1." &"'),B('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),B("%;L.# &;/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),B(";¹.# &; "),B("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),B(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),B("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),B("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),B("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),B("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),B("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),B("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),B('%3""5#7Ó.# &;6/\' 8!:Ƌ!! )'),B('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),B('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),B("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),B('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),B('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),B(";¾"),B('%;/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),B(";ô.# &; "),B('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),B('%;/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),B("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),B("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),B("$;%0#*;%&"),B("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),B('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),B('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),B("%;\\.) &;X.# &;/' 8!:Ƣ!! )"),B(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),B('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?'),B('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),B('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),B('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),B("%;Ą/#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),B("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),B("%;ă/,#;ă/#$+\")(\"'#&'#"),B("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),B("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),B('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),B(";.# &;L"),B("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),B("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let a=0,V=0;const c=[{line:1,column:1}];let l,h=0,g=[],p=0;if(void 0!==e.startRule){if(!(e.startRule in i))throw new Error("Can't start parsing from rule \""+e.startRule+'".');n=i[e.startRule]}function u(){return A.substring(V,a)}function C(){return M(V,a)}function E(A,e){return{type:"literal",text:A,ignoreCase:e}}function I(A,e,t){return{type:"class",parts:A,inverted:e,ignoreCase:t}}function w(e){let t,s=c[e];if(s)return s;for(t=e-1;!c[t];)t--;for(s=c[t],s={line:s.line,column:s.column};t<e;)10===A.charCodeAt(t)?(s.line++,s.column=1):s.column++,t++;return c[e]=s,s}function M(A,e){const t=w(A),i=w(e);return{source:s,start:{offset:A,line:t.line,column:t.column},end:{offset:e,line:i.line,column:i.column}}}function f(A){a<h||(a>h&&(h=a,g=[]),g.push(A))}function B(A){return A.split("").map(A=>A.charCodeAt(0)-32)}if(e.data={},l=function e(s){const i=r[s];let n=0;const c=[];let l=i.length;const h=[],g=[];let q;for(;;){for(;n<l;)switch(i[n]){case 0:g.push(o[i[n+1]]),n+=2;break;case 1:g.push(void 0),n++;break;case 2:g.push(null),n++;break;case 3:g.push(t),n++;break;case 4:g.push([]),n++;break;case 5:g.push(a),n++;break;case 6:g.pop(),n++;break;case 7:a=g.pop(),n++;break;case 8:g.length-=i[n+1],n+=2;break;case 9:g.splice(-2,1),n++;break;case 10:g[g.length-2].push(g.pop()),n++;break;case 11:g.push(g.splice(g.length-i[n+1],i[n+1])),n+=2;break;case 12:g.push(A.substring(g.pop(),a)),n++;break;case 13:h.push(l),c.push(n+3+i[n+1]+i[n+2]),g[g.length-1]?(l=n+3+i[n+1],n+=3):(l=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 14:h.push(l),c.push(n+3+i[n+1]+i[n+2]),g[g.length-1]===t?(l=n+3+i[n+1],n+=3):(l=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 15:h.push(l),c.push(n+3+i[n+1]+i[n+2]),g[g.length-1]!==t?(l=n+3+i[n+1],n+=3):(l=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 16:g[g.length-1]!==t?(h.push(l),c.push(n),l=n+2+i[n+1],n+=2):n+=2+i[n+1];break;case 17:h.push(l),c.push(n+3+i[n+1]+i[n+2]),A.length>a?(l=n+3+i[n+1],n+=3):(l=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 18:h.push(l),c.push(n+4+i[n+2]+i[n+3]),A.substr(a,o[i[n+1]].length)===o[i[n+1]]?(l=n+4+i[n+2],n+=4):(l=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 19:h.push(l),c.push(n+4+i[n+2]+i[n+3]),A.substr(a,o[i[n+1]].length).toLowerCase()===o[i[n+1]]?(l=n+4+i[n+2],n+=4):(l=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 20:h.push(l),c.push(n+4+i[n+2]+i[n+3]),o[i[n+1]].test(A.charAt(a))?(l=n+4+i[n+2],n+=4):(l=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 21:g.push(A.substr(a,i[n+1])),a+=i[n+1],n+=2;break;case 22:g.push(o[i[n+1]]),a+=o[i[n+1]].length,n+=2;break;case 23:g.push(t),0===p&&f(o[i[n+1]]),n+=2;break;case 24:V=g[g.length-1-i[n+1]],n+=2;break;case 25:V=a,n++;break;case 26:q=i.slice(n+4,n+4+i[n+3]).map(function(A){return g[g.length-1-A]}),g.splice(g.length-i[n+2],i[n+2],o[i[n+1]].apply(null,q)),n+=4+i[n+3];break;case 27:g.push(e(i[n+1])),n+=2;break;case 28:p++,n++;break;case 29:p--,n++;break;default:throw new Error("Invalid opcode: "+i[n]+".")}if(!(h.length>0))break;l=h.pop(),n=c.pop()}return g[0]}(n),l!==t&&a===A.length)return l;throw l!==t&&a<A.length&&f({type:"end"}),S=g,Q=h<A.length?A.charAt(h):null,T=h<A.length?M(h,h+1):M(h,h),new m(m.buildMessage(S,Q),S,Q,T);var S,Q,T};var E;!function(A){A.parse=function(A,e){const t={startRule:e};try{C(A,t)}catch(A){t.data=-1}return t.data},A.nameAddrHeaderParse=function(e){const t=A.parse(e,"Name_Addr_Header");return-1!==t?t:void 0},A.URIParse=function(e){const t=A.parse(e,"SIP_URI");return-1!==t?t:void 0}}(E=E||(E={}));const I={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 w(A,e=32){let t="";for(let s=0;s<A;s++){t+=Math.floor(Math.random()*e).toString(e)}return t}function M(A){return I[A]||""}function f(){return w(10)}function B(A){const e={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},t=A.toLowerCase().replace(/_/g,"-").split("-"),s=t.length;let i="";for(let A=0;A<s;A++)0!==A&&(i+="-"),i+=t[A].charAt(0).toUpperCase()+t[A].substring(1);return e[i]&&(i=e[i]),i}function S(A){return encodeURIComponent(A).replace(/%[A-F\d]{2}/g,"U").length}class Q{constructor(){this.headers={}}addHeader(A,e){const t={raw:e};A=B(A),this.headers[A]?this.headers[A].push(t):this.headers[A]=[t]}getHeader(A){const e=this.headers[B(A)];if(e)return e[0]?e[0].raw:void 0}getHeaders(A){const e=this.headers[B(A)],t=[];if(!e)return[];for(const A of e)t.push(A.raw);return t}hasHeader(A){return!!this.headers[B(A)]}parseHeader(A,e=0){if(A=B(A),!this.headers[A])return;if(e>=this.headers[A].length)return;const t=this.headers[A][e],s=t.raw;if(t.parsed)return t.parsed;const i=E.parse(s,A.replace(/-/g,"_"));return-1===i?void this.headers[A].splice(e,1):(t.parsed=i,i)}s(A,e=0){return this.parseHeader(A,e)}setHeader(A,e){this.headers[B(A)]=[{raw:e}]}toString(){return this.data}}class T extends Q{constructor(){super()}}class y extends Q{constructor(){super()}}class D{constructor(A,e,t,s,i,n,o){this.headers={},this.extraHeaders=[],this.options=D.getDefaultOptions(),i&&(this.options=Object.assign(Object.assign({},this.options),i),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=A,this.ruri=e.clone(),this.fromURI=t.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:f(),this.from=D.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=s.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+w(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(A,e,t){const s={};return t&&(s.tag=t),new q(A,e,s)}getHeader(A){const e=this.headers[B(A)];if(e){if(e[0])return e[0]}else{const e=new RegExp("^\\s*"+A+"\\s*:","i");for(const A of this.extraHeaders)if(e.test(A))return A.substring(A.indexOf(":")+1).trim()}}getHeaders(A){const e=[],t=this.headers[B(A)];if(t)for(const A of t)e.push(A);else{const t=new RegExp("^\\s*"+A+"\\s*:","i");for(const A of this.extraHeaders)t.test(A)&&e.push(A.substring(A.indexOf(":")+1).trim())}return e}hasHeader(A){if(this.headers[B(A)])return!0;{const e=new RegExp("^\\s*"+A+"\\s*:","i");for(const A of this.extraHeaders)if(e.test(A))return!0}return!1}setHeader(A,e){this.headers[B(A)]=e instanceof Array?e:[e]}setViaHeader(A,e){this.options.hackViaTcp&&(e="TCP");let t="SIP/2.0/"+e;t+=" "+this.options.viaHost+";branch="+A,this.options.forceRport&&(t+=";rport"),this.setHeader("via",t),this.branch=A}toString(){let A="";A+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const e in this.headers)if(this.headers[e])for(const t of this.headers[e])A+=e+": "+t+"\r\n";for(const e of this.extraHeaders)A+=e.trim()+"\r\n";return A+="Supported: "+this.options.optionTags.join(", ")+"\r\n",A+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(A+="Content-Length: "+S(this.body)+"\r\n\r\n",A+=this.body):this.body.body&&this.body.contentType?(A+="Content-Type: "+this.body.contentType+"\r\n",A+="Content-Length: "+S(this.body.body)+"\r\n\r\n",A+=this.body.body):A+="Content-Length: 0\r\n\r\n":A+="Content-Length: 0\r\n\r\n",A}}function R(A){return"application/sdp"===A?"session":"render"}function U(A){const e="string"==typeof A?A:A.body,t="string"==typeof A?"application/sdp":A.contentType;return{contentDisposition:R(t),contentType:t,content:e}}function k(A){return!(!A||"string"!=typeof A.content||"string"!=typeof A.contentType||void 0!==A.contentDisposition)||"string"==typeof A.contentDisposition}function G(A){let e,t,s;if(A instanceof T&&A.body){const i=A.parseHeader("Content-Disposition");e=i?i.type:void 0,t=A.parseHeader("Content-Type"),s=A.body}if(A instanceof y&&A.body){const i=A.parseHeader("Content-Disposition");e=i?i.type:void 0,t=A.parseHeader("Content-Type"),s=A.body}if(A instanceof D&&A.body)if(e=A.getHeader("Content-Disposition"),t=A.getHeader("Content-Type"),"string"==typeof A.body){if(!t)throw new Error("Header content type header does not equal body content type.");s=A.body}else{if(t&&t!==A.body.contentType)throw new Error("Header content type header does not equal body content type.");t=A.body.contentType,s=A.body.body}if(k(A)&&(e=A.contentDisposition,t=A.contentType,s=A.content),s){if(t&&!e&&(e=R(t)),!e)throw new Error("Content disposition undefined.");if(!t)throw new Error("Content type undefined.");return{contentDisposition:e,contentType:t,content:s}}}var F,Y;!function(A){A.Initial="Initial",A.Early="Early",A.AckWait="AckWait",A.Confirmed="Confirmed",A.Terminated="Terminated"}(F=F||(F={})),function(A){A.Initial="Initial",A.HaveLocalOffer="HaveLocalOffer",A.HaveRemoteOffer="HaveRemoteOffer",A.Stable="Stable",A.Closed="Closed"}(Y=Y||(Y={}));const x=500,v=5e3,Z={T1:x,T2:4e3,T4:v,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 O extends t{constructor(A){super(A||"Transaction state error.")}}var N;!function(A){A.ACK="ACK",A.BYE="BYE",A.CANCEL="CANCEL",A.INFO="INFO",A.INVITE="INVITE",A.MESSAGE="MESSAGE",A.NOTIFY="NOTIFY",A.OPTIONS="OPTIONS",A.REGISTER="REGISTER",A.UPDATE="UPDATE",A.SUBSCRIBE="SUBSCRIBE",A.PUBLISH="PUBLISH",A.REFER="REFER",A.PRACK="PRACK"}(N=N||(N={}));const K=[N.ACK,N.BYE,N.CANCEL,N.INFO,N.INVITE,N.MESSAGE,N.NOTIFY,N.OPTIONS,N.PRACK,N.REFER,N.REGISTER,N.SUBSCRIBE];class b{constructor(A){this.incomingMessageRequest=A}get request(){return this.incomingMessageRequest.message}accept(A){return this.incomingMessageRequest.accept(A),Promise.resolve()}reject(A){return this.incomingMessageRequest.reject(A),Promise.resolve()}}let J=class{constructor(A){this.incomingNotifyRequest=A}get request(){return this.incomingNotifyRequest.message}accept(A){return this.incomingNotifyRequest.accept(A),Promise.resolve()}reject(A){return this.incomingNotifyRequest.reject(A),Promise.resolve()}};class L{constructor(A,e){this.incomingReferRequest=A,this.session=e}get referTo(){const A=this.incomingReferRequest.message.parseHeader("refer-to");if(!(A instanceof q))throw new Error("Failed to parse Refer-To header.");return A}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const A=this.referTo.uri.getHeader("replaces");return A instanceof Array?A[0]:A}get request(){return this.incomingReferRequest.message}accept(A={statusCode:202}){return this.incomingReferRequest.accept(A),Promise.resolve()}reject(A){return this.incomingReferRequest.reject(A),Promise.resolve()}makeInviter(A){if(this.inviter)return this.inviter;const e=this.referTo.uri.clone();e.clearHeaders();const t=((A=A||{}).extraHeaders||[]).slice(),s=this.replaces;s&&t.push("Replaces: "+decodeURIComponent(s));const i=this.referredBy;return i&&t.push("Referred-By: "+i),A.extraHeaders=t,this.inviter=this.session.userAgent._makeInviter(e,A),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var H,j;!function(A){A.Initial="Initial",A.Establishing="Establishing",A.Established="Established",A.Terminating="Terminating",A.Terminated="Terminated"}(H=H||(H={}));class W{constructor(A,e={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=H.Initial,this.delegate=e.delegate,this._stateEventEmitter=new l,this._userAgent=A}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 H.Initial:case H.Establishing:break;case H.Established:return new Promise(A=>{this._bye({onAccept:()=>A(),onRedirect:()=>A(),onReject:()=>A()})});case H.Terminating:case H.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(A){this._sessionDescriptionHandlerModifiers=A.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(A){this._sessionDescriptionHandlerOptions=Object.assign({},A)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(A){this._sessionDescriptionHandlerModifiersReInvite=A.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(A){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},A)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(A={}){let e="Session.bye() may only be called if established session.";switch(this.state){case H.Initial:"function"==typeof this.cancel?(e+=" However Inviter.invite() has not yet been called.",e+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(e+=" However Invitation.accept() has not yet been called.",e+=" Perhaps you should have called Invitation.reject()?");break;case H.Establishing:"function"==typeof this.cancel?(e+=" However a dialog does not yet exist.",e+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(e+=" However Invitation.accept() has not yet been called (or not yet resolved).",e+=" Perhaps you should have called Invitation.reject()?");break;case H.Established:{const e=A.requestDelegate,t=this.copyRequestOptions(A.requestOptions);return this._bye(e,t)}case H.Terminating:e+=" However this session is already terminating.","function"==typeof this.cancel?e+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(e+=" Perhaps you have already called Session.bye()?");break;case H.Terminated:e+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(A={}){if(this.state!==H.Established){const A="Session.info() may only be called if established session.";return this.logger.error(A),Promise.reject(new Error(`Invalid session state ${this.state}`))}const e=A.requestDelegate,t=this.copyRequestOptions(A.requestOptions);return this._info(e,t)}invite(A={}){if(this.logger.log("Session.invite"),this.state!==H.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new i("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,A.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=A.sessionDescriptionHandlerModifiers),A.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=A.sessionDescriptionHandlerOptions);const e={onAccept:e=>{const t=G(e.message);if(!t)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(H.Terminated),void(this.pendingReinvite=!1);if(A.withoutSdp){const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(t,s).then(A=>{e.ack({body:A})}).catch(A=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(A.message),this.state===H.Terminated?e.ack():(this.ackAndBye(e,488,"Bad Media Description"),this.stateTransition(H.Terminated))}).then(()=>{this.pendingReinvite=!1,A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e)})}else{const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(t,s).then(()=>{e.ack()}).catch(A=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(A.message),this.state!==H.Terminated?(this.ackAndBye(e,488,"Bad Media Description"),this.stateTransition(H.Terminated)):e.ack()}).then(()=>{this.pendingReinvite=!1,A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e)})}},onProgress:A=>{},onRedirect:A=>{},onReject:e=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,A.withoutSdp?A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e):this.rollbackOffer().catch(A=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(A.message),this.state!==H.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const A=[];A.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated)}}).then(()=>{A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e)})},onTrying:A=>{}},t=A.requestOptions||{};if(t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push("Allow: "+K.toString()),t.extraHeaders.push("Contact: "+this._contact),A.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(e,t))}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(s).then(A=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return t.body=A,this.dialog.invite(e,t)}).catch(A=>{throw this.logger.error(A.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,A})}message(A={}){if(this.state!==H.Established){const A="Session.message() may only be called if established session.";return this.logger.error(A),Promise.reject(new Error(`Invalid session state ${this.state}`))}const e=A.requestDelegate,t=this.copyRequestOptions(A.requestOptions);return this._message(e,t)}refer(A,e={}){if(this.state!==H.Established){const A="Session.refer() may only be called if established session.";return this.logger.error(A),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(A instanceof W&&!A.dialog){const A="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(A),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return s.extraHeaders=s.extraHeaders?s.extraHeaders.concat(this.referExtraHeaders(this.referToString(A))):this.referExtraHeaders(this.referToString(A)),this._refer(e.onNotify,t,s)}_bye(A,e){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const t=this.dialog;switch(t.sessionState){case F.Initial:case F.Early:throw new Error(`Invalid dialog state ${t.sessionState}`);case F.AckWait:return this.stateTransition(H.Terminating),new Promise(s=>{t.delegate={onAck:()=>{const i=t.bye(A,e);return this.stateTransition(H.Terminated),s(i),Promise.resolve()},onAckTimeout:()=>{const i=t.bye(A,e);this.stateTransition(H.Terminated),s(i)}}});case F.Confirmed:{const s=t.bye(A,e);return this.stateTransition(H.Terminated),Promise.resolve(s)}case F.Terminated:throw new Error(`Invalid dialog state ${t.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(A,e){return this.dialog?Promise.resolve(this.dialog.info(A,e)):Promise.reject(new Error("Session dialog undefined."))}_message(A,e){return this.dialog?Promise.resolve(this.dialog.message(A,e)):Promise.reject(new Error("Session dialog undefined."))}_refer(A,e,t){return this.dialog?(this.onNotify=A,Promise.resolve(this.dialog.refer(e,t))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(A,e,t){A.ack();const s=[];e&&s.push("Reason: "+this.getReasonHeaderValue(e,t)),A.session.bye(void 0,{extraHeaders:s})}onAckRequest(A){if(this.logger.log("Session.onAckRequest"),this.state!==H.Established&&this.state!==H.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const e=this.dialog;if(!e)throw new Error("Dialog undefined.");const t={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const e=new a(A);this.delegate.onAck(e)}switch(this.pendingReinviteAck=!1,e.signalingState){case Y.Initial:{this.logger.error(`Invalid signaling state ${e.signalingState}.`);const A=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return e.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated),Promise.resolve()}case Y.Stable:{const s=G(A.message);return s?"render"===s.contentDisposition?(this._renderbody=s.content,this._rendertype=s.contentType,Promise.resolve()):"session"!==s.contentDisposition?Promise.resolve():this.setAnswer(s,t).catch(A=>{this.logger.error(A.message);const t=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];e.bye(void 0,{extraHeaders:t}),this.stateTransition(H.Terminated)}):Promise.resolve()}case Y.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${e.signalingState}.`);const A=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return e.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated),Promise.resolve()}case Y.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${e.signalingState}.`);const A=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return e.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated),Promise.resolve()}case Y.Closed:default:throw new Error(`Invalid signaling state ${e.signalingState}.`)}}onByeRequest(A){if(this.logger.log("Session.onByeRequest"),this.state===H.Established){if(this.delegate&&this.delegate.onBye){const e=new V(A);this.delegate.onBye(e)}else A.accept();this.stateTransition(H.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(A){if(this.logger.log("Session.onInfoRequest"),this.state===H.Established)if(this.delegate&&this.delegate.onInfo){const e=new h(A);this.delegate.onInfo(e)}else A.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(A){if(this.logger.log("Session.onInviteRequest"),this.state!==H.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const e=["Contact: "+this._contact];if(A.message.hasHeader("P-Asserted-Identity")){const e=A.message.getHeader("P-Asserted-Identity");if(!e)throw new Error("Header undefined.");this._assertedIdentity=E.nameAddrHeaderParse(e)}const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(t).then(t=>{const s=A.accept({statusCode:200,extraHeaders:e,body:t});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(A.message,s.message,200)}).catch(e=>{if(this.logger.error(e.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===Y.Stable){const e=A.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(A.message,e.message,488))}this.rollbackOffer().then(()=>{const e=A.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(A.message,e.message,488)}).catch(e=>{this.logger.error(e.message),this.logger.error("Failed to rollback offer on re-INVITE request");const t=A.reject({statusCode:488});if(this.state!==H.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const A=[];A.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(A.message,t.message,488)})})}onMessageRequest(A){if(this.logger.log("Session.onMessageRequest"),this.state===H.Established)if(this.delegate&&this.delegate.onMessage){const e=new b(A);this.delegate.onMessage(e)}else A.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(A){if(this.logger.log("Session.onNotifyRequest"),this.state===H.Established){if(this.onNotify){const e=new J(A);return void this.onNotify(e)}if(this.delegate&&this.delegate.onNotify){const e=new J(A);this.delegate.onNotify(e)}else A.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(A){if(this.logger.log("Session.onPrackRequest"),this.state===H.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(A){if(this.logger.log("Session.onReferRequest"),this.state!==H.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!A.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void A.reject();const e=new L(A,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(e):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),e.accept().then(()=>e.makeInviter(this._referralInviterOptions).invite()).catch(A=>{this.logger.error(A.message)}))}generateResponseOfferAnswer(A,e){if(this.dialog)return this.generateResponseOfferAnswerInDialog(e);const t=G(A.message);return t&&"session"===t.contentDisposition?this.setOfferAndGetAnswer(t,e):this.getOffer(e)}generateResponseOfferAnswerInDialog(A){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case Y.Initial:return this.getOffer(A);case Y.HaveLocalOffer:return Promise.resolve(void 0);case Y.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,A);case Y.Stable:return this.state!==H.Established?Promise.resolve(void 0):this.getOffer(A);case Y.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(A){const e=this.setupSessionDescriptionHandler(),t=A.sessionDescriptionHandlerOptions,s=A.sessionDescriptionHandlerModifiers;try{return e.getDescription(t,s).then(A=>U(A)).catch(A=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const e=A instanceof Error?A:new Error("Session.getOffer unknown error.");throw this.logger.error(e.message),e})}catch(A){this.logger.error("Session.getOffer: SDH getDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}}rollbackOffer(){const A=this.setupSessionDescriptionHandler();if(void 0===A.rollbackDescription)return Promise.resolve();try{return A.rollbackDescription().catch(A=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const e=A instanceof Error?A:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(e.message),e})}catch(A){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}}setAnswer(A,e){const t=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,n=e.sessionDescriptionHandlerModifiers;try{if(!t.hasDescription(A.contentType))return Promise.reject(new s)}catch(A){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}try{return t.setDescription(A.content,i,n).catch(A=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const e=A instanceof Error?A:new Error("Session.setAnswer unknown error.");throw this.logger.error(e.message),e})}catch(A){this.logger.error("Session.setAnswer: SDH setDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}}setOfferAndGetAnswer(A,e){const t=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,n=e.sessionDescriptionHandlerModifiers;try{if(!t.hasDescription(A.contentType))return Promise.reject(new s)}catch(A){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}try{return t.setDescription(A.content,i,n).then(()=>t.getDescription(i,n)).then(A=>U(A)).catch(A=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const e=A instanceof Error?A:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(e.message),e})}catch(A){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}}setSessionDescriptionHandler(A){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=A}setupSessionDescriptionHandler(){var A;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(A=this.delegate)||void 0===A?void 0:A.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(A){const e=()=>{throw new Error(`Invalid state transition from ${this._state} to ${A}`)};switch(this._state){case H.Initial:A!==H.Establishing&&A!==H.Established&&A!==H.Terminating&&A!==H.Terminated&&e();break;case H.Establishing:A!==H.Established&&A!==H.Terminating&&A!==H.Terminated&&e();break;case H.Established:A!==H.Terminating&&A!==H.Terminated&&e();break;case H.Terminating:A!==H.Terminated&&e();break;case H.Terminated:e();break;default:throw new Error("Unrecognized state.")}this._state=A,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),A===H.Terminated&&this.dispose()}copyRequestOptions(A={}){return{extraHeaders:A.extraHeaders?A.extraHeaders.slice():void 0,body:A.body?{contentDisposition:A.body.contentDisposition||"render",contentType:A.body.contentType||"text/plain",content:A.body.content||""}:void 0}}getReasonHeaderValue(A,e){const t=A;let s=M(A);return!s&&e&&(s=e),"SIP;cause="+t+';text="'+s+'"'}referExtraHeaders(A){const e=[];return e.push("Referred-By: <"+this.userAgent.configuration.uri+">"),e.push("Contact: "+this._contact),e.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.push("Refer-To: "+A),e}referToString(A){let e;if(A instanceof d)e=A.toString();else{if(!A.dialog)throw new Error("Dialog undefined.");const t=A.remoteIdentity.friendlyName,s=A.dialog.remoteTarget.toString(),i=A.dialog.callId,n=A.dialog.remoteTag,o=A.dialog.localTag;e=`"${t}" <${s}?Replaces=${encodeURIComponent(`${i};to-tag=${n};from-tag=${o}`)}>`}return e}}!function(A){A.Required="Required",A.Supported="Supported",A.Unsupported="Unsupported"}(j=j||(j={}));const P={"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 W{constructor(A,e){super(A),this.incomingInviteRequest=e,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=A.getLogger("sip.Invitation");const t=this.incomingInviteRequest.message,s=t.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(this.rel100="required");const i=t.getHeader("supported");if(i&&i.toLowerCase().includes("100rel")&&(this.rel100="supported"),t.toTag=e.toTag,"string"!=typeof t.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{e.reject({statusCode:480}),this.stateTransition(H.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),t.hasHeader("expires")){const A=1e3*Number(t.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===H.Initial&&(e.reject({statusCode:487}),this.stateTransition(H.Terminated))},A)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=E.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=t.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=t.body,this._rendertype=t.getHeader("Content-Type")),this._id=t.callId+t.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 H.Initial:case H.Establishing:return this.reject().then(()=>super.dispose());case H.Established:case H.Terminating:case H.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(A={}){if(this.logger.log("Invitation.accept"),this.state!==H.Initial){const A=new Error(`Invalid session state ${this.state}`);return this.logger.error(A.message),Promise.reject(A)}return A.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=A.sessionDescriptionHandlerModifiers),A.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=A.sessionDescriptionHandlerOptions),this.stateTransition(H.Establishing),this.sendAccept(A).then(({message:A,session:e})=>{e.delegate={onAck:A=>this.onAckRequest(A),onAckTimeout:()=>this.onAckTimeout(),onBye:A=>this.onByeRequest(A),onInfo:A=>this.onInfoRequest(A),onInvite:A=>this.onInviteRequest(A),onMessage:A=>this.onMessageRequest(A),onNotify:A=>this.onNotifyRequest(A),onPrack:A=>this.onPrackRequest(A),onRefer:A=>this.onReferRequest(A)},this._dialog=e,this.stateTransition(H.Established),this._replacee&&this._replacee._bye()}).catch(A=>this.handleResponseError(A))}progress(A={}){if(this.logger.log("Invitation.progress"),this.state!==H.Initial){const A=new Error(`Invalid session state ${this.state}`);return this.logger.error(A.message),Promise.reject(A)}const e=A.statusCode||180;if(e<100||e>199)throw new TypeError("Invalid statusCode: "+e);return A.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=A.sessionDescriptionHandlerModifiers),A.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=A.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===A.statusCode?this.sendProgressTrying().then(()=>{}).catch(A=>this.handleResponseError(A)):"required"===this.rel100||"supported"===this.rel100&&A.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===j.Required?this.sendProgressReliableWaitForPrack(A).then(()=>{}).catch(A=>this.handleResponseError(A)):this.sendProgress(A).then(()=>{}).catch(A=>this.handleResponseError(A))}reject(A={}){if(this.logger.log("Invitation.reject"),this.state!==H.Initial&&this.state!==H.Establishing){const A=new Error(`Invalid session state ${this.state}`);return this.logger.error(A.message),Promise.reject(A)}const e=A.statusCode||480,t=A.reasonPhrase?A.reasonPhrase:M(e),s=A.extraHeaders||[];if(e<300||e>699)throw new TypeError("Invalid statusCode: "+e);const i=A.body?U(A.body):void 0;return e<400?this.incomingInviteRequest.redirect([],{statusCode:e,reasonPhrase:t,extraHeaders:s,body:i}):this.incomingInviteRequest.reject({statusCode:e,reasonPhrase:t,extraHeaders:s,body:i}),this.stateTransition(H.Terminated),Promise.resolve()}_onCancel(A){if(this.logger.log("Invitation._onCancel"),this.state===H.Initial||this.state===H.Establishing){if(this.delegate&&this.delegate.onCancel){const e=new c(A);this.delegate.onCancel(e)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(H.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(A){if(!this.dialog)throw new Error("Dialog undefined.");const e=G(A.message);if(!e||"session"!==e.contentDisposition)return Promise.resolve(void 0);const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case Y.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Y.Stable:return this.setAnswer(e,t).then(()=>{});case Y.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Y.HaveRemoteOffer:return this.setOfferAndGetAnswer(e,t);case Y.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(A){let e=480;if(A instanceof Error?this.logger.error(A.message):this.logger.error(A),A instanceof s?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),e=415):A instanceof n?this.logger.error("A session description handler occurred while sending response"):A instanceof o?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):A instanceof O&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===H.Initial||this.state===H.Establishing)try{this.incomingInviteRequest.reject({statusCode:e}),this.stateTransition(H.Terminated)}catch(A){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),A}if(!this.isCanceled)throw A;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(H.Terminated)}sendAccept(A={}){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},t=A.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,e)).then(A=>this.incomingInviteRequest.accept({statusCode:200,body:A,extraHeaders:t})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(A=>this.incomingInviteRequest.accept({statusCode:200,body:A,extraHeaders:t})))}sendProgress(A={}){const e=A.statusCode||180,t=A.reasonPhrase,s=(A.extraHeaders||[]).slice(),i=A.body?U(A.body):void 0;if(183===e&&!i)return this.sendProgressWithSDP(A);try{const A=this.incomingInviteRequest.progress({statusCode:e,reasonPhrase:t,extraHeaders:s,body:i});return this._dialog=A.session,Promise.resolve(A)}catch(A){return Promise.reject(A)}}sendProgressWithSDP(A={}){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},t=A.statusCode||183,s=A.reasonPhrase,i=(A.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(A=>this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:A})).then(A=>(this._dialog=A.session,A))}sendProgressReliable(A={}){return A.extraHeaders=(A.extraHeaders||[]).slice(),A.extraHeaders.push("Require: 100rel"),A.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(A)}sendProgressReliableWaitForPrack(A={}){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},t=A.statusCode||183,s=A.reasonPhrase,i=(A.extraHeaders||[]).slice();let n;return i.push("Require: 100rel"),i.push("RSeq: "+this.rseq++),new Promise((A,r)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(A=>(n=A,this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:n}))).then(e=>{let a,V;this._dialog=e.session,e.session.delegate={onPrack:t=>{a=t,clearTimeout(c),clearTimeout(g),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then(t=>{try{V=a.accept({statusCode:200,body:t}),this.prackArrived(),A({prackRequest:a,prackResponse:V,progressResponse:e})}catch(A){r(A)}}).catch(A=>r(A)))}};const c=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(g),this.reject({statusCode:504}).then(()=>r(new o)).catch(A=>r(A)))},64*Z.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:n})}catch(A){return this.waitingForPrack=!1,void r(A)}g=setTimeout(l,h*=2)};let h=Z.T1,g=setTimeout(l,h)}).catch(A=>{this.waitingForPrack=!1,r(A)})})}sendProgressTrying(){try{const A=this.incomingInviteRequest.trying();return Promise.resolve(A)}catch(A){return Promise.reject(A)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((A,e)=>{this.waitingForPrackResolve=A,this.waitingForPrackReject=e}),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 X extends W{constructor(A,e,t={}){super(A,t),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=A.getLogger("sip.Inviter"),this.earlyMedia=void 0!==t.earlyMedia?t.earlyMedia:this.earlyMedia,this.fromTag=f(),this.inviteWithoutSdp=void 0!==t.inviteWithoutSdp?t.inviteWithoutSdp:this.inviteWithoutSdp;const s=Object.assign({},t);s.params=Object.assign({},t.params);const i=t.anonymous||!1,n=A.contact.toString({anonymous:i,outbound:i?!A.contact.tempGruu:!A.contact.pubGruu});i&&A.configuration.uri&&(s.params.fromDisplayName="Anonymous",s.params.fromUri="sip:anonymous@anonymous.invalid");let o=A.userAgentCore.configuration.aor;if(s.params.fromUri&&(o="string"==typeof s.params.fromUri?E.URIParse(s.params.fromUri):s.params.fromUri),!o)throw new TypeError("Invalid from URI: "+s.params.fromUri);let r=e;if(s.params.toUri&&(r="string"==typeof s.params.toUri?E.URIParse(s.params.toUri):s.params.toUri),!r)throw new TypeError("Invalid to URI: "+s.params.toUri);const a=Object.assign({},s.params);a.fromTag=this.fromTag;const V=(s.extraHeaders||[]).slice();i&&A.configuration.uri&&(V.push("P-Preferred-Identity: "+A.configuration.uri.toString()),V.push("Privacy: id")),V.push("Contact: "+n),V.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),A.configuration.sipExtension100rel===j.Required&&V.push("Require: 100rel"),A.configuration.sipExtensionReplaces===j.Required&&V.push("Require: replaces"),s.extraHeaders=V;this.outgoingRequestMessage=A.userAgentCore.makeOutgoingRequestMessage(N.INVITE,e,o,r,a,V,undefined),this._contact=n,this._referralInviterOptions=s,this._renderbody=t.renderbody,this._rendertype=t.rendertype,t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),t.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=t.sessionDescriptionHandlerModifiersReInvite),t.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=t.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 H.Initial:case H.Establishing:return this.cancel().then(()=>super.dispose());case H.Established:case H.Terminating:case H.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(A={}){if(this.logger.log("Inviter.cancel"),this.state!==H.Initial&&this.state!==H.Establishing){const A=new Error(`Invalid session state ${this.state}`);return this.logger.error(A.message),Promise.reject(A)}if(this.isCanceled=!0,this.stateTransition(H.Terminating),this.outgoingInviteRequest){let e;A.statusCode&&A.reasonPhrase&&(e=function(A,e){if(A&&A<200||A>699)throw new TypeError("Invalid statusCode: "+A);if(A)return"SIP;cause="+A+';text="'+(M(A)||e)+'"'}(A.statusCode,A.reasonPhrase)),this.outgoingInviteRequest.cancel(e,A)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(H.Terminated);return Promise.resolve()}invite(A={}){if(this.logger.log("Inviter.invite"),this.state!==H.Initial)return super.invite(A);if(A.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=A.sessionDescriptionHandlerModifiers),A.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=A.sessionDescriptionHandlerOptions),A.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(H.Establishing),Promise.resolve(this.sendInvite(A));const e={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(e).then(e=>(this.outgoingRequestMessage.body={body:e.content,contentType:e.contentType},this.stateTransition(H.Establishing),this.sendInvite(A))).catch(A=>{throw this.logger.log(A.message),this.state!==H.Terminated&&this.stateTransition(H.Terminated),A})}sendInvite(A={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:e=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(e)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(e),void this.stateTransition(H.Terminated)):(this.notifyReferer(e),void this.onAccept(e).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e)})),onProgress:e=>{this.isCanceled||(this.notifyReferer(e),this.onProgress(e).catch(()=>{this.disposeEarlyMedia()}).then(()=>{A.requestDelegate&&A.requestDelegate.onProgress&&A.requestDelegate.onProgress(e)}))},onRedirect:e=>{this.notifyReferer(e),this.onRedirect(e),A.requestDelegate&&A.requestDelegate.onRedirect&&A.requestDelegate.onRedirect(e)},onReject:e=>{this.notifyReferer(e),this.onReject(e),A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e)},onTrying:e=>{this.notifyReferer(e),this.onTrying(e),A.requestDelegate&&A.requestDelegate.onTrying&&A.requestDelegate.onTrying(e)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(A=>{A.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(A){if(!this._referred)return;if(!(this._referred instanceof W))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!A.message.statusCode)throw new Error("Status code undefined.");if(!A.message.reasonPhrase)throw new Error("Reason phrase undefined.");const e=`SIP/2.0 ${A.message.statusCode} ${A.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:e}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(A){if(this.logger.log("Inviter.onAccept"),this.state!==H.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const e=A.message,t=A.session;switch(e.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=E.nameAddrHeaderParse(e.getHeader("P-Asserted-Identity"))),t.delegate={onAck:A=>this.onAckRequest(A),onBye:A=>this.onByeRequest(A),onInfo:A=>this.onInfoRequest(A),onInvite:A=>this.onInviteRequest(A),onMessage:A=>this.onMessageRequest(A),onNotify:A=>this.onNotifyRequest(A),onPrack:A=>this.onPrackRequest(A),onRefer:A=>this.onReferRequest(A)},this._dialog=t,t.signalingState){case Y.Initial:case Y.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(A,400,"Missing session description"),this.stateTransition(H.Terminated),Promise.reject(new Error("Bad Media Description"));case Y.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const e={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,e).then(e=>{A.ack({body:e}),this.stateTransition(H.Established)}).catch(e=>{throw this.ackAndBye(A,488,"Invalid session description"),this.stateTransition(H.Terminated),e})}case Y.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const e=this.earlyMediaSessionDescriptionHandlers.get(t.id);if(!e)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(e),this.earlyMediaSessionDescriptionHandlers.delete(t.id),A.ack(),this.stateTransition(H.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==t){if(this.earlyMedia){const A="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(A)}const e=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(e.message),this.ackAndBye(A,488,"Not Acceptable Here"),this.stateTransition(H.Terminated),Promise.reject(e)}return A.ack(),this.stateTransition(H.Established),Promise.resolve()}const e=t.answer;if(!e)throw new Error("Answer is undefined.");const s={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,s).then(()=>{let e;this._renderbody&&this._rendertype&&(e={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),A.ack(e),this.stateTransition(H.Established)}).catch(e=>{throw this.logger.error(e.message),this.ackAndBye(A,488,"Not Acceptable Here"),this.stateTransition(H.Terminated),e})}case Y.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(A){var e;if(this.logger.log("Inviter.onProgress"),this.state!==H.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 t=A.message,s=A.session;t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=E.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity")));const i=t.getHeader("require"),n=t.getHeader("rseq"),o=!!(i&&i.includes("100rel")&&n?Number(n):void 0),r=[];switch(o&&r.push("RAck: "+t.getHeader("rseq")+" "+t.getHeader("cseq")),s.signalingState){case Y.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),A.prack({extraHeaders:r})),Promise.resolve();case Y.HaveLocalOffer:return o&&A.prack({extraHeaders:r}),Promise.resolve();case Y.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const i=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(i,!0),this.earlyMediaSessionDescriptionHandlers.set(s.id,i),i.setDescription(t.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>i.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(e=>{const t={contentDisposition:"session",contentType:e.contentType,content:e.body};A.prack({extraHeaders:r,body:t})}).catch(A=>{throw this.stateTransition(H.Terminated),A})}case Y.Stable:if(o&&A.prack({extraHeaders:r}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=s;const A=s.answer;if(!A)throw new Error("Answer is undefined.");const e={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(A,e).catch(A=>{throw this.stateTransition(H.Terminated),A})}return Promise.resolve();case Y.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(A){this.logger.log("Inviter.onRedirect"),this.state===H.Establishing||this.state===H.Terminating?this.stateTransition(H.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(A){this.logger.log("Inviter.onReject"),this.state===H.Establishing||this.state===H.Terminating?this.stateTransition(H.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(A){this.logger.log("Inviter.onTrying"),this.state===H.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var _,$,AA,eA,tA,sA,iA;!function(A){A.Initial="Initial",A.Registered="Registered",A.Unregistered="Unregistered",A.Terminated="Terminated"}(_=_||(_={}));class nA{constructor(A,e={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=_.Initial,this._waiting=!1,this._stateEventEmitter=new l,this._waitingEventEmitter=new l,this.userAgent=A;const t=A.configuration.uri.clone();if(t.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},nA.defaultOptions()),{registrar:t}),nA.stripUndefinedProperties(e)),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===E.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const s=this.options.registrar,i=this.options.params&&this.options.params.fromUri||A.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||A.configuration.uri,o=this.options.params||{},r=(e.extraHeaders||[]).slice();if(this.request=A.userAgentCore.makeOutgoingRequestMessage(N.REGISTER,s,i,n,o,r,void 0),this.expires=this.options.expires||nA.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||nA.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=A.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(A=>{const e=this.options[A];if("registrar"===A)this.logger.log("· "+A+": "+e);else this.logger.log("· "+A+": "+JSON.stringify(e))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:nA.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new d("sip","anonymous","anonymous.invalid"),refreshFrequency:nA.defaultRefreshFrequency}}static stripUndefinedProperties(A){return Object.keys(A).reduce((e,t)=>(void 0!==A[t]&&(e[t]=A[t]),e),{})}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(A=>{const e=()=>{if(!this.waiting&&this._state===_.Registered)return this.stateChange.addListener(()=>{this.terminated(),A()},{once:!0}),void this.unregister();this.terminated(),A()};this.waiting?this.waitingChange.addListener(()=>{e()},{once:!0}):e()}))}register(A={}){if(this.state===_.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 A=new i("REGISTER request already in progress, waiting for final response");return Promise.reject(A)}A.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),A.requestOptions));const e=(this.options.extraHeaders||[]).slice();e.push("Contact: "+this.generateContactHeader(this.expires)),e.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=e,this.waitingToggle(!0);const t=this.userAgent.userAgentCore.register(this.request,{onAccept:e=>{let t;e.message.hasHeader("expires")&&(t=Number(e.message.getHeader("expires"))),this._contacts=e.message.getHeaders("contact");let s,i=this._contacts.length;if(!i)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;i--;){if(s=e.message.parseHeader("contact",i),!s)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&p(s.uri,this.userAgent.contact.pubGruu)){t=Number(s.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(s.uri.user===this.userAgent.contact.uri.user){t=Number(s.getParam("expires"));break}}else if(p(s.uri,this.userAgent.contact.uri)){t=Number(s.getParam("expires"));break}s=void 0}if(void 0===s)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===t)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(s.hasParam("temp-gruu")){const A=s.getParam("temp-gruu");A&&(this.userAgent.contact.tempGruu=E.URIParse(A.replace(/"/g,"")))}if(s.hasParam("pub-gruu")){const A=s.getParam("pub-gruu");A&&(this.userAgent.contact.pubGruu=E.URIParse(A.replace(/"/g,"")))}this.registered(t),A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e),this.waitingToggle(!1)},onProgress:e=>{A.requestDelegate&&A.requestDelegate.onProgress&&A.requestDelegate.onProgress(e)},onRedirect:e=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),A.requestDelegate&&A.requestDelegate.onRedirect&&A.requestDelegate.onRedirect(e),this.waitingToggle(!1)},onReject:e=>{if(423===e.message.statusCode)return e.message.hasHeader("min-expires")?(this.expires=Number(e.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 ${e.message.statusCode}`);let t=NaN;if(500===e.message.statusCode||503===e.message.statusCode){const A=e.message.getHeader("retry-after");A&&(t=Number.parseInt(A,void 0))}this._retryAfter=isNaN(t)?void 0:t,this.unregistered(),A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:e=>{A.requestDelegate&&A.requestDelegate.onTrying&&A.requestDelegate.onTrying(e)}});return Promise.resolve(t)}unregister(A={}){if(this.state===_.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==_.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const A=new i("REGISTER request already in progress, waiting for final response");return Promise.reject(A)}this._state===_.Registered||A.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const e=(A.requestOptions&&A.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=e,A.all?(e.push("Contact: *"),e.push("Expires: 0")):e.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 t=this.userAgent.userAgentCore.register(this.request,{onAccept:e=>{this._contacts=e.message.getHeaders("contact"),this.unregistered(),A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e),this.waitingToggle(!1)},onProgress:e=>{A.requestDelegate&&A.requestDelegate.onProgress&&A.requestDelegate.onProgress(e)},onRedirect:e=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),A.requestDelegate&&A.requestDelegate.onRedirect&&A.requestDelegate.onRedirect(e),this.waitingToggle(!1)},onReject:e=>{this.logger.error(`Unregister rejected with status code ${e.message.statusCode}`),this.unregistered(),A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e),this.waitingToggle(!1)},onTrying:e=>{A.requestDelegate&&A.requestDelegate.onTrying&&A.requestDelegate.onTrying(e)}});return Promise.resolve(t)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(A){let e=this.userAgent.contact.toString({register:!0});return this.options.regId&&this.options.instanceId&&(e+=";reg-id="+this.options.regId,e+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(A=>{e+=";"+A}),e+=";expires="+A,e}registered(A){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*A*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*A),this._state!==_.Registered&&this.stateTransition(_.Registered)}unregistered(){this.clearTimers(),this._state!==_.Unregistered&&this.stateTransition(_.Unregistered)}terminated(){this.clearTimers(),this._state!==_.Terminated&&this.stateTransition(_.Terminated)}stateTransition(A){const e=()=>{throw new Error(`Invalid state transition from ${this._state} to ${A}`)};switch(this._state){case _.Initial:A!==_.Registered&&A!==_.Unregistered&&A!==_.Terminated&&e();break;case _.Registered:A!==_.Unregistered&&A!==_.Terminated&&e();break;case _.Unregistered:A!==_.Registered&&A!==_.Terminated&&e();break;case _.Terminated:e();break;default:throw new Error("Unrecognized state.")}this._state=A,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),A===_.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(A){if(this._waiting===A)throw new Error(`Invalid waiting transition from ${this._waiting} to ${A}`);this._waiting=A,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let A="An attempt was made to send a REGISTER request while a prior one was still in progress.";A+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",A+=" from the registrar for the previous one or the previous REGISTER request has timed out.",A+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",A+=" 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 A=`An attempt was made to send a REGISTER request when the Registerer ${this.state===_.Terminated?"is in 'Terminated' state":"has been disposed"}.`;A+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",A+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(A)}}nA.defaultExpires=600,nA.defaultRefreshFrequency=99,function(A){A.Initial="Initial",A.NotifyWait="NotifyWait",A.Pending="Pending",A.Active="Active",A.Terminated="Terminated"}($=$||($={})),function(A){A.Connecting="Connecting",A.Connected="Connected",A.Disconnecting="Disconnecting",A.Disconnected="Disconnected"}(AA=AA||(AA={})),function(A){A.Started="Started",A.Stopped="Stopped"}(eA=eA||(eA={}));class oA{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(A,e=!1){return this.onePassHasher.start().appendStr(A).end(e)}static hashAsciiStr(A,e=!1){return this.onePassHasher.start().appendAsciiStr(A).end(e)}static _hex(A){const e=oA.hexChars,t=oA.hexOut;let s,i,n,o;for(o=0;o<4;o+=1)for(i=8*o,s=A[o],n=0;n<8;n+=2)t[i+1+n]=e.charAt(15&s),s>>>=4,t[i+0+n]=e.charAt(15&s),s>>>=4;return t.join("")}static _md5cycle(A,e){let t=A[0],s=A[1],i=A[2],n=A[3];t+=(s&i|~s&n)+e[0]-680876936|0,t=(t<<7|t>>>25)+s|0,n+=(t&s|~t&i)+e[1]-389564586|0,n=(n<<12|n>>>20)+t|0,i+=(n&t|~n&s)+e[2]+606105819|0,i=(i<<17|i>>>15)+n|0,s+=(i&n|~i&t)+e[3]-1044525330|0,s=(s<<22|s>>>10)+i|0,t+=(s&i|~s&n)+e[4]-176418897|0,t=(t<<7|t>>>25)+s|0,n+=(t&s|~t&i)+e[5]+1200080426|0,n=(n<<12|n>>>20)+t|0,i+=(n&t|~n&s)+e[6]-1473231341|0,i=(i<<17|i>>>15)+n|0,s+=(i&n|~i&t)+e[7]-45705983|0,s=(s<<22|s>>>10)+i|0,t+=(s&i|~s&n)+e[8]+1770035416|0,t=(t<<7|t>>>25)+s|0,n+=(t&s|~t&i)+e[9]-1958414417|0,n=(n<<12|n>>>20)+t|0,i+=(n&t|~n&s)+e[10]-42063|0,i=(i<<17|i>>>15)+n|0,s+=(i&n|~i&t)+e[11]-1990404162|0,s=(s<<22|s>>>10)+i|0,t+=(s&i|~s&n)+e[12]+1804603682|0,t=(t<<7|t>>>25)+s|0,n+=(t&s|~t&i)+e[13]-40341101|0,n=(n<<12|n>>>20)+t|0,i+=(n&t|~n&s)+e[14]-1502002290|0,i=(i<<17|i>>>15)+n|0,s+=(i&n|~i&t)+e[15]+1236535329|0,s=(s<<22|s>>>10)+i|0,t+=(s&n|i&~n)+e[1]-165796510|0,t=(t<<5|t>>>27)+s|0,n+=(t&i|s&~i)+e[6]-1069501632|0,n=(n<<9|n>>>23)+t|0,i+=(n&s|t&~s)+e[11]+643717713|0,i=(i<<14|i>>>18)+n|0,s+=(i&t|n&~t)+e[0]-373897302|0,s=(s<<20|s>>>12)+i|0,t+=(s&n|i&~n)+e[5]-701558691|0,t=(t<<5|t>>>27)+s|0,n+=(t&i|s&~i)+e[10]+38016083|0,n=(n<<9|n>>>23)+t|0,i+=(n&s|t&~s)+e[15]-660478335|0,i=(i<<14|i>>>18)+n|0,s+=(i&t|n&~t)+e[4]-405537848|0,s=(s<<20|s>>>12)+i|0,t+=(s&n|i&~n)+e[9]+568446438|0,t=(t<<5|t>>>27)+s|0,n+=(t&i|s&~i)+e[14]-1019803690|0,n=(n<<9|n>>>23)+t|0,i+=(n&s|t&~s)+e[3]-187363961|0,i=(i<<14|i>>>18)+n|0,s+=(i&t|n&~t)+e[8]+1163531501|0,s=(s<<20|s>>>12)+i|0,t+=(s&n|i&~n)+e[13]-1444681467|0,t=(t<<5|t>>>27)+s|0,n+=(t&i|s&~i)+e[2]-51403784|0,n=(n<<9|n>>>23)+t|0,i+=(n&s|t&~s)+e[7]+1735328473|0,i=(i<<14|i>>>18)+n|0,s+=(i&t|n&~t)+e[12]-1926607734|0,s=(s<<20|s>>>12)+i|0,t+=(s^i^n)+e[5]-378558|0,t=(t<<4|t>>>28)+s|0,n+=(t^s^i)+e[8]-2022574463|0,n=(n<<11|n>>>21)+t|0,i+=(n^t^s)+e[11]+1839030562|0,i=(i<<16|i>>>16)+n|0,s+=(i^n^t)+e[14]-35309556|0,s=(s<<23|s>>>9)+i|0,t+=(s^i^n)+e[1]-1530992060|0,t=(t<<4|t>>>28)+s|0,n+=(t^s^i)+e[4]+1272893353|0,n=(n<<11|n>>>21)+t|0,i+=(n^t^s)+e[7]-155497632|0,i=(i<<16|i>>>16)+n|0,s+=(i^n^t)+e[10]-1094730640|0,s=(s<<23|s>>>9)+i|0,t+=(s^i^n)+e[13]+681279174|0,t=(t<<4|t>>>28)+s|0,n+=(t^s^i)+e[0]-358537222|0,n=(n<<11|n>>>21)+t|0,i+=(n^t^s)+e[3]-722521979|0,i=(i<<16|i>>>16)+n|0,s+=(i^n^t)+e[6]+76029189|0,s=(s<<23|s>>>9)+i|0,t+=(s^i^n)+e[9]-640364487|0,t=(t<<4|t>>>28)+s|0,n+=(t^s^i)+e[12]-421815835|0,n=(n<<11|n>>>21)+t|0,i+=(n^t^s)+e[15]+530742520|0,i=(i<<16|i>>>16)+n|0,s+=(i^n^t)+e[2]-995338651|0,s=(s<<23|s>>>9)+i|0,t+=(i^(s|~n))+e[0]-198630844|0,t=(t<<6|t>>>26)+s|0,n+=(s^(t|~i))+e[7]+1126891415|0,n=(n<<10|n>>>22)+t|0,i+=(t^(n|~s))+e[14]-1416354905|0,i=(i<<15|i>>>17)+n|0,s+=(n^(i|~t))+e[5]-57434055|0,s=(s<<21|s>>>11)+i|0,t+=(i^(s|~n))+e[12]+1700485571|0,t=(t<<6|t>>>26)+s|0,n+=(s^(t|~i))+e[3]-1894986606|0,n=(n<<10|n>>>22)+t|0,i+=(t^(n|~s))+e[10]-1051523|0,i=(i<<15|i>>>17)+n|0,s+=(n^(i|~t))+e[1]-2054922799|0,s=(s<<21|s>>>11)+i|0,t+=(i^(s|~n))+e[8]+1873313359|0,t=(t<<6|t>>>26)+s|0,n+=(s^(t|~i))+e[15]-30611744|0,n=(n<<10|n>>>22)+t|0,i+=(t^(n|~s))+e[6]-1560198380|0,i=(i<<15|i>>>17)+n|0,s+=(n^(i|~t))+e[13]+1309151649|0,s=(s<<21|s>>>11)+i|0,t+=(i^(s|~n))+e[4]-145523070|0,t=(t<<6|t>>>26)+s|0,n+=(s^(t|~i))+e[11]-1120210379|0,n=(n<<10|n>>>22)+t|0,i+=(t^(n|~s))+e[2]+718787259|0,i=(i<<15|i>>>17)+n|0,s+=(n^(i|~t))+e[9]-343485551|0,s=(s<<21|s>>>11)+i|0,A[0]=t+A[0]|0,A[1]=s+A[1]|0,A[2]=i+A[2]|0,A[3]=n+A[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(oA.stateIdentity),this}appendStr(A){const e=this._buffer8,t=this._buffer32;let s,i,n=this._bufferLength;for(i=0;i<A.length;i+=1){if(s=A.charCodeAt(i),s<128)e[n++]=s;else if(s<2048)e[n++]=(s>>>6)+192,e[n++]=63&s|128;else if(s<55296||s>56319)e[n++]=(s>>>12)+224,e[n++]=s>>>6&63|128,e[n++]=63&s|128;else{if(s=1024*(s-55296)+(A.charCodeAt(++i)-56320)+65536,s>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");e[n++]=(s>>>18)+240,e[n++]=s>>>12&63|128,e[n++]=s>>>6&63|128,e[n++]=63&s|128}n>=64&&(this._dataLength+=64,oA._md5cycle(this._state,t),n-=64,t[0]=t[16])}return this._bufferLength=n,this}appendAsciiStr(A){const e=this._buffer8,t=this._buffer32;let s,i=this._bufferLength,n=0;for(;;){for(s=Math.min(A.length-n,64-i);s--;)e[i++]=A.charCodeAt(n++);if(i<64)break;this._dataLength+=64,oA._md5cycle(this._state,t),i=0}return this._bufferLength=i,this}appendByteArray(A){const e=this._buffer8,t=this._buffer32;let s,i=this._bufferLength,n=0;for(;;){for(s=Math.min(A.length-n,64-i);s--;)e[i++]=A[n++];if(i<64)break;this._dataLength+=64,oA._md5cycle(this._state,t),i=0}return this._bufferLength=i,this}getState(){const A=this,e=A._state;return{buffer:String.fromCharCode.apply(null,A._buffer8),buflen:A._bufferLength,length:A._dataLength,state:[e[0],e[1],e[2],e[3]]}}setState(A){const e=A.buffer,t=A.state,s=this._state;let i;for(this._dataLength=A.length,this._bufferLength=A.buflen,s[0]=t[0],s[1]=t[1],s[2]=t[2],s[3]=t[3],i=0;i<e.length;i+=1)this._buffer8[i]=e.charCodeAt(i)}end(A=!1){const e=this._bufferLength,t=this._buffer8,s=this._buffer32,i=1+(e>>2);let n;if(this._dataLength+=e,t[e]=128,t[e+1]=t[e+2]=t[e+3]=0,s.set(oA.buffer32Identity.subarray(i),i),e>55&&(oA._md5cycle(this._state,s),s.set(oA.buffer32Identity)),n=8*this._dataLength,n<=4294967295)s[14]=n;else{const A=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===A)return;const e=parseInt(A[2],16),t=parseInt(A[1],16)||0;s[14]=e,s[15]=t}return oA._md5cycle(this._state,s),A?this._state:oA._hex(this._state)}}function rA(A){return oA.hashStr(A)}oA.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),oA.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),oA.hexChars="0123456789abcdef",oA.hexOut=[],oA.onePassHasher=new oA,"5d41402abc4b2a76b9719d911017c592"!==oA.hashStr("hello")&&console.error("Md5 self test failed.");class aA{constructor(A,e,t,s){this.logger=A.getLogger("sipjs.digestauthentication"),this.username=t,this.password=s,this.ha1=e,this.nc=0,this.ncHex="00000000"}authenticate(A,e,t){if(this.algorithm=e.algorithm,this.realm=e.realm,this.nonce=e.nonce,this.opaque=e.opaque,this.stale=e.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(e.qop)if(e.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(e.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=A.method,this.uri=A.ruri,this.cnonce=w(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(t),!0}toString(){const A=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return A.push("algorithm="+this.algorithm),A.push('username="'+this.username+'"'),A.push('realm="'+this.realm+'"'),A.push('nonce="'+this.nonce+'"'),A.push('uri="'+this.uri+'"'),A.push('response="'+this.response+'"'),this.opaque&&A.push('opaque="'+this.opaque+'"'),this.qop&&(A.push("qop="+this.qop),A.push('cnonce="'+this.cnonce+'"'),A.push("nc="+this.ncHex)),"Digest "+A.join(", ")}updateNcHex(){const A=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-A.length)+A}calculateResponse(A){let e,t;e=this.ha1,""!==e&&void 0!==e||(e=rA(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(t=rA(this.method+":"+this.uri),this.response=rA(e+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+t)):"auth-int"===this.qop?(t=rA(this.method+":"+this.uri+":"+rA(A||"")),this.response=rA(e+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+t)):void 0===this.qop&&(t=rA(this.method+":"+this.uri),this.response=rA(e+":"+this.nonce+":"+t))}}!function(A){A[A.error=0]="error",A[A.warn=1]="warn",A[A.log=2]="log",A[A.debug=3]="debug"}(tA=tA||(tA={}));class VA{constructor(A,e,t){this.logger=A,this.category=e,this.label=t}error(A){this.genericLog(tA.error,A)}warn(A){this.genericLog(tA.warn,A)}log(A){this.genericLog(tA.log,A)}debug(A){this.genericLog(tA.debug,A)}genericLog(A,e){this.logger.genericLog(A,this.category,this.label,e)}get level(){return this.logger.level}set level(A){this.logger.level=A}}class cA{constructor(){this.builtinEnabled=!0,this._level=tA.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(A){A>=0&&A<=3?this._level=A:A>3?this._level=3:tA.hasOwnProperty(A)?this._level=A:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(A))}get connector(){return this._connector}set connector(A){A?"function"==typeof A?this._connector=A:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(A)):this._connector=void 0}getLogger(A,e){if(e&&3===this.level)return new VA(this,A,e);if(this.loggers[A])return this.loggers[A];{const e=new VA(this,A);return this.loggers[A]=e,e}}genericLog(A,e,t,s){this.level>=A&&this.builtinEnabled&&this.print(A,e,t,s),this.connector&&this.connector(tA[A],e,t,s)}print(A,e,t,s){if("string"==typeof s){const A=[new Date,e];t&&A.push(t),s=A.concat(s).join(" | ")}switch(A){case tA.error:console.error(s);break;case tA.warn:console.warn(s);case tA.log:case tA.debug:}}}function lA(A,e){const t="\r\n";if(e.statusCode<100||e.statusCode>699)throw new TypeError("Invalid statusCode: "+e.statusCode);const s=e.reasonPhrase?e.reasonPhrase:M(e.statusCode);let i="SIP/2.0 "+e.statusCode+" "+s+t;e.statusCode>=100&&e.statusCode,e.statusCode;const n="From: "+A.getHeader("From")+t,o="Call-ID: "+A.callId+t,r="CSeq: "+A.cseq+" "+A.method+t,a=A.getHeaders("via").reduce((A,e)=>A+"Via: "+e+t,"");let V="To: "+A.getHeader("to");if(e.statusCode>100&&!A.parseHeader("to").hasParam("tag")){let A=e.toTag;A||(A=f()),V+=";tag="+A}V+=t;let c="";e.supported&&(c="Supported: "+e.supported.join(", ")+t);let l="";e.userAgent&&(l="User-Agent: "+e.userAgent+t);let h="";return e.extraHeaders&&(h=e.extraHeaders.reduce((A,e)=>A+e.trim()+t,"")),i+=a,i+=n,i+=V,i+=r,i+=o,i+=c,i+=l,i+=h,e.body?(i+="Content-Type: "+e.body.contentType+t,i+="Content-Length: "+S(e.body.content)+t+t,i+=e.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}!function(A){function e(A,e){let t=e,s=0,i=0;if(A.substring(t,t+2).match(/(^\r\n)/))return-2;for(;0===s;){if(i=A.indexOf("\r\n",t),-1===i)return i;!A.substring(i+2,i+4).match(/(^\r\n)/)&&A.charAt(i+2).match(/(^\s+)/)?t=i+2:s=i}return s}function t(A,e,t,s){const i=e.indexOf(":",t),n=e.substring(t,i).trim(),o=e.substring(i+1,s).trim();let r;switch(n.toLowerCase()){case"via":case"v":A.addHeader("via",o),1===A.getHeaders("via").length?(r=A.parseHeader("Via"),r&&(A.via=r,A.viaBranch=r.branch)):r=0;break;case"from":case"f":A.setHeader("from",o),r=A.parseHeader("from"),r&&(A.from=r,A.fromTag=r.getParam("tag"));break;case"to":case"t":A.setHeader("to",o),r=A.parseHeader("to"),r&&(A.to=r,A.toTag=r.getParam("tag"));break;case"record-route":if(r=E.parse(o,"Record_Route"),-1===r){r=void 0;break}if(!(r instanceof Array)){r=void 0;break}r.forEach(e=>{A.addHeader("record-route",o.substring(e.position,e.offset)),A.headers["Record-Route"][A.getHeaders("record-route").length-1].parsed=e.parsed});break;case"call-id":case"i":A.setHeader("call-id",o),r=A.parseHeader("call-id"),r&&(A.callId=o);break;case"contact":case"m":if(r=E.parse(o,"Contact"),-1===r){r=void 0;break}if(!(r instanceof Array)){r=void 0;break}r.forEach(e=>{A.addHeader("contact",o.substring(e.position,e.offset)),A.headers.Contact[A.getHeaders("contact").length-1].parsed=e.parsed});break;case"content-length":case"l":A.setHeader("content-length",o),r=A.parseHeader("content-length");break;case"content-type":case"c":A.setHeader("content-type",o),r=A.parseHeader("content-type");break;case"cseq":A.setHeader("cseq",o),r=A.parseHeader("cseq"),r&&(A.cseq=r.value),A instanceof y&&(A.method=r.method);break;case"max-forwards":A.setHeader("max-forwards",o),r=A.parseHeader("max-forwards");break;case"www-authenticate":A.setHeader("www-authenticate",o),r=A.parseHeader("www-authenticate");break;case"proxy-authenticate":A.setHeader("proxy-authenticate",o),r=A.parseHeader("proxy-authenticate");break;case"refer-to":case"r":A.setHeader("refer-to",o),r=A.parseHeader("refer-to"),r&&(A.referTo=r);break;default:A.addHeader(n.toLowerCase(),o),r=0}return void 0!==r||{error:"error parsing header '"+n+"'"}}A.getHeader=e,A.parseHeader=t,A.parseMessage=function(A,s){let i=0,n=A.indexOf("\r\n");if(-1===n)return void s.warn("no CRLF found, not a SIP message, discarded");const o=A.substring(0,n),r=E.parse(o,"Request_Response");let a,V;if(-1!==r){for(r.status_code?(a=new y,a.statusCode=r.status_code,a.reasonPhrase=r.reason_phrase):(a=new T,a.method=r.method,a.ruri=r.uri),a.data=A,i=n+2;;){if(n=e(A,i),-2===n){V=i+2;break}if(-1===n)return void s.error("malformed message");const o=t(a,A,i,n);if(o&&!0!==o)return void s.error(o.error);i=n+2}return a.hasHeader("content-length")?a.body=A.substr(V,Number(a.getHeader("content-length"))):a.body=A.substring(V),a}s.warn('error parsing first line of SIP message: "'+o+'"')}}(sA=sA||(sA={}));class hA extends t{constructor(A){super(A||"Unspecified transport error.")}}class gA{constructor(A,e,t,s,i){this._transport=A,this._user=e,this._id=t,this._state=s,this.listeners=new Array,this.logger=e.loggerFactory.getLogger(i,t),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(A,e){const t=()=>{this.removeStateChangeListener(t),A()};!0===(null==e?void 0:e.once)?this.listeners.push(t):this.listeners.push(A)}notifyStateChangeListeners(){this.listeners.slice().forEach(A=>A())}removeStateChangeListener(A){this.listeners=this.listeners.filter(e=>e!==A)}logTransportError(A,e){this.logger.error(A.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(e)}send(A){return this.transport.send(A).catch(A=>{if(A instanceof hA)throw this.onTransportError(A),A;let e;throw e=A&&"string"==typeof A.message?new hA(A.message):new hA,this.onTransportError(e),e})}setState(A){this.logger.debug(`State change to "${A}" on ${this.typeToString()} with id ${this.id}.`),this._state=A,this._user.onStateChange&&this._user.onStateChange(A),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class qA extends gA{constructor(A,e,t,s,i){super(e,t,A.viaBranch,s,i),this._request=A,this.user=t}get request(){return this._request}}!function(A){A.Accepted="Accepted",A.Calling="Calling",A.Completed="Completed",A.Confirmed="Confirmed",A.Proceeding="Proceeding",A.Terminated="Terminated",A.Trying="Trying"}(iA=iA||(iA={}));class dA extends qA{constructor(A,e,t){super(A,e,t,iA.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(A){switch(this.state){case iA.Proceeding:if(A.method===N.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(A=>{this.logTransportError(A,"Failed to send retransmission of provisional response.")}));break;case iA.Accepted:if(A.method===N.INVITE)return;break;case iA.Completed:if(A.method===N.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(A=>{this.logTransportError(A,"Failed to send retransmission of final response.")})}if(A.method===N.ACK)return void this.stateTransition(iA.Confirmed);break;case iA.Confirmed:case iA.Terminated:if(A.method===N.INVITE||A.method===N.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const e=`INVITE server transaction received unexpected ${A.method} request while in state ${this.state}.`;this.logger.warn(e)}receiveResponse(A,e){if(A<100||A>699)throw new Error(`Invalid status code ${A}`);switch(this.state){case iA.Proceeding:if(A>=100&&A<=199)return this.lastProvisionalResponse=e,A>100&&this.startProgressExtensionTimer(),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send 1xx response.")});if(A>=200&&A<=299)return this.lastFinalResponse=e,this.stateTransition(iA.Accepted),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send 2xx response.")});if(A>=300&&A<=699)return this.lastFinalResponse=e,this.stateTransition(iA.Completed),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send non-2xx final response.")});break;case iA.Accepted:if(A>=200&&A<=299)return void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send 2xx response.")});break;case iA.Completed:case iA.Confirmed:case iA.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${A} response from TU while in state ${this.state}.`;throw this.logger.error(t),new Error(t)}retransmitAcceptedResponse(){this.state===iA.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(A=>{this.logTransportError(A,"Failed to send 2xx response.")})}onTransportError(A){this.user.onTransportError&&this.user.onTransportError(A)}typeToString(){return"INVITE server transaction"}stateTransition(A){const e=()=>{throw new Error(`Invalid state transition from ${this.state} to ${A}`)};switch(A){case iA.Proceeding:e();break;case iA.Accepted:case iA.Completed:this.state!==iA.Proceeding&&e();break;case iA.Confirmed:this.state!==iA.Completed&&e();break;case iA.Terminated:this.state!==iA.Accepted&&this.state!==iA.Completed&&this.state!==iA.Confirmed&&e();break;default:e()}this.stopProgressExtensionTimer(),A===iA.Accepted&&(this.L=setTimeout(()=>this.timerL(),Z.TIMER_L)),A===iA.Completed&&(this.H=setTimeout(()=>this.timerH(),Z.TIMER_H)),A===iA.Confirmed&&(this.I=setTimeout(()=>this.timerI(),Z.TIMER_I)),A===iA.Terminated&&this.dispose(),this.setState(A)}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(A=>{this.logTransportError(A,"Failed to send retransmission of provisional response.")})},Z.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===iA.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(iA.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(iA.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===iA.Accepted&&this.stateTransition(iA.Terminated)}}class pA extends gA{constructor(A,e,t,s,i){super(e,t,pA.makeId(A),s,i),this._request=A,this.user=t,A.setViaHeader(this.id,e.protocol)}static makeId(A){if("CANCEL"===A.method){if(!A.branch)throw new Error("Outgoing CANCEL request without a branch.");return A.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class uA extends pA{constructor(A,e,t){super(A,e,t,iA.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),Z.TIMER_F),this.send(A.toString()).catch(A=>{this.logTransportError(A,"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(A){const e=A.statusCode;if(!e||e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case iA.Trying:if(e>=100&&e<=199)return this.stateTransition(iA.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=200&&e<=699)return this.stateTransition(iA.Completed),408===e?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(A));break;case iA.Proceeding:if(e>=100&&e<=199&&this.user.receiveResponse)return this.user.receiveResponse(A);if(e>=200&&e<=699)return this.stateTransition(iA.Completed),408===e?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(A));break;case iA.Completed:case iA.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const t=`Non-INVITE client transaction received unexpected ${e} response while in state ${this.state}.`;this.logger.warn(t)}onTransportError(A){this.user.onTransportError&&this.user.onTransportError(A),this.stateTransition(iA.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(A,e=!1){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${A}`)};switch(A){case iA.Trying:t();break;case iA.Proceeding:this.state!==iA.Trying&&t();break;case iA.Completed:this.state!==iA.Trying&&this.state!==iA.Proceeding&&t();break;case iA.Terminated:this.state!==iA.Trying&&this.state!==iA.Proceeding&&this.state!==iA.Completed&&(e||t());break;default:t()}A===iA.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),Z.TIMER_K)),A===iA.Terminated&&this.dispose(),this.setState(A)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==iA.Trying&&this.state!==iA.Proceeding||(this.onRequestTimeout(),this.stateTransition(iA.Terminated))}timerK(){this.state===iA.Completed&&this.stateTransition(iA.Terminated)}}class mA{constructor(A,e){this.core=A,this.dialogState=e,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(A,e){const t=e.getHeaders("record-route").reverse(),s=e.parseHeader("contact");if(!s)throw new Error("Contact undefined.");if(!(s instanceof q))throw new Error("Contact not instance of NameAddrHeader.");const i=s.uri,n=A.cseq,o=A.callId,r=A.fromTag,a=e.toTag;if(!o)throw new Error("Call id undefined.");if(!r)throw new Error("From tag undefined.");if(!a)throw new Error("To tag undefined.");if(!A.from)throw new Error("From undefined.");if(!A.to)throw new Error("To undefined.");const V=A.from.uri,c=A.to.uri;if(!e.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+r+a,early:e.statusCode<200,callId:o,localTag:r,remoteTag:a,localSequenceNumber:n,remoteSequenceNumber:undefined,localURI:V,remoteURI:c,remoteTarget:i,routeSet:t,secure:!1}}static initialDialogStateForUserAgentServer(A,e,t=!1){const s=A.getHeaders("record-route"),i=A.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof q))throw new Error("Contact not instance of NameAddrHeader.");const n=i.uri,o=A.cseq,r=A.callId,a=e,V=A.fromTag,c=A.from.uri;return{id:r+a+V,early:t,callId:r,localTag:a,remoteTag:V,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:A.to.uri,remoteURI:c,remoteTarget:n,routeSet:s,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(A){if(A.method!==N.ACK){if(this.remoteSequenceNumber){if(A.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=A.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=A.cseq)}}recomputeRouteSet(A){this.dialogState.routeSet=A.getHeaders("record-route").reverse()}createOutgoingRequestMessage(A,e){const t=this.remoteURI,s=this.remoteTag,i=this.localURI,n=this.localTag,o=this.callId;let r;r=e&&e.cseq?e.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const a=this.remoteTarget,V=this.routeSet,c=e&&e.extraHeaders,l=e&&e.body;return this.userAgentCore.makeOutgoingRequestMessage(A,a,i,t,{callId:o,cseq:r,fromTag:n,toTag:s,routeSet:V},c,l)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(A){return A.method===N.ACK||(!(this.remoteSequenceNumber&&A.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(A,{statusCode:500}),!1))}}class CA extends pA{constructor(A,e,t){super(A,e,t,iA.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),Z.TIMER_B),this.send(A.toString()).catch(A=>{this.logTransportError(A,"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(A){const e=A.toTag;if(!e)throw new Error("To tag undefined.");const t="z9hG4bK"+Math.floor(1e7*Math.random());A.setViaHeader(t,this.transport.protocol),this.ackRetransmissionCache.set(e,A),this.send(A.toString()).catch(A=>{this.logTransportError(A,"Failed to send ACK to 2xx response.")})}receiveResponse(A){const e=A.statusCode;if(!e||e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case iA.Calling:if(e>=100&&e<=199)return this.stateTransition(iA.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=200&&e<=299)return this.ackRetransmissionCache.set(A.toTag,void 0),this.stateTransition(iA.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=300&&e<=699)return this.stateTransition(iA.Completed),this.ack(A),void(this.user.receiveResponse&&this.user.receiveResponse(A));break;case iA.Proceeding:if(e>=100&&e<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=200&&e<=299)return this.ackRetransmissionCache.set(A.toTag,void 0),this.stateTransition(iA.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=300&&e<=699)return this.stateTransition(iA.Completed),this.ack(A),void(this.user.receiveResponse&&this.user.receiveResponse(A));break;case iA.Accepted:if(e>=200&&e<=299){if(!this.ackRetransmissionCache.has(A.toTag))return this.ackRetransmissionCache.set(A.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(A));const e=this.ackRetransmissionCache.get(A.toTag);return e?void this.send(e.toString()).catch(A=>{this.logTransportError(A,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case iA.Completed:if(e>=300&&e<=699)return void this.ack(A);break;case iA.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const t=`Received unexpected ${e} response while in state ${this.state}.`;this.logger.warn(t)}onTransportError(A){this.user.onTransportError&&this.user.onTransportError(A),this.stateTransition(iA.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(A){const e=this.request.ruri,t=this.request.callId,s=this.request.cseq,i=this.request.getHeader("from"),n=A.getHeader("to"),o=this.request.getHeader("via"),r=this.request.getHeader("route");if(!i)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let a=`ACK ${e} SIP/2.0\r\n`;r&&(a+=`Route: ${r}\r\n`),a+=`Via: ${o}\r\n`,a+=`To: ${n}\r\n`,a+=`From: ${i}\r\n`,a+=`Call-ID: ${t}\r\n`,a+=`CSeq: ${s} ACK\r\n`,a+="Max-Forwards: 70\r\n",a+="Content-Length: 0\r\n\r\n",this.send(a).catch(A=>{this.logTransportError(A,"Failed to send ACK to non-2xx response.")})}stateTransition(A,e=!1){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${A}`)};switch(A){case iA.Calling:t();break;case iA.Proceeding:this.state!==iA.Calling&&t();break;case iA.Accepted:case iA.Completed:this.state!==iA.Calling&&this.state!==iA.Proceeding&&t();break;case iA.Terminated:this.state!==iA.Calling&&this.state!==iA.Accepted&&this.state!==iA.Completed&&(e||t());break;default:t()}this.B&&(clearTimeout(this.B),this.B=void 0),iA.Proceeding,A===iA.Completed&&(this.D=setTimeout(()=>this.timerD(),Z.TIMER_D)),A===iA.Accepted&&(this.M=setTimeout(()=>this.timerM(),Z.TIMER_M)),A===iA.Terminated&&this.dispose(),this.setState(A)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===iA.Calling&&(this.onRequestTimeout(),this.stateTransition(iA.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===iA.Completed&&this.stateTransition(iA.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===iA.Accepted&&this.stateTransition(iA.Terminated)}}class EA{constructor(A,e,t,s){this.transactionConstructor=A,this.core=e,this.message=t,this.delegate=s,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(A,e={}){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 t=this.core.makeOutgoingRequestMessage(N.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},e.extraHeaders);return t.branch=this.message.branch,this.message.headers.Route&&(t.headers.Route=this.message.headers.Route),A&&t.setHeader("Reason",A),this.transaction.state===iA.Proceeding?new EA(uA,this.core,t):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===iA.Proceeding&&new EA(uA,this.core,t)},{once:!0}),t}authenticationGuard(A,e){const t=A.statusCode;if(!t)throw new Error("Response status code undefined.");if(401!==t&&407!==t)return!0;let s,i;if(401===t?(s=A.parseHeader("www-authenticate"),i="authorization"):(s=A.parseHeader("proxy-authenticate"),i="proxy-authorization"),!s)return this.logger.warn(t+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==s.stale))return this.logger.warn(t+" 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,s))return!0;this.challenged=!0,s.stale&&(this.stale=!0);let n=this.message.cseq+=1;return e&&e.localSequenceNumber&&(e.incrementLocalSequenceNumber(),n=this.message.cseq=e.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(i,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const A=new y;A.statusCode=408,A.reasonPhrase="Request Timeout",this.receiveResponse(A)}onTransportError(A){this.logger.error(A.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const e=new y;e.statusCode=503,e.reasonPhrase="Service Unavailable",this.receiveResponse(e)}receiveResponse(A){if(!this.authenticationGuard(A))return;const e=A.statusCode?A.statusCode.toString():"";if(!e)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(e):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:A});break;case/^1[0-9]{2}$/.test(e):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:A});break;case/^2[0-9]{2}$/.test(e):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:A});break;case/^3[0-9]{2}$/.test(e):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:A});break;case/^[4-6][0-9]{2}$/.test(e):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:A});break;default:throw new Error(`Invalid status code ${e}`)}}init(){const A={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:A=>{A===iA.Terminated&&(this.core.userAgentClients.delete(t),e===this._transaction&&this.dispose())},onTransportError:A=>this.onTransportError(A),receiveResponse:A=>this.receiveResponse(A)},e=new this.transactionConstructor(this.message,this.core.transport,A);this._transaction=e;const t=e.id+e.request.method;this.core.userAgentClients.set(t,this)}}class IA extends EA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.BYE,t);super(uA,A.userAgentCore,s,e),A.dispose()}}class wA extends qA{constructor(A,e,t){super(A,e,t,iA.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(A){switch(this.state){case iA.Trying:break;case iA.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(A=>{this.logTransportError(A,"Failed to send retransmission of provisional response.")});break;case iA.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(A=>{this.logTransportError(A,"Failed to send retransmission of final response.")});break;case iA.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(A,e){if(A<100||A>699)throw new Error(`Invalid status code ${A}`);if(A>100&&A<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case iA.Trying:if(this.lastResponse=e,A>=100&&A<200)return this.stateTransition(iA.Proceeding),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send provisional response.")});if(A>=200&&A<=699)return this.stateTransition(iA.Completed),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send final response.")});break;case iA.Proceeding:if(this.lastResponse=e,A>=200&&A<=699)return this.stateTransition(iA.Completed),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send final response.")});break;case iA.Completed:return;case iA.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const t=`Non-INVITE server transaction received unexpected ${A} response from TU while in state ${this.state}.`;throw this.logger.error(t),new Error(t)}onTransportError(A){this.user.onTransportError&&this.user.onTransportError(A),this.stateTransition(iA.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(A,e=!1){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${A}`)};switch(A){case iA.Trying:t();break;case iA.Proceeding:this.state!==iA.Trying&&t();break;case iA.Completed:this.state!==iA.Trying&&this.state!==iA.Proceeding&&t();break;case iA.Terminated:this.state!==iA.Proceeding&&this.state!==iA.Completed&&(e||t());break;default:t()}A===iA.Completed&&(this.J=setTimeout(()=>this.timerJ(),Z.TIMER_J)),A===iA.Terminated&&this.dispose(),this.setState(A)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===iA.Completed&&this.stateTransition(iA.Terminated)}}class MA{constructor(A,e,t,s){this.transactionConstructor=A,this.core=e,this.message=t,this.delegate=s,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=t.toTag?t.toTag:f(),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(A={statusCode:200}){if(!this.acceptable)throw new O(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const e=A.statusCode;if(e<200||e>299)throw new TypeError(`Invalid statusCode: ${e}`);return this.reply(A)}progress(A={statusCode:180}){if(!this.progressable)throw new O(`${this.message.method} not progressable in state ${this.transaction.state}.`);const e=A.statusCode;if(e<101||e>199)throw new TypeError(`Invalid statusCode: ${e}`);return this.reply(A)}redirect(A,e={statusCode:302}){if(!this.redirectable)throw new O(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<300||t>399)throw new TypeError(`Invalid statusCode: ${t}`);const s=new Array;A.forEach(A=>s.push(`Contact: ${A.toString()}`)),e.extraHeaders=(e.extraHeaders||[]).concat(s);return this.reply(e)}reject(A={statusCode:480}){if(!this.rejectable)throw new O(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const e=A.statusCode;if(e<400||e>699)throw new TypeError(`Invalid statusCode: ${e}`);return this.reply(A)}trying(A){if(!this.tryingable)throw new O(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(A){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(A)}get acceptable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding||this.transaction.state===iA.Accepted;if(this.transaction instanceof wA)return this.transaction.state===iA.Trying||this.transaction.state===iA.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding;if(this.transaction instanceof wA)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding;if(this.transaction instanceof wA)return this.transaction.state===iA.Trying||this.transaction.state===iA.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding;if(this.transaction instanceof wA)return this.transaction.state===iA.Trying||this.transaction.state===iA.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding;if(this.transaction instanceof wA)return this.transaction.state===iA.Trying;throw new Error("Unknown transaction type.")}reply(A){A.toTag||100===A.statusCode||(A.toTag=this.toTag),A.userAgent=A.userAgent||this.core.configuration.userAgentHeaderFieldValue,A.supported=A.supported||this.core.configuration.supportedOptionTagsResponse;const e=lA(this.message,A);return this.transaction.receiveResponse(A.statusCode,e.message),e}init(){const A={loggerFactory:this.loggerFactory,onStateChange:A=>{A===iA.Terminated&&(this.core.userAgentServers.delete(t),this.dispose())},onTransportError:A=>{this.logger.error(A.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(A):this.logger.error("User agent server response transport error.")}},e=new this.transactionConstructor(this.message,this.core.transport,A);this._transaction=e;const t=e.id;this.core.userAgentServers.set(e.id,this)}}class fA extends MA{constructor(A,e,t){super(wA,A.userAgentCore,e,t)}}class BA extends EA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.INFO,t);super(uA,A.userAgentCore,s,e)}}class SA extends MA{constructor(A,e,t){super(wA,A.userAgentCore,e,t)}}class QA extends EA{constructor(A,e,t){super(uA,A,e,t)}}class TA extends MA{constructor(A,e,t){super(wA,A,e,t)}}class yA extends EA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.NOTIFY,t);super(uA,A.userAgentCore,s,e)}}class DA extends MA{constructor(A,e,t){const s=void 0!==A.userAgentCore?A.userAgentCore:A;super(wA,s,e,t)}}class RA extends EA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.PRACK,t);super(uA,A.userAgentCore,s,e),A.signalingStateTransition(s)}}class UA extends MA{constructor(A,e,t){super(wA,A.userAgentCore,e,t),A.signalingStateTransition(e),this.dialog=A}accept(A={statusCode:200}){return A.body&&this.dialog.signalingStateTransition(A.body),super.accept(A)}}class kA extends EA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.INVITE,t);super(CA,A.userAgentCore,s,e),this.delegate=e,A.signalingStateTransition(s),A.reinviteUserAgentClient=this,this.dialog=A}receiveResponse(A){if(!this.authenticationGuard(A,this.dialog))return;const e=A.statusCode?A.statusCode.toString():"";if(!e)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(e):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:A});break;case/^1[0-9]{2}$/.test(e):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:A,session:this.dialog,prack:A=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(e):this.dialog.signalingStateTransition(A),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:A,session:this.dialog,ack:A=>this.dialog.ack(A)});break;case/^3[0-9]{2}$/.test(e):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:A});break;case/^[4-6][0-9]{2}$/.test(e):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:A});break;default:throw new Error(`Invalid status code ${e}`)}}}class GA extends MA{constructor(A,e,t){super(dA,A.userAgentCore,e,t),A.reinviteUserAgentServer=this,this.dialog=A}accept(A={statusCode:200}){A.extraHeaders=A.extraHeaders||[],A.extraHeaders=A.extraHeaders.concat(this.dialog.routeSet.map(A=>`Record-Route: ${A}`));const e=super.accept(A),t=this.dialog,s=Object.assign(Object.assign({},e),{session:t});return A.body&&this.dialog.signalingStateTransition(A.body),this.dialog.reConfirm(),s}progress(A={statusCode:180}){const e=super.progress(A),t=this.dialog,s=Object.assign(Object.assign({},e),{session:t});return A.body&&this.dialog.signalingStateTransition(A.body),s}redirect(A,e={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(A={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(A)}}class FA extends EA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.REFER,t);super(uA,A.userAgentCore,s,e)}}class YA extends MA{constructor(A,e,t){const s=void 0!==A.userAgentCore?A.userAgentCore:A;super(wA,s,e,t)}}class xA extends mA{constructor(A,e,t,s){super(e,t),this.initialTransaction=A,this._signalingState=Y.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=s,A instanceof dA&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(A.request),this.logger=e.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=Y.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?F.Early:this.ackWait?F.AckWait:this._signalingState===Y.Closed?F.Terminated:F.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(A={}){let e;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof CA))throw new Error("Transaction not instance of InviteClientTransaction.");e=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof CA))throw new Error("Initial transaction not instance of InviteClientTransaction.");e=this.initialTransaction}const t=this.createOutgoingRequestMessage(N.ACK,{cseq:e.request.cseq,extraHeaders:A.extraHeaders,body:A.body});return e.ackResponse(t),this.signalingStateTransition(t),{message:t}}bye(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof dA){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==iA.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 IA(this,A,e)}info(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new BA(this,A,e)}invite(A,e){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 kA(this,A,e)}message(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const t=this.createOutgoingRequestMessage(N.MESSAGE,e);return new QA(this.core,t,A)}notify(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new yA(this,A,e)}prack(A,e){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new RA(this,A,e)}refer(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new FA(this,A,e)}receiveRequest(A){if(this.logger.log(`INVITE dialog ${this.id} received ${A.method} request`),A.method!==N.ACK)if(this.sequenceGuard(A)){if(super.receiveRequest(A),A.method===N.INVITE){const e=()=>{const A=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${A}`);let e="RFC 5407 suggests the following to avoid this race condition... ";e+=" Note: Implementation issues are outside the scope of this document,",e+=" but the following tip is provided for avoiding race conditions of",e+=" this type. The caller can delay sending re-INVITE F6 for some period",e+=" of time (2 seconds, perhaps), after which the caller can reasonably",e+=" assume that its ACK has been received. Implementors can decouple the",e+=" actions of the user (e.g., pressing the hold button) from the actions",e+=" of the protocol (the sending of re-INVITE F6), so that the UA can",e+=" behave like this. In this case, it is the implementor's choice as to",e+=" how long to wait. In most cases, such an implementation may be",e+=" useful to prevent the type of race condition shown in this section.",e+=" This document expresses no preference about whether or not they",e+=" should wait for an ACK to be delivered. After considering the impact",e+=" on user experience, implementors should decide whether or not to wait",e+=" for a while, because the user experience depends on the",e+=" 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.")},t=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(A,{statusCode:500,extraHeaders:t}),void e();if(this.ackWait&&this.signalingState!==Y.Stable)return this.core.replyStateless(A,{statusCode:500,extraHeaders:t}),void e();if(this.reinviteUserAgentServer)return void this.core.replyStateless(A,{statusCode:500,extraHeaders:t});if(this.reinviteUserAgentClient)return void this.core.replyStateless(A,{statusCode:491})}if(A.method===N.INVITE){const e=A.parseHeader("contact");if(!e)throw new Error("Contact undefined.");if(!(e instanceof q))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=e.uri}switch(A.method){case N.BYE:{const e=new fA(this,A);this.delegate&&this.delegate.onBye?this.delegate.onBye(e):e.accept(),this.dispose()}break;case N.INFO:{const e=new SA(this,A);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(e):e.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case N.INVITE:{const e=new GA(this,A);this.signalingStateTransition(A),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(e):e.reject({statusCode:488})}break;case N.MESSAGE:{const e=new TA(this.core,A);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(e):e.accept()}break;case N.NOTIFY:{const e=new DA(this,A);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(e):e.accept()}break;case N.PRACK:{const e=new UA(this,A);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(e):e.accept()}break;case N.REFER:{const e=new YA(this,A);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(e):e.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${A.method} request`),this.core.replyStateless(A,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${A.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof CA)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${A.method} request, dropping.`);if(this.initialTransaction.request.cseq!==A.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${A.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${A.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==A.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${A.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(A),this.delegate&&this.delegate.onAck){const e=this.delegate.onAck({message:A});e instanceof Promise&&(this.ackProcessing=!0,e.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(A){const e=A.statusCode;if(!e)throw new Error("Status code undefined");if(e>100&&e<200){const e=A.getHeader("require"),t=A.getHeader("rseq"),s=e&&e.includes("100rel")&&t?Number(t):void 0;if(s){if(this.rseq&&this.rseq+1!==s)return!1;this.rseq=this.rseq?this.rseq+1:s}}return!0}signalingStateRollback(){this._signalingState!==Y.HaveLocalOffer&&this.signalingState!==Y.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=Y.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(A){const e=G(A);if(e&&"session"===e.contentDisposition){if(this._signalingState===Y.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),A instanceof T)switch(this._signalingState){case Y.Initial:case Y.Stable:this._signalingState=Y.HaveRemoteOffer,this._offer=e,this._answer=void 0;break;case Y.HaveLocalOffer:this._signalingState=Y.Stable,this._answer=e;break;case Y.HaveRemoteOffer:case Y.Closed:break;default:throw new Error("Unexpected signaling state.")}if(A instanceof y)switch(this._signalingState){case Y.Initial:case Y.Stable:this._signalingState=Y.HaveRemoteOffer,this._offer=e,this._answer=void 0;break;case Y.HaveLocalOffer:this._signalingState=Y.Stable,this._answer=e;break;case Y.HaveRemoteOffer:case Y.Closed:break;default:throw new Error("Unexpected signaling state.")}if(A instanceof D)switch(this._signalingState){case Y.Initial:case Y.Stable:this._signalingState=Y.HaveLocalOffer,this._offer=e,this._answer=void 0;break;case Y.HaveLocalOffer:break;case Y.HaveRemoteOffer:this._signalingState=Y.Stable,this._answer=e;break;case Y.Closed:break;default:throw new Error("Unexpected signaling state.")}if(k(A))switch(this._signalingState){case Y.Initial:case Y.Stable:this._signalingState=Y.HaveLocalOffer,this._offer=e,this._answer=void 0;break;case Y.HaveLocalOffer:break;case Y.HaveRemoteOffer:this._signalingState=Y.Stable,this._answer=e;break;case Y.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof dA){const A=this.initialTransaction;let e=Z.T1;const t=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),A.retransmitAcceptedResponse(),e=Math.min(2*e,Z.T2),this.invite2xxTimer=setTimeout(t,e)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(t,e);const s=()=>{A.state===iA.Terminated&&(A.removeStateChangeListener(s),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};A.addStateChangeListener(s)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof dA){const A=this.reinviteUserAgentServer.transaction;let e=Z.T1;const t=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),A.retransmitAcceptedResponse(),e=Math.min(2*e,Z.T2),this.invite2xxTimer=setTimeout(t,e)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(t,e);const s=()=>{A.state===iA.Terminated&&(A.removeStateChangeListener(s),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};A.addStateChangeListener(s)}}}class vA extends EA{constructor(A,e,t){super(CA,A,e,t),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=t}dispose(){this.earlyDialogs.forEach(A=>A.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(A){if(this.transaction.state===iA.Calling)return super.onTransportError(A);this.logger.error(A.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(A){if(!this.authenticationGuard(A))return;const e=A.statusCode?A.statusCode.toString():"";if(!e)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(e):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:A}));case/^1[0-9]{2}$/.test(e):{if(!A.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!A.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const e=mA.initialDialogStateForUserAgentClient(this.message,A);let t=this.earlyDialogs.get(e.id);if(!t){const A=this.transaction;if(!(A instanceof CA))throw new Error("Transaction not instance of InviteClientTransaction.");t=new xA(A,this.core,e),this.earlyDialogs.set(t.id,t)}if(!t.reliableSequenceGuard(A))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");t.signalingState!==Y.Initial&&t.signalingState!==Y.HaveLocalOffer||t.signalingStateTransition(A);const s=t;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:A,session:s,prack:A=>s.prack(void 0,A)})}return;case/^2[0-9]{2}$/.test(e):{if(!A.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!A.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const e=mA.initialDialogStateForUserAgentClient(this.message,A);let t=this.confirmedDialogs.get(e.id);if(t){const A=this.confirmedDialogAcks.get(e.id);if(A){const e=this.transaction;if(!(e instanceof CA))throw new Error("Client transaction not instance of InviteClientTransaction.");e.ackResponse(A.message)}return}if(t=this.earlyDialogs.get(e.id),t)t.confirm(),t.recomputeRouteSet(A),this.earlyDialogs.delete(t.id),this.confirmedDialogs.set(t.id,t);else{const A=this.transaction;if(!(A instanceof CA))throw new Error("Transaction not instance of InviteClientTransaction.");t=new xA(A,this.core,e),this.confirmedDialogs.set(t.id,t)}t.signalingState!==Y.Initial&&t.signalingState!==Y.HaveLocalOffer||t.signalingStateTransition(A);const s=t;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:A,session:s,ack:A=>{const e=s.ack(A);return this.confirmedDialogAcks.set(s.id,e),e}});else{const A=s.ack();this.confirmedDialogAcks.set(s.id,A)}}return;case/^3[0-9]{2}$/.test(e):return this.earlyDialogs.forEach(A=>A.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:A}));case/^[4-6][0-9]{2}$/.test(e):return this.earlyDialogs.forEach(A=>A.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:A}));default:throw new Error(`Invalid status code ${e}`)}}}class ZA extends MA{constructor(A,e,t){super(dA,A,e,t),this.core=A}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(A={statusCode:200}){if(!this.acceptable)throw new O(`${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 A=this.transaction;if(!(A instanceof dA))throw new Error("Transaction not instance of InviteClientTransaction.");const e=mA.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new xA(A,this.core,e)}const e=this.message.getHeaders("record-route").map(A=>`Record-Route: ${A}`),t=`Contact: ${this.core.configuration.contact.toString()}`,s="Allow: "+K.toString();if(!A.body)if(this.confirmedDialog.signalingState===Y.Stable)A.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===Y.Initial||this.confirmedDialog.signalingState===Y.HaveRemoteOffer)throw new Error("Response must have a body.");A.statusCode=A.statusCode||200,A.extraHeaders=A.extraHeaders||[],A.extraHeaders=A.extraHeaders.concat(e),A.extraHeaders.push(s),A.extraHeaders.push(t);const i=super.accept(A),n=this.confirmedDialog,o=Object.assign(Object.assign({},i),{session:n});return A.body&&this.confirmedDialog.signalingState!==Y.Stable&&this.confirmedDialog.signalingStateTransition(A.body),o}progress(A={statusCode:180}){if(!this.progressable)throw new O(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const A=this.transaction;if(!(A instanceof dA))throw new Error("Transaction not instance of InviteClientTransaction.");const e=mA.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new xA(A,this.core,e)}const e=this.message.getHeaders("record-route").map(A=>`Record-Route: ${A}`),t=`Contact: ${this.core.configuration.contact}`;A.extraHeaders=A.extraHeaders||[],A.extraHeaders=A.extraHeaders.concat(e),A.extraHeaders.push(t);const s=super.progress(A),i=this.earlyDialog,n=Object.assign(Object.assign({},s),{session:i});return A.body&&this.earlyDialog.signalingState!==Y.Stable&&this.earlyDialog.signalingStateTransition(A.body),n}redirect(A,e={statusCode:302}){return super.redirect(A,e)}reject(A={statusCode:486}){return super.reject(A)}}class OA extends EA{constructor(A,e,t){super(uA,A,e,t)}}class NA extends EA{constructor(A,e,t){super(uA,A,e,t)}}class KA extends MA{constructor(A,e,t){super(wA,A,e,t),this.core=A}}class bA extends EA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.SUBSCRIBE,t);super(uA,A.userAgentCore,s,e),this.dialog=A}waitNotifyStop(){}receiveResponse(A){if(A.statusCode&&A.statusCode>=200&&A.statusCode<300){const e=A.getHeader("Expires");if(e){const A=Number(e);this.dialog.subscriptionExpires>A&&(this.dialog.subscriptionExpires=A)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(A.statusCode&&A.statusCode>=400&&A.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(A.statusCode)&&this.dialog.terminate()}super.receiveResponse(A)}}class JA extends mA{constructor(A,e,t,s,i,n){super(s,i),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=A,this._subscriptionExpires=e,this._subscriptionExpiresInitial=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=t,this.logger=s.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(A,e){const t=e.getHeaders("record-route"),s=e.parseHeader("contact");if(!s)throw new Error("Contact undefined.");if(!(s instanceof q))throw new Error("Contact not instance of NameAddrHeader.");const i=s.uri,n=A.cseq,o=A.callId,r=A.fromTag,a=e.fromTag;if(!o)throw new Error("Call id undefined.");if(!r)throw new Error("From tag undefined.");if(!a)throw new Error("To tag undefined.");if(!A.from)throw new Error("From undefined.");if(!A.to)throw new Error("To undefined.");return{id:o+r+a,early:!1,callId:o,localTag:r,remoteTag:a,localSequenceNumber:n,remoteSequenceNumber:undefined,localURI:A.from.uri,remoteURI:A.to.uri,remoteTarget:i,routeSet:t,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(A){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const A=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,e=this._subscriptionExpires-A;return Math.max(e,0)}set subscriptionExpires(A){if(A<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=A,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){const e=this.subscriptionRefresh;(void 0===e||e>=A)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const A=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,e=this._subscriptionRefresh-A;return Math.max(e,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(A){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${A.method} request`),this.sequenceGuard(A))if(super.receiveRequest(A),A.method===N.NOTIFY)this.onNotify(A);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${A.method} request`),this.core.replyStateless(A,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${A.method} request.`)}refresh(){const A="Allow: "+K.toString(),e={};return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push(A),e.extraHeaders.push("Event: "+this.subscriptionEvent),e.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),e.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,e)}subscribe(A,e={}){var t;if(this.subscriptionState!==$.Pending&&this.subscriptionState!==$.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const s=new bA(this,A,e);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(t=e.extraHeaders)||void 0===t?void 0:t.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),Z.TIMER_N)),s}terminate(){this.stateTransition($.Terminated),this.onTerminated()}unsubscribe(){const A="Allow: "+K.toString(),e={};return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push(A),e.extraHeaders.push("Event: "+this.subscriptionEvent),e.extraHeaders.push("Expires: 0"),e.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,e)}onNotify(A){const e=A.parseHeader("Event").event;if(!e||e!==this.subscriptionEvent)return void this.core.replyStateless(A,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const t=A.parseHeader("Subscription-State");if(!t||!t.state)return void this.core.replyStateless(A,{statusCode:489});const s=t.state,i=t.expires?Math.max(t.expires,0):void 0;switch(s){case"pending":this.stateTransition($.Pending,i);break;case"active":this.stateTransition($.Active,i);break;case"terminated":this.stateTransition($.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new DA(this,A);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(A){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(A)}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 A=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(A/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())},A)}}stateTransition(A,e){const t=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${A}`)};switch(A){case $.Initial:case $.NotifyWait:return void t();case $.Pending:if(this.subscriptionState!==$.NotifyWait&&this.subscriptionState!==$.Pending)return void t();break;case $.Active:case $.Terminated:if(this.subscriptionState!==$.NotifyWait&&this.subscriptionState!==$.Pending&&this.subscriptionState!==$.Active)return void t();break;default:return void t()}A===$.Pending&&e&&(this.subscriptionExpires=e),A===$.Active&&e&&(this.subscriptionExpires=e),A===$.Terminated&&this.dispose(),this._subscriptionState=A}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==$.Terminated&&(this.stateTransition($.Terminated),this.onTerminated())}}class LA extends EA{constructor(A,e,t){const s=e.getHeader("Event");if(!s)throw new Error("Event undefined");const i=e.getHeader("Expires");if(!i)throw new Error("Expires undefined");super(uA,A,e,t),this.delegate=t,this.subscriberId=e.callId+e.fromTag+s,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(i),this.subscriptionEvent=s,this.subscriptionState=$.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(A){const e=A.message.parseHeader("Event").event;if(!e||e!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void A.reject({statusCode:489});const t=A.message.parseHeader("Subscription-State");if(!t||!t.state)return this.logger.warn("Failed to parse subscription state."),void A.reject({statusCode:489});const s=t.state;switch(s){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${s}`),void A.reject({statusCode:489})}if("terminated"!==s){if(!A.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void A.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=t.expires?Math.min(this.subscriptionExpires,Math.max(t.expires,0)):this.subscriptionExpires,s){case"pending":this.subscriptionState=$.Pending;break;case"active":this.subscriptionState=$.Active;break;case"terminated":this.subscriptionState=$.Terminated;break;default:throw new Error(`Unrecognized state ${s}.`)}if(this.subscriptionState!==$.Terminated){const e=JA.initialDialogStateForSubscription(this.message,A.message);this.dialog=new JA(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,e)}if(this.delegate&&this.delegate.onNotify){const e=A,t=this.dialog;this.delegate.onNotify({request:e,subscription:t})}else A.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),Z.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(A){if(this.authenticationGuard(A)){if(A.statusCode&&A.statusCode>=200&&A.statusCode<300){const e=A.getHeader("Expires");if(e){const A=Number(e);A>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),A<this.subscriptionExpires&&(this.subscriptionExpires=A)}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)}A.statusCode&&A.statusCode>=300&&A.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(A)}}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 HA extends MA{constructor(A,e,t){super(wA,A,e,t),this.core=A}}const jA=["application/sdp","application/dtmf-relay"];class WA{constructor(A,e={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=A,this.delegate=e,this.dialogs=new Map,this.subscribers=new Map,this.logger=A.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(A=>A.dispose()),this.dialogs.clear(),this.subscribers.forEach(A=>A.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(A=>A.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(A=>A.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const A=this.configuration.transportAccessor();if(!A)throw new Error("Transport undefined.");return A}invite(A,e){return new vA(this,A,e)}message(A,e){return new QA(this,A,e)}publish(A,e){return new OA(this,A,e)}register(A,e){return new NA(this,A,e)}subscribe(A,e){return new LA(this,A,e)}request(A,e){return new EA(uA,this,A,e)}makeOutgoingRequestMessage(A,e,t,s,i,n,o){const r=this.configuration.sipjsId,a=this.configuration.displayName,V=this.configuration.viaForceRport,c=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();A===N.REGISTER&&l.push("path","gruu"),A===N.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");const h={callIdPrefix:r,forceRport:V,fromDisplayName:a,hackViaTcp:c,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},g=Object.assign(Object.assign({},h),i);return new D(A,e,t,s,g,n,o)}receiveIncomingRequestFromTransport(A){this.receiveRequestFromTransport(A)}receiveIncomingResponseFromTransport(A){this.receiveResponseFromTransport(A)}replyStateless(A,e){const t=this.configuration.userAgentHeaderFieldValue,s=this.configuration.supportedOptionTagsResponse;e=Object.assign(Object.assign({},e),{userAgent:t,supported:s});const i=lA(A,e);return this.transport.send(i.message).catch(e=>{e instanceof Error&&this.logger.error(e.message),this.logger.error(`Transport error occurred sending stateless reply to ${A.method} request.`)}),i}receiveRequestFromTransport(A){const e=A.viaBranch,t=this.userAgentServers.get(e);A.method===N.ACK&&t&&t.transaction.state===iA.Accepted&&t instanceof ZA?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${e}.`):A.method!==N.CANCEL?t?t.transaction.receiveRequest(A):this.receiveRequest(A):t?(this.replyStateless(A,{statusCode:200}),t.transaction instanceof dA&&t.transaction.state===iA.Proceeding&&t instanceof ZA&&t.receiveCancel(A)):this.replyStateless(A,{statusCode:481})}receiveRequest(A){if(!K.includes(A.method)){const e="Allow: "+K.toString();return void this.replyStateless(A,{statusCode:405,extraHeaders:[e]})}if(!A.ruri)throw new Error("Request-URI undefined.");if("sip"!==A.ruri.scheme)return void this.replyStateless(A,{statusCode:416});const e=A.ruri,t=A=>!!A&&A.user===e.user;if(!t(this.configuration.aor)&&!(t(this.configuration.contact.uri)||t(this.configuration.contact.pubGruu)||t(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(A.method!==N.ACK&&this.replyStateless(A,{statusCode:404}));if(A.method!==N.INVITE||A.hasHeader("Contact")){if(!A.toTag){const e=A.viaBranch;if(!this.userAgentServers.has(e)){if(Array.from(this.userAgentServers.values()).some(e=>e.transaction.request.fromTag===A.fromTag&&e.transaction.request.callId===A.callId&&e.transaction.request.cseq===A.cseq))return void this.replyStateless(A,{statusCode:482})}}A.toTag?this.receiveInsideDialogRequest(A):this.receiveOutsideDialogRequest(A)}else this.replyStateless(A,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(A){if(A.method===N.NOTIFY){const e=A.parseHeader("Event");if(!e||!e.event)return void this.replyStateless(A,{statusCode:489});const t=A.callId+A.toTag+e.event,s=this.subscribers.get(t);if(s){const e=new DA(this,A);return void s.onNotify(e)}}const e=A.callId+A.toTag+A.fromTag,t=this.dialogs.get(e);if(t){if(A.method===N.OPTIONS){const e="Allow: "+K.toString(),t="Accept: "+jA.toString();return void this.replyStateless(A,{statusCode:200,extraHeaders:[e,t]})}t.receiveRequest(A)}else A.method!==N.ACK&&this.replyStateless(A,{statusCode:481})}receiveOutsideDialogRequest(A){switch(A.method){case N.ACK:break;case N.BYE:this.replyStateless(A,{statusCode:481});break;case N.CANCEL:throw new Error(`Unexpected out of dialog request method ${A.method}.`);case N.INFO:this.replyStateless(A,{statusCode:405});break;case N.INVITE:{const e=new ZA(this,A);this.delegate.onInvite?this.delegate.onInvite(e):e.reject()}break;case N.MESSAGE:{const e=new TA(this,A);this.delegate.onMessage?this.delegate.onMessage(e):e.accept()}break;case N.NOTIFY:{const e=new DA(this,A);this.delegate.onNotify?this.delegate.onNotify(e):e.reject({statusCode:405})}break;case N.OPTIONS:{const e="Allow: "+K.toString(),t="Accept: "+jA.toString();this.replyStateless(A,{statusCode:200,extraHeaders:[e,t]})}break;case N.REFER:{const e=new YA(this,A);this.delegate.onRefer?this.delegate.onRefer(e):e.reject({statusCode:405})}break;case N.REGISTER:{const e=new KA(this,A);this.delegate.onRegister?this.delegate.onRegister(e):e.reject({statusCode:405})}break;case N.SUBSCRIBE:{const e=new HA(this,A);this.delegate.onSubscribe?this.delegate.onSubscribe(e):e.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${A.method}.`)}}receiveResponseFromTransport(A){if(A.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const e=A.viaBranch+A.method,t=this.userAgentClients.get(e);t?t.transaction.receiveResponse(A):this.logger.warn(`Discarding unmatched ${A.statusCode} response to ${A.method} ${e}.`)}}class PA{constructor(A,e,t){A.debug("SessionDescriptionHandler.constructor"),this.logger=A,this.mediaStreamFactory=e,this.sessionDescriptionHandlerConfiguration=t,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==t?void 0:t.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(A){this._peerConnectionDelegate=A}static dispatchAddTrackEvent(A,e){A.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:e}))}static dispatchRemoveTrackEvent(A,e){A.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:e}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(A=>{A.track&&A.track.stop()}),this._peerConnection.getSenders().forEach(A=>{A.track&&A.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(A){const e=this.peerConnection;if(!e)throw new Error("Peer connection closed.");e.getReceivers().forEach(e=>{e.track&&(e.track.enabled=A)})}enableSenderTracks(A){const e=this.peerConnection;if(!e)throw new Error("Peer connection closed.");e.getSenders().forEach(e=>{e.track&&(e.track.enabled=A)})}getDescription(A,e){var t,s;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==A?void 0:A.onDataChannel;const i=null===(t=null==A?void 0:A.offerOptions)||void 0===t?void 0:t.iceRestart,n=void 0===(null==A?void 0:A.iceGatheringTimeout)?null===(s=this.sessionDescriptionHandlerConfiguration)||void 0===s?void 0:s.iceGatheringTimeout:null==A?void 0:A.iceGatheringTimeout;return this.getLocalMediaStream(A).then(()=>this.updateDirection(A)).then(()=>this.createDataChannel(A)).then(()=>this.createLocalOfferOrAnswer(A)).then(A=>this.applyModifiers(A,e)).then(A=>this.setLocalSessionDescription(A)).then(()=>this.waitForIceGatheringComplete(i,n)).then(()=>this.getLocalSessionDescription()).then(A=>({body:A.sdp,contentType:"application/sdp"})).catch(A=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+A),A})}hasDescription(A){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===A}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(A,e){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const t=this._peerConnection.getSenders();if(0===t.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const s=t[0].dtmf;if(!s)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const i=null==e?void 0:e.duration,n=null==e?void 0:e.interToneGap;try{s.insertDTMF(A,i,n)}catch(A){return this.logger.error(A.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+A.toString()),!0}setDescription(A,e,t){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const s="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(e).then(()=>this.applyModifiers({sdp:A,type:s},t)).then(A=>this.setRemoteSessionDescription(A)).catch(A=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+A),A})}applyModifiers(A,e){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),e&&0!==e.length?e.reduce((A,e)=>A.then(e),Promise.resolve(A)).then(A=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!A.sdp||!A.type)throw new Error("Invalid SDP.");return{sdp:A.sdp,type:A.type}}):Promise.resolve(A)}createDataChannel(A){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==A?void 0:A.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==A?void 0:A.dataChannelLabel)||"",null==A?void 0:A.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(A){return Promise.reject(A)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(A){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==A?void 0:A.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==A?void 0:A.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(A){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let e=Object.assign({},null==A?void 0:A.constraints);if(this.localMediaStreamConstraints){if(e.audio=e.audio||this.localMediaStreamConstraints.audio,e.video=e.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(e.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(e.video))return Promise.resolve()}else void 0===e.audio&&void 0===e.video&&(e={audio:!0});return this.localMediaStreamConstraints=e,this.mediaStreamFactory(e,this,A).then(A=>this.setLocalMediaStream(A))}setLocalMediaStream(A){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection,t=this._localMediaStream,s=[],i=A=>{const i=A.kind;if("audio"!==i&&"video"!==i)throw new Error(`Unknown new track kind ${i}.`);const n=e.getSenders().find(A=>A.track&&A.track.kind===i);n?s.push(new Promise(A=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${i} track`),A()}).then(()=>n.replaceTrack(A).then(()=>{const e=t.getTracks().find(A=>A.kind===i);e&&(e.stop(),t.removeTrack(e),PA.dispatchRemoveTrackEvent(t,e)),t.addTrack(A),PA.dispatchAddTrackEvent(t,A)}).catch(A=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${i} track`),A}))):s.push(new Promise(A=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${i} track`),A()}).then(()=>{try{e.addTrack(A,t)}catch(A){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${i} track`),A}t.addTrack(A),PA.dispatchAddTrackEvent(t,A)}))},n=A.getAudioTracks();n.length&&i(n[0]);const o=A.getVideoTracks();return o.length&&i(o[0]),s.reduce((A,e)=>A.then(()=>e),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const A=this._peerConnection.localDescription;return A?Promise.resolve(A):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(A){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(A)}setRemoteSessionDescription(A){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=A.sdp;let t;switch(this._peerConnection.signalingState){case"stable":t="offer";break;case"have-local-offer":t="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return e?this._peerConnection.setRemoteDescription({sdp:e,type:t}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(A){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const e=this._remoteMediaStream;e.getTrackById(A.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${A.kind} track`):"audio"===A.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${A.kind} track`),e.getAudioTracks().forEach(A=>{A.stop(),e.removeTrack(A),PA.dispatchRemoveTrackEvent(e,A)}),e.addTrack(A),PA.dispatchAddTrackEvent(e,A)):"video"===A.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${A.kind} track`),e.getVideoTracks().forEach(A=>{A.stop(),e.removeTrack(A),PA.dispatchRemoveTrackEvent(e,A)}),e.addTrack(A),PA.dispatchAddTrackEvent(e,A))}updateDirection(A){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 e=e=>{switch(e){case"inactive":case"recvonly":return(null==A?void 0:A.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==A?void 0:A.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach(A=>{if(A.direction){const t=e(A.direction);A.direction!==t&&(A.direction=t)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const e=(()=>{const A=this._peerConnection.remoteDescription;if(!A)throw new Error("Failed to read remote offer");const e=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(A.sdp);if(e)switch(e[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"})(),t=(()=>{switch(e){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==A?void 0:A.hold)?"inactive":"recvonly";case"sendrecv":return(null==A?void 0:A.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach(A=>{A.direction&&"stopped"!==A.direction&&A.direction!==t&&(A.direction=t)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(A=!1,e=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):A||"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((A,t)=>{this.iceGatheringCompleteResolve=A,this.iceGatheringCompleteReject=t,e>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+e),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},e))}),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 A=this._peerConnection;A.onconnectionstatechange=e=>{var t;const s=A.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${s}`),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(e)},A.ondatachannel=A=>{var e;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=A.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(A)},A.onicecandidate=A=>{var e;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(A)},A.onicecandidateerror=A=>{var e;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(A)},A.oniceconnectionstatechange=e=>{var t;const s=A.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${s}`),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(e)},A.onicegatheringstatechange=e=>{var t;const s=A.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${s}`),"complete"===s&&this.iceGatheringComplete(),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(e)},A.onnegotiationneeded=A=>{var e;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(A)},A.onsignalingstatechange=e=>{var t;const s=A.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${s}`),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(e)},A.ontrack=A=>{var e;const t=A.track.kind,s=A.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${t} ${s}`),this.setRemoteTrack(A.track),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.ontrack)&&this._peerConnectionDelegate.ontrack(A)}}}function zA(A){return(e,t)=>{void 0===A&&(A=A=>A.audio||A.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,A):Promise.resolve(new MediaStream));const s={iceGatheringTimeout:void 0!==(null==t?void 0:t.iceGatheringTimeout)?null==t?void 0:t.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==t?void 0:t.peerConnectionConfiguration)},i=e.userAgent.getLogger("sip.SessionDescriptionHandler");return new PA(i,A,s)}}class XA{constructor(A,e){if(this._state=AA.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new l,this.logger=A,e){const A=e,t=null==A?void 0:A.wsServers,s=null==A?void 0:A.maxReconnectionAttempts;if(void 0!==t){const A='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(A)}if(void 0!==s){const A='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(A)}t&&!e.server&&("string"==typeof t&&(e.server=t),t instanceof Array&&(e.server=t[0]))}this.configuration=Object.assign(Object.assign({},XA.defaultOptions),e);const t=this.configuration.server,s=E.parse(t,"absoluteURI");if(-1===s)throw this.logger.error(`Invalid WebSocket Server URL "${t}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(s.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${t}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=s.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===AA.Connected}send(A){return this._send(A)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case AA.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(AA.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case AA.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(AA.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case AA.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(AA.Connecting)}catch(A){if(A instanceof r)return Promise.reject(A);throw A}break;case AA.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(AA.Connecting)}catch(A){if(A instanceof r)return Promise.reject(A);throw A}break;default:throw new Error("Unknown state")}let A;try{A=new WebSocket(this.server,"sip"),A.binaryType="arraybuffer",A.addEventListener("close",e=>this.onWebSocketClose(e,A)),A.addEventListener("error",e=>this.onWebSocketError(e,A)),A.addEventListener("open",e=>this.onWebSocketOpen(e,A)),A.addEventListener("message",e=>this.onWebSocketMessage(e,A)),this._ws=A}catch(A){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(A.toString()),new Promise((e,t)=>{this.connectResolve=e,this.connectReject=t,this.transitionState(AA.Disconnected,A)})}return this.connectPromise=new Promise((e,t)=>{this.connectResolve=e,this.connectReject=t,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),A.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case AA.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(AA.Disconnecting)}catch(A){if(A instanceof r)return Promise.reject(A);throw A}break;case AA.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(AA.Disconnecting)}catch(A){if(A instanceof r)return Promise.reject(A);throw A}break;case AA.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(AA.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case AA.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(AA.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 A=this._ws;return this.disconnectPromise=new Promise((e,t)=>{this.disconnectResolve=e,this.disconnectReject=t;try{A.close(1e3)}catch(A){throw this.logger.error("WebSocket close failed."),this.logger.error(A.toString()),A}}),this.disconnectPromise}_send(A){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+A+"\n"),this._state!==AA.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(A)}catch(A){return A instanceof Error?Promise.reject(A):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(A,e){if(e!==this._ws)return;const t=`WebSocket closed ${this.server} (code: ${A.code})`,s=this.disconnectPromise?void 0:new Error(t);s&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(t),this._ws=void 0,this.transitionState(AA.Disconnected,s)}onWebSocketError(A,e){e===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(A,e){if(e!==this._ws)return;const t=A.data;let s;if(/^(\r\n)+$/.test(t))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(t){if("string"!=typeof t){try{s=(new TextDecoder).decode(new Uint8Array(t))}catch(A){return this.logger.error(A.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"+s+"\n")}else s=t,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+s+"\n");if(this.state===AA.Connected){if(this.onMessage)try{this.onMessage(s)}catch(A){throw this.logger.error(A.toString()),this.logger.error("Exception thrown by onMessage callback"),A}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(A,e){e===this._ws&&this._state===AA.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(AA.Connected))}transitionLoopDetectedError(A){let e="A state transition loop has been detected.";return e+=` An attempt to transition from ${this._state} to ${A} before the prior transition completed.`,e+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(e),new r("Loop detected.")}transitionState(A,e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${A}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(A);switch(this.transitioningState=!0,this._state){case AA.Connecting:A!==AA.Connected&&A!==AA.Disconnecting&&A!==AA.Disconnected&&t();break;case AA.Connected:A!==AA.Disconnecting&&A!==AA.Disconnected&&t();break;case AA.Disconnecting:A!==AA.Connecting&&A!==AA.Disconnected&&t();break;case AA.Disconnected:A!==AA.Connecting&&t();break;default:throw new Error("Unknown state.")}const s=this._state;this._state=A;const i=this.connectResolve,n=this.connectReject;s===AA.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,r=this.disconnectReject;if(s===AA.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 ${s} to ${this._state}`),this._stateEventEmitter.emit(this._state),A===AA.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(A){throw this.logger.error(A.toString()),this.logger.error("Exception thrown by onConnect callback"),A}if(s===AA.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{e?this.onDisconnect(e):this.onDisconnect()}catch(A){throw this.logger.error(A.toString()),this.logger.error("Exception thrown by onDisconnect callback"),A}if(s===AA.Connecting){if(!i)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");A===AA.Connected?i():n(e||new Error("Connect aborted."))}if(s===AA.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!r)throw new Error("Disconnect reject undefined.");A===AA.Disconnected?o():r(e||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()},(A=>{const e=.8*A;return 1e3*(Math.random()*(A-e)+e)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}XA.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class _A{constructor(A={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=eA.Stopped,this._stateEventEmitter=new l,this.delegate=A.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},_A.defaultOptions()),{sipjsId:w(5)}),{uri:new d("sip","anonymous."+w(6),"anonymous.invalid")}),{viaHost:w(12)+".invalid"}),_A.stripUndefinedProperties(A)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const A=1,e=254,t=Math.floor(Math.random()*(e-A+1)+A);this.options.viaHost="192.0.2."+t}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new cA,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=tA.error;break;case"warn":this.loggerFactory.level=tA.warn;break;case"log":this.loggerFactory.level=tA.log;break;case"debug":this.loggerFactory.level=tA.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(A=>{const e=this.options[A];switch(A){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+A+": "+e);break;case"authorizationPassword":this.logger.log("· "+A+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+A+": "+e.name);break;default:this.logger.log("· "+A+": "+JSON.stringify(e))}})),this.options.transportOptions){const e=this.options.transportOptions,t=e.maxReconnectionAttempts,s=e.reconnectionTimeout;if(void 0!==t){const A='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(A)}if(void 0!==s){const A='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(A)}void 0===A.reconnectionDelay&&void 0!==s&&(this.options.reconnectionDelay=s),void 0===A.reconnectionAttempts&&void 0!==t&&(this.options.reconnectionAttempts=t)}if(void 0!==A.reconnectionDelay){const A='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(A)}if(void 0!==A.reconnectionAttempts){const A='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(A)}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:_A.newUUID(),-1===E.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(A){return E.URIParse(A)}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:zA(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:j.Unsupported,sipExtensionReplaces:j.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:XA,transportOptions:{},uri:new d("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){const A="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,A=>{const e=Math.floor(16*Math.random());return("x"===A?e:e%4+8).toString(16)});return A}static stripUndefinedProperties(A){return Object.keys(A).reduce((e,t)=>(void 0!==A[t]&&(e[t]=A[t]),e),{})}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(A,e){return this.loggerFactory.getLogger(A,e)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===eA.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===eA.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(eA.Started),this.transport.connect())}async stop(){if(this.state===eA.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(A=>{throw this.logger.error(A.message),A}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(eA.Stopped),Promise.resolve();const A=Object.assign({},this._publishers),e=Object.assign({},this._registerers),t=Object.assign({},this._sessions),s=Object.assign({},this._subscriptions),i=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const A in e)e[A]&&await e[A].dispose().catch(e=>{throw this.logger.error(e.message),delete this._registerers[A],e});this.logger.log("Dispose of sessions");for(const A in t)t[A]&&await t[A].dispose().catch(e=>{throw this.logger.error(e.message),delete this._sessions[A],e});this.logger.log("Dispose of subscriptions");for(const A in s)s[A]&&await s[A].dispose().catch(e=>{throw this.logger.error(e.message),delete this._subscriptions[A],e});this.logger.log("Dispose of publishers");for(const e in A)A[e]&&await A[e].dispose().catch(A=>{throw this.logger.error(A.message),delete this._publishers[e],A});this.logger.log("Dispose of transport"),await i.dispose().catch(A=>{throw this.logger.error(A.message),A}),this.logger.log("Dispose of core"),n.dispose(),this.transitionState(eA.Stopped)}_makeInviter(A,e){return new X(this,A,e)}attemptReconnection(A=1){const e=this.options.reconnectionAttempts,t=this.options.reconnectionDelay;A>e?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${A} of ${e} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${A} of ${e} - succeeded`)}).catch(t=>{this.logger.error(t.message),this.logger.log(`Reconnection attempt ${A} of ${e} - failed`),this.attemptReconnection(++A)})},1===A?0:1e3*t))}initContact(){const A=""!==this.options.contactName?this.options.contactName:w(8),e=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new d("sip",A,this.options.viaHost,void 0,e),toString:(A={})=>{const t=A.anonymous||!1,s=A.outbound||!1,i=A.register||!1;let n="<";return n+=t?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${e.transport?e.transport:"ws"}`:i?this.contact.uri:this.contact.pubGruu||this.contact.uri,s&&(n+=";ob"),n+=">",this.options.instanceIdAlwaysAdded&&(n+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),n}}}initCore(){let A=[];A.push("outbound"),this.options.sipExtension100rel===j.Supported&&A.push("100rel"),this.options.sipExtensionReplaces===j.Supported&&A.push("replaces"),this.options.sipExtensionExtraSupported&&A.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(A=A.filter(A=>P[A])),A=Array.from(new Set(A));const e=A.slice();(this.contact.pubGruu||this.contact.tempGruu)&&e.push("gruu");const t={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:A,supportedOptionTagsResponse:e,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const A=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,e=this.options.authorizationPassword?this.options.authorizationPassword:void 0,t=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new aA(this.getLoggerFactory(),t,A,e)},transportAccessor:()=>this.transport},s={onInvite:A=>{var e;const t=new z(this,A);if(A.delegate={onCancel:A=>{t._onCancel(A)},onTransportError:A=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},A.trying(),this.options.sipExtensionReplaces!==j.Unsupported){const e=A.message.parseHeader("replaces");if(e){const A=e.call_id;if("string"!=typeof A)throw new Error("Type of call id is not string");const s=e.replaces_to_tag;if("string"!=typeof s)throw new Error("Type of to tag is not string");const i=e.replaces_from_tag;if("string"!=typeof i)throw new Error("type of from tag is not string");const n=A+s+i,o=this.userAgentCore.dialogs.get(n);if(!o)return void t.reject({statusCode:481});if(!o.early&&!0===e.early_only)return void t.reject({statusCode:486});const r=this._sessions[A+i]||this._sessions[A+s]||void 0;if(!r)throw new Error("Session does not exist.");t._replacee=r}}if(null===(e=this.delegate)||void 0===e?void 0:e.onInvite)return t.autoSendAnInitialProvisionalResponse?void t.progress().then(()=>{var A;if(void 0===(null===(A=this.delegate)||void 0===A?void 0:A.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(t)}):void this.delegate.onInvite(t);t.reject({statusCode:486})},onMessage:A=>{if(this.delegate&&this.delegate.onMessage){const e=new b(A);this.delegate.onMessage(e)}else A.accept()},onNotify:A=>{if(this.delegate&&this.delegate.onNotify){const e=new J(A);this.delegate.onNotify(e)}else this.options.allowLegacyNotifications?A.accept():A.reject({statusCode:481})},onRefer:A=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(A):A.reject({statusCode:405})},onRegister:A=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(A):A.reject({statusCode:405})},onSubscribe:A=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(A):A.reject({statusCode:405})}};return new WA(t,s)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=A=>this.onTransportDisconnect(A),this.transport.onMessage=A=>this.onTransportMessage(A)}onTransportConnect(){this.state!==eA.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(A){this.state!==eA.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(A),A&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(A){const e=sA.parseMessage(A,this.getLogger("sip.Parser"));if(!e)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===eA.Stopped&&e instanceof T)return void this.logger.warn(`Received ${e.method} request while stopped. Dropping.`);const t=()=>{const A=["from","to","call_id","cseq","via"];for(const t of A)if(!e.hasHeader(t))return this.logger.warn(`Missing mandatory header field : ${t}.`),!1;return!0};if(e instanceof T){if(!t())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!e.toTag&&e.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(e,{statusCode:482});const A=S(e.body),s=e.getHeader("content-length");if(s&&A<Number(s))return void this.userAgentCore.replyStateless(e,{statusCode:400})}if(e instanceof y){if(!t())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(e.via.host!==this.options.viaHost||void 0!==e.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const A=S(e.body),s=e.getHeader("content-length");if(s&&A<Number(s))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(e instanceof T)this.userAgentCore.receiveIncomingRequestFromTransport(e);else{if(!(e instanceof y))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(e)}}transitionState(A,e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${A}`)};switch(this._state){case eA.Started:A!==eA.Stopped&&t();break;case eA.Stopped:A!==eA.Started&&t();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${A}`),this._state=A,this._stateEventEmitter.emit(this._state)}}class $A{constructor(A){this.listeners=[],this.keyListeners={},this.data={...A},this.proxy=new Proxy(this.data,{set:(A,e,t)=>(A[e]!==t&&(A[e]=t,this.notify(),this.notifyKey(e,t)),!0)})}getState(){return this.proxy}setState(A,e=!1){let t=!1;for(const s in A)if(Object.prototype.hasOwnProperty.call(A,s)){const i=this.data[s],n=A[s];(e||i!==n)&&(this.data[s]=n,t=!0,this.notifyKey(s,n))}(t||e)&&this.notify()}subscribe(A){return this.listeners.push(A),()=>{this.listeners=this.listeners.filter(e=>e!==A)}}subscribeKey(A,e){return this.keyListeners[A]||(this.keyListeners[A]=[]),this.keyListeners[A].push(e),()=>{this.keyListeners[A]=this.keyListeners[A].filter(A=>A!==e)}}notify(){const A=this.getState();for(const e of this.listeners)e(A)}notifyKey(A,e){const t=this.keyListeners[A];t&&t.forEach(A=>A(e))}}var Ae,ee,te,se,ie,ne,oe;exports.AgentStatus=void 0,(Ae=exports.AgentStatus||(exports.AgentStatus={}))[Ae.IDLE=1]="IDLE",Ae[Ae.BUSY=2]="BUSY",Ae[Ae.RINGING=3]="RINGING",Ae[Ae.OFFLINE=0]="OFFLINE",Ae[Ae.UNREGISTERED=4]="UNREGISTERED",exports.DirectionEnum=void 0,(ee=exports.DirectionEnum||(exports.DirectionEnum={})).OUTGOING="outgoing",ee.INCOMING="incoming",ee.CONSULT="consult",ee.MEETING="meeting",ee.TRANSFER="transfer",ee.PREDICT_OUT_CALL="predict_out_call",exports.WebsocketTypeEnum=void 0,(te=exports.WebsocketTypeEnum||(exports.WebsocketTypeEnum={}))[te.OUT_CALL=100]="OUT_CALL",te[te.AGENT_STATE=101]="AGENT_STATE",te[te.OUT_CALL_INCOMING_CALL=102]="OUT_CALL_INCOMING_CALL",te[te.OUT_CALL_RINGING=103]="OUT_CALL_RINGING",te[te.OUT_CALL_ANSWER=104]="OUT_CALL_ANSWER",te[te.CALL_HOLD=105]="CALL_HOLD",te[te.CALL_UNHOLD=106]="CALL_UNHOLD",te[te.OUT_CALL_END=107]="OUT_CALL_END",te[te.CONSULT_REQUEST=108]="CONSULT_REQUEST",te[te.CONSULT_RINGING=109]="CONSULT_RINGING",te[te.CONSULT_ANSWER=110]="CONSULT_ANSWER",te[te.CONSULT_FAIL=111]="CONSULT_FAIL",te[te.MUTE=112]="MUTE",te[te.UNMUTE=113]="UNMUTE",te[te.CONSULT_CALL_IN=114]="CONSULT_CALL_IN",te[te.CONSULT_CALL_IN_SUCCESS=115]="CONSULT_CALL_IN_SUCCESS",te[te.CONSULT_RETURN_CALL=125]="CONSULT_RETURN_CALL",te[te.CONSULT_RETURN_CALL_SUCCESS=126]="CONSULT_RETURN_CALL_SUCCESS",te[te.CONSULT_TRANSFER=116]="CONSULT_TRANSFER",te[te.CONSULT_TRANSFER_FAILED=118]="CONSULT_TRANSFER_FAILED",te[te.CONSULT_TRANSFER_OFF_HOOK=117]="CONSULT_TRANSFER_OFF_HOOK",te[te.INCOMING_CALL=119]="INCOMING_CALL",te[te.INCOMING_CALL_OFF_HOOK=120]="INCOMING_CALL_OFF_HOOK",te[te.INCOMING_CALL_END=121]="INCOMING_CALL_END",te[te.SATISFACTION_EVALUATION=122]="SATISFACTION_EVALUATION",te[te.CONSULT_THREE_WAY=123]="CONSULT_THREE_WAY",te[te.CONSULT_THREE_WAY_RESULT=124]="CONSULT_THREE_WAY_RESULT",te[te.TRANSFER=127]="TRANSFER",te[te.TRANSFER_FAILED=128]="TRANSFER_FAILED",te[te.TRANSFER_INCOMING_CALL=129]="TRANSFER_INCOMING_CALL",te[te.TRANSFER_OFF_HOOK=130]="TRANSFER_OFF_HOOK",te[te.AGENT_HANGUP=131]="AGENT_HANGUP",te[te.KICK_OFFLINE=132]="KICK_OFFLINE",te[te.CONTINUOUS_NOT_ANSWER=133]="CONTINUOUS_NOT_ANSWER",te[te.PREVIEW_OUT_CALL=134]="PREVIEW_OUT_CALL",te[te.SIGN_OUT=135]="SIGN_OUT",te[te.SIGN_IN_SWITCH_DEVICE=136]="SIGN_IN_SWITCH_DEVICE",te[te.LISTEN_CALL_FAILED=137]="LISTEN_CALL_FAILED",te[te.LISTEN_INCOMING_CALL=138]="LISTEN_INCOMING_CALL",te[te.LISTEN_INCOMING_CALL_OFF_HOOK=139]="LISTEN_INCOMING_CALL_OFF_HOOK",te[te.EAR_SPEECH=140]="EAR_SPEECH",te[te.STOP_EAR_SPEECH=141]="STOP_EAR_SPEECH",te[te.CALL_FORCE_INSERT=142]="CALL_FORCE_INSERT",exports.WebRtcCallSipEventEnum=void 0,(se=exports.WebRtcCallSipEventEnum||(exports.WebRtcCallSipEventEnum={})).WEB_RTC_CONNECTING="connecting",se.WEB_RTC_CONNECTED="connected",se.WEB_RTC_DISCONNECTING="disconnecting",se.WEB_RTC_DISCONNECTED="disconnected",se.WEB_RTC_REGISTERED="registered",se.WEB_RTC_UNREGISTERED="unregistered",se.WEB_RTC_TERMINATED="terminated",se.WEB_RTC_REGISTER_FAILED="register_failed",se.WEB_RTC_ANSWER_FAILED="answer_failed",se.WEB_RTC_SEND_DTMF="send_dtmf",exports.CallSipCallEventEnum=void 0,(ie=exports.CallSipCallEventEnum||(exports.CallSipCallEventEnum={})).CUSTOMER_INFO="customer_info",ie.CALL_PROGRESS="call_progress",ie.OUT_INCOMING_CALL="out_call_incoming_call",ie.PREVIEW_OUT_INCOMING_CALL="preview_out_incoming_call",ie.OUT_SUCCESS="out_call_success",ie.OUT_FAILED="out_call_failed",ie.OUT_RINGING="out_call_ringing",ie.OUT_OFF_ANSWER="out_call_answer",ie.HOLD_SUCCESS="hold_success",ie.HOLD_FAILED="hold_failed",ie.UNHOLD_SUCCESS="unhold_success",ie.UNHOLD_FAILED="unhold_failed",ie.OUT_HANGUP="out_call_hangup",ie.CONSULT_RINGING="consult_ringing",ie.CONSULT_OFF_HOOK="consult_off_hook",ie.CONSULT_FAILED="consult_failed",ie.CONSULT_INCOMING="consult_incoming",ie.CONSULT_CALL_IN_SUCCESS="consult_call_in_success",ie.CONSULT_RETURN_CALL_SUCCESS="consult_return_call_success",ie.OTHER_SIDE_CONSULT_HANGUP="other_side_consult_hangup",ie.OUR_SIDE_CONSULT_HANGUP="our_side_consult_hangup",ie.AGENT_STATE="agent_state",ie.MUTE_SUCCESS="mute_success",ie.MUTE_FAILED="mute_failed",ie.UNMUTE_SUCCESS="unmute_success",ie.UNMUTE_FAILED="unmute_failed",ie.CONSULT_TRANSFER_SUCCESS="consult_transfer_success",ie.CONSULT_TRANSFER_FAILED="consult_transfer_failed",ie.CONSULT_TRANSFER_OFF_HOOK="consult_transfer_off_hook",ie.INCOMING_CALL="incoming_call",ie.PREDICT_INCOMING_CALL="predict_incoming_call",ie.INCOMING_CALL_OFF_HOOK="incoming_call_off_hook",ie.INCOMING_CALL_END="incoming_call_end",ie.SATISFACTION_EVALUATION_SUCCESS="satisfaction_evaluation_success",ie.SATISFACTION_EVALUATION_FAILED="satisfaction_evaluation_failed",ie.CONSULT_THREE_WAY_SUCCESS="consult_three_way_success",ie.CONSULT_THREE_WAY_FAILED="consult_three_way_failed",ie.THREE_WAY_OUR_SIDE_HANGUP="three_way_our_side_hangup",ie.TRANSFER_FAILED="transfer_failed",ie.TRANSFER_PROGRESS="transfer_progress",ie.TRANSFER_INCOMING_CALL="transfer_incoming_call",ie.TRANSFER_OFF_HOOK="transfer_off_hook",ie.TRANSFER_END="transfer_end",ie.REJECT="reject",ie.LISTEN_CALL_FAILED="listen_call_failed",ie.LISTEN_INCOMING_CALL="listen_incoming_call",ie.LISTEN_INCOMING_CALL_OFF_HOOK="listen_incoming_call_off_hook",ie.LISTEN_HANGUP="listen_hangup",ie.EAR_SPEECH_SUCCESS="ear_speech_success",ie.EAR_SPEECH_BE_SUCCESS="ear_speech_be_success",ie.EAR_SPEECH_FAILED="ear_speech_failed",ie.STOP_EAR_SPEECH_SUCCESS="stop_ear_speech_success",ie.STOP_EAR_SPEECH_FAILED="stop_ear_speech_failed",ie.CALL_FORCE_INSERT_SUCCESS="call_force_insert_success",ie.CALL_FORCE_INSERT_SUCCESS_LISTENER="call_force_insert_success_listener",ie.CALL_FORCE_INSERT_FAILED="call_force_insert_failed",exports.EventName=void 0,(ne=exports.EventName||(exports.EventName={})).EVENT_ALL="event_all",ne.NOTIFICATION_CLICK="notification_click",ne.UPDATE_ANSWER_DEVICE="update_answer_device",ne.PHONE_BAR_OPERATION="phone_bar_operation",ne.AGENT_INIT_STATUS="agent_init_status",ne.WEBSITE_DELAY="website_delay",ne.SELECT_EXTERNAL_NUMBER="select_external_number",ne.FAIL_NOTIFICATION="fail_notification",ne.KICK_OFF="kick_off",ne.DESTROY="destroy",ne.NETWORK_OFFLINE="network_offline",ne.NETWORK_ONLINE="network_online",ne.SIGN_OUT="sign_out",ne.SIGN_IN_SWITCH_DEVICE="sign_in_switch_device",exports.DisplayTextEnum=void 0,(oe=exports.DisplayTextEnum||(exports.DisplayTextEnum={})).RINGING="客户振铃",oe.AGENT_RINGING="振铃中",oe.CALLING="通话中",oe.CONSULTING="正在咨询",oe.CONSULT_CALL_IN="咨询来电",oe.INCOMING_CALL="客户来电",oe.MEETING="会议中",oe.TRANSFERRING="转接中",oe.TRANSFER_INCOMING_CALL="转接来电",oe.HOLDING="保持中",oe.MUTING="静音中",oe.LISTENING="监听来电";const re=function(A){return{all:A=A||new Map,on:function(e,t){var s=A.get(e);s?s.push(t):A.set(e,[t])},off:function(e,t){var s=A.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):A.set(e,[]))},emit:function(e,t){var s=A.get(e);s&&s.slice().map(function(A){A(t)}),(s=A.get("*"))&&s.slice().map(function(A){A(e,t)})}}}(),ae={on:(A,e)=>(re.on(A,e),ae),off(A,e){re.off(A,e)},emit(A,e){re.emit(A,e),re.emit(exports.EventName.EVENT_ALL,{event:A,data:e})},clearAllListeners(){re.all.clear()}},Ve={agentInfo:{},isRtcReconnecting:!1,sessionId:"",enableBrowserAlert:!1,autoStateTimer:null,autoAnswerTimer:null,logBuiltinEnabled:!1,browserAlertTime:3e3,latency:0,monitoredAgentNo:"",earSpeakAgent:""},ce={isCalling:!1,direction:null,outCallIsAnswer:!1,incomingIsAnswer:!1,transferIsAnswer:!1,isMeeting:!1,isHold:!1,displayText:"",isMuted:!1,consultIsAnswer:!1,actionConfigs:[],answerDevice:1,selectOutNumber:"",customerObject:void 0,isNextState:!0};const le=new class extends $A{updateIsCalling(A){this.setState({isCalling:A})}updateDirection(A){this.setState({direction:A})}updateOutCallIsAnswer(A){this.setState({outCallIsAnswer:A})}updateIsHold(A){if(Ve.stateObject?.state===exports.AgentStatus.UNREGISTERED)return;const e=this.get("actionConfigs");if(A){const A=[...e.filter(A=>"hold"!==A)];A.push("unhold"),this.updateActionConfigs(A)}else{const A=[...e.filter(A=>"unhold"!==A)];A.push("hold"),this.updateActionConfigs(A)}this.getState().isHold=A}updateDisplayText(A){this.setState({displayText:A}),ae.emit(exports.CallSipCallEventEnum.CALL_PROGRESS,A)}updateActionConfigs(A){const{show_satisfaction:e}=Ve.agentInfo||{},t=this.get("answerDevice"),s=A.filter(A=>(0!==e||"satisfaction"!==A)&&(2!==t||"answer"!==A));this.setState({actionConfigs:s}),ae.emit(exports.EventName.PHONE_BAR_OPERATION,s)}updateConsultIsAnswer(A){this.setState({consultIsAnswer:A})}updateIsMuted(A){if(Ve.stateObject?.state===exports.AgentStatus.UNREGISTERED)return;const e=this.get("actionConfigs");if(A){const A=[...e.filter(A=>"mute"!==A)];A.push("unmute"),this.updateActionConfigs(A)}else{const A=[...e.filter(A=>"unmute"!==A)];A.push("mute"),this.updateActionConfigs(A)}this.setState({isMuted:A})}updateIncomingIsAnswer(A){this.setState({incomingIsAnswer:A})}updateAnswerDevice(A){this.setState({answerDevice:A}),ae.emit(exports.EventName.UPDATE_ANSWER_DEVICE,A)}updateIsMeeting(A){this.setState({isMeeting:A})}updateTransferIsAnswer(A){this.setState({transferIsAnswer:A})}updateSelectOutNumber(A){ae.emit(exports.EventName.SELECT_EXTERNAL_NUMBER,A),this.setState({selectOutNumber:A})}updateCustomerInfo(A){const e=this.get("displayText");if(A&&e){const{contact_count:e,customer_name:t,phone:s,city:i,province:n,is_vip:o,in_contact_count:r,trace_id:a,contact_count_month:V,in_contact_count_month:c}=A;ae.emit(exports.CallSipCallEventEnum.CUSTOMER_INFO,{customer_name:t||"未知客户",phone:s,city:i||"未知",province:n||"未知",contact_count:e||0,in_contact_count:r||0,is_vip:o,trace_id:a,contact_count_month:V||0,in_contact_count_month:c||0})}else ae.emit(exports.CallSipCallEventEnum.CUSTOMER_INFO,void 0);this.setState({customerObject:A})}updateIsNextState(A){this.setState({isNextState:A}),A?ae.emit(exports.EventName.NETWORK_ONLINE):(Ve.stateObject={state:exports.AgentStatus.OFFLINE,state_name:"离线"},this.updateActionConfigs([]),ae.emit(exports.CallSipCallEventEnum.AGENT_STATE,Ve.stateObject),ae.emit(exports.EventName.NETWORK_OFFLINE))}reset(){this.updateIsCalling(ce.isCalling),this.updateDirection(ce.direction),this.updateOutCallIsAnswer(ce.outCallIsAnswer),this.updateIsHold(ce.isHold),this.updateDisplayText(ce.displayText),this.updateActionConfigs(ce.actionConfigs),this.updateConsultIsAnswer(ce.consultIsAnswer),this.updateIsMuted(ce.isMuted),this.updateIncomingIsAnswer(ce.incomingIsAnswer),this.updateIsMeeting(ce.isMeeting),this.updateTransferIsAnswer(ce.transferIsAnswer),this.updateCustomerInfo(void 0)}getCallInfo(){return this.getState()}get(A){return this.getState()[A]}}(ce);const he=new class extends $A{updateRttObject(A){this.setState({rttObject:A}),ae.emit(exports.EventName.WEBSITE_DELAY,A)}}({rttObject:{rtt:null,jitter:null,packetsLost:null,packetsReceived:null,packetsSent:null,sendBitrate:null,recvBitrate:null,codec:null}});class ge{constructor(A,e){this.config=A,this.eventCallback=e,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.isManuallyStopped=!1,this.registerIntervalTimer=null,this.registerInterval=6e4,this.handleNetworkInfoChange=A=>{if(A.rttObject?.rtt){0===(A.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()},he.subscribe(this.handleNetworkInfoChange)}async start(){const A=_A.makeURI(`sip:${this.config.user}@${this.config.server}`);if(!A)throw new Error("无效的SIP配置");const e={uri:A,authorizationUsername:this.config.user,authorizationPassword:this.config.password,transportOptions:{server:this.config.webSocket,connectionTimeout:30,keepAliveInterval:20},contactName:this.config.user,contactParams:{transport:"wss"},userAgentString:"SwiftSIP/1.1.19",sessionDescriptionHandlerFactoryOptions:{alwaysAcquireMediaFirst:!0,peerConnectionConfiguration:{iceServers:[{urls:"stun:stun.qq.com:3478"},{urls:"stun:stun.agora.io:3478"}]},iceGatheringTimeout:1500},logBuiltinEnabled:Ve.logBuiltinEnabled};this.userAgent=new _A(e),this.setupEventListeners(),await this.userAgent.start(),await this.register()}setupEventListeners(){this.userAgent&&(this.userAgent.transport.stateChange.addListener(A=>{let e;switch(A){case AA.Connecting:e=exports.WebRtcCallSipEventEnum.WEB_RTC_CONNECTING;break;case AA.Connected:e=exports.WebRtcCallSipEventEnum.WEB_RTC_CONNECTED,this.reconnectAttempts=0,Ve.isRtcReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);break;case AA.Disconnecting:e=exports.WebRtcCallSipEventEnum.WEB_RTC_DISCONNECTING;break;case AA.Disconnected:{if(this.isManuallyStopped)return void console.warn("[SIP] 手动断开,不触发重连");e=exports.WebRtcCallSipEventEnum.WEB_RTC_DISCONNECTED;const A=le.get("answerDevice");if(!Ve.isRtcReconnecting&&this.reconnectAttempts<this.maxReconnectAttempts&&1===A){this.reconnectAttempts++;const A=1e3*this.reconnectAttempts;console.warn(`SIP WebSocket 断开,第 ${this.reconnectAttempts} 次尝试重连,${A}ms 后重试...`),this.reconnectTimer=setTimeout(()=>{this.reconnect()},A)}else this.reconnectAttempts>=this.maxReconnectAttempts&&console.error("SIP 重连失败:已达到最大重试次数");break}default:e="unknown"}this.eventCallback?.({type:e})}),this.userAgent.delegate={onInvite:A=>{this.handleIncomingCall(A)}})}async refreshRegister(){if(this.registerer)try{await this.registerer.register(),(new Date).toLocaleTimeString()}catch(A){console.error("[SIPClient] REGISTER刷新失败",A)}}async register(){if(this.userAgent){this.registerer=new nA(this.userAgent),this.registerer?.stateChange.addListener(A=>{let e;switch(A){case _.Initial:e="initial";break;case _.Registered:e=exports.WebRtcCallSipEventEnum.WEB_RTC_REGISTERED;break;case _.Unregistered:e=exports.WebRtcCallSipEventEnum.WEB_RTC_UNREGISTERED;break;case _.Terminated:e=exports.WebRtcCallSipEventEnum.WEB_RTC_TERMINATED;break;default:e="unknown"}this.eventCallback?.({type:e})});try{await this.registerer.register(),this.registerIntervalTimer||(this.registerIntervalTimer=setInterval(()=>{this.refreshRegister()},this.registerInterval))}catch(A){this.eventCallback?.({type:exports.WebRtcCallSipEventEnum.WEB_RTC_REGISTER_FAILED,data:A})}}}attachRemoteAudio(A){const e=A.sessionDescriptionHandler;if(e){const A=e.peerConnection;if(!A)return;const t=new MediaStream;A.getReceivers().forEach(A=>{A.track&&"audio"===A.track.kind&&t.addTrack(A.track)});let s=document.getElementById("sip-remote-audio");s||(s=document.createElement("audio"),s.id="sip-remote-audio",s.autoplay=!0,s.style.display="none",document.body.appendChild(s)),s.srcObject=t,s.play().catch(A=>{console.error("音频播放失败,需要用户交互触发",A)})}}handleSessionState(A,e,t){A.stateChange.addListener(e=>{switch(e){case H.Established:clearTimeout(this.callTimeoutTimer),this.activeSession=A,this.attachRemoteAudio(A);break;case H.Terminating:break;case H.Terminated:this.activeSession=null,clearTimeout(this.callTimeoutTimer);case H.Establishing:}})}handleIncomingCall(A){this.incomingInvitation=A,this.handleSessionState(A,!1);le.get("direction")===exports.DirectionEnum.OUTGOING&&this.answerCall()}async answerCall(){if(!this.incomingInvitation)throw new Error("无来电可接听");Ve.autoAnswerTimer&&(clearTimeout(Ve.autoAnswerTimer),Ve.autoAnswerTimer=null);try{await this.incomingInvitation.accept(),this.activeSession=this.incomingInvitation,this.incomingInvitation=null}catch(A){this.eventCallback?.({type:exports.WebRtcCallSipEventEnum.WEB_RTC_ANSWER_FAILED,data:{detail:A}})}}async rejectInCall(){if(this.incomingInvitation)try{await this.incomingInvitation.reject(),this.incomingInvitation=null,le.updateDirection(null),le.updateIsCalling(!1),clearTimeout(this.callTimeoutTimer)}catch(A){this.eventCallback?.({type:"error",data:{message:"拒接失败",detail:A}})}}sendDTMF(A){if(!this.activeSession)throw new Error("当前没有活跃的通话");const e=this.activeSession.sessionDescriptionHandler;e&&"function"==typeof e.sendDtmf?(e.sendDtmf(A),this.eventCallback?.({type:exports.WebRtcCallSipEventEnum.WEB_RTC_SEND_DTMF,data:{tone:A}})):console.warn("DTMF发送不支持或未初始化")}async hangup(){if(this.activeSession,this.activeSession){clearTimeout(this.callTimeoutTimer);const A=this.activeSession;if(!A)return;const e=A.state;try{e===H.Established?await A.bye():e===H.Establishing&&(A instanceof X?await A.cancel():A instanceof z&&await A.reject()),clearTimeout(this.callTimeoutTimer)}catch(A){console.error("挂断失败",A)}finally{this.activeSession=null}}}async rejectOutCall(){this.activeSession instanceof z&&(await this.activeSession.reject(),this.activeSession=null)}async destroy(){if(this.isManuallyStopped=!0,clearTimeout(this.callTimeoutTimer),clearInterval(this.registerIntervalTimer),this.activeSession&&await this.hangup(),this.registerIntervalTimer&&(clearInterval(this.registerIntervalTimer),this.registerIntervalTimer=null),this.registerer){try{await this.registerer.unregister()}catch(A){console.warn("注销失败",A)}this.registerer=null}this.userAgent&&(await this.userAgent.stop(),this.userAgent=null)}async reconnect(){if(!Ve.isRtcReconnecting){Ve.isRtcReconnecting=!0;try{await this.destroy(),await this.start(),this.isOffline=!1}catch(A){console.error("重连失败",A)}finally{Ve.isRtcReconnecting=!1}}}async getNetworkStats(){if(this.activeSession){const A=this.activeSession.sessionDescriptionHandler?.peerConnection;if(!A)return null;const e=await A.getStats(),t={};return e.forEach(A=>{"candidate-pair"===A.type&&"succeeded"===A.state&&null!=A.currentRoundTripTime&&(t.rtt=+(1e3*A.currentRoundTripTime).toFixed(2)),"inbound-rtp"===A.type&&"audio"===A.kind&&(t.jitter=+(1e3*A.jitter).toFixed(2),t.packetsLost=A.packetsLost,t.packetsReceived=A.packetsReceived,A.bytesReceived&&A.timestamp&&(t.recvBitrate=+(A.bytesReceived/1024).toFixed(2))),"outbound-rtp"===A.type&&"audio"===A.kind&&(t.packetsSent=A.packetsSent,A.bytesSent&&A.timestamp&&(t.sendBitrate=+(A.bytesSent/1024).toFixed(2))),"codec"===A.type&&A.mimeType&&(t.codec=A.mimeType)}),{...t,rtt:t?.rtt||40}}return{rtt:Ve.latency||1}}}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var A=require("crypto"),e=require("buffer");class t extends Error{constructor(A){super(A),Object.setPrototypeOf(this,new.target.prototype)}}class s extends t{constructor(A){super(A||"Unsupported content type.")}}class i extends t{constructor(A){super(A||"Request pending.")}}class n extends t{constructor(A){super(A||"Unspecified session description handler error.")}}class o extends t{constructor(){super("The session has terminated.")}}class r extends t{constructor(A){super(A||"An error occurred during state transition.")}}class a{constructor(A){this.incomingAckRequest=A}get request(){return this.incomingAckRequest.message}}class V{constructor(A){this.incomingByeRequest=A}get request(){return this.incomingByeRequest.message}accept(A){return this.incomingByeRequest.accept(A),Promise.resolve()}reject(A){return this.incomingByeRequest.reject(A),Promise.resolve()}}class c{constructor(A){this.incomingCancelRequest=A}get request(){return this.incomingCancelRequest}}class l{constructor(){this.listeners=new Array}addListener(A,e){const t=e=>{this.removeListener(t),A(e)};!0===(null==e?void 0:e.once)?this.listeners.push(t):this.listeners.push(A)}emit(A){this.listeners.slice().forEach(e=>e(A))}removeAllListeners(){this.listeners=[]}removeListener(A){this.listeners=this.listeners.filter(e=>e!==A)}on(A){return this.addListener(A)}off(A){return this.removeListener(A)}once(A){return this.addListener(A,{once:!0})}}class h{constructor(A){this.incomingInfoRequest=A}get request(){return this.incomingInfoRequest.message}accept(A){return this.incomingInfoRequest.accept(A),Promise.resolve()}reject(A){return this.incomingInfoRequest.reject(A),Promise.resolve()}}class g{constructor(A){this.parameters={};for(const e in A)A.hasOwnProperty(e)&&this.setParam(e,A[e])}setParam(A,e){A&&(this.parameters[A.toLowerCase()]=null==e?null:e.toString())}getParam(A){if(A)return this.parameters[A.toLowerCase()]}hasParam(A){return!(!A||void 0===this.parameters[A.toLowerCase()])}deleteParam(A){if(A=A.toLowerCase(),this.hasParam(A)){const e=this.parameters[A];return delete this.parameters[A],e}}clearParams(){this.parameters={}}}class q extends g{constructor(A,e,t){super(t),this.uri=A,this._displayName=e}get friendlyName(){return this.displayName||this.uri.aor}get displayName(){return this._displayName}set displayName(A){this._displayName=A}clone(){return new q(this.uri.clone(),this._displayName,JSON.parse(JSON.stringify(this.parameters)))}toString(){let A=this.displayName||"0"===this.displayName?'"'+this.displayName+'" ':"";A+="<"+this.uri.toString()+">";for(const e in this.parameters)this.parameters.hasOwnProperty(e)&&(A+=";"+e,null!==this.parameters[e]&&(A+="="+this.parameters[e]));return A}}class d extends g{constructor(A="sip",e,t,s,i,n){if(super(i||{}),this.headers={},!t)throw new TypeError('missing or invalid "host" parameter');for(const A in n)n.hasOwnProperty(A)&&this.setHeader(A,n[A]);this.raw={scheme:A,user:e,host:t,port:s},this.normal={scheme:A.toLowerCase(),user:e,host:t.toLowerCase(),port:s}}get scheme(){return this.normal.scheme}set scheme(A){this.raw.scheme=A,this.normal.scheme=A.toLowerCase()}get user(){return this.normal.user}set user(A){this.normal.user=this.raw.user=A}get host(){return this.normal.host}set host(A){this.raw.host=A,this.normal.host=A.toLowerCase()}get aor(){return this.normal.user+"@"+this.normal.host}get port(){return this.normal.port}set port(A){this.normal.port=this.raw.port=A}setHeader(A,e){this.headers[this.headerize(A)]=e instanceof Array?e:[e]}getHeader(A){if(A)return this.headers[this.headerize(A)]}hasHeader(A){return!!A&&!!this.headers.hasOwnProperty(this.headerize(A))}deleteHeader(A){if(A=this.headerize(A),this.headers.hasOwnProperty(A)){const e=this.headers[A];return delete this.headers[A],e}}clearHeaders(){this.headers={}}clone(){return new d(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(A){let e=A.scheme+":";A.scheme.toLowerCase().match("^sips?$")||(e+="//"),A.user&&(e+=this.escapeUser(A.user)+"@"),e+=A.host,(A.port||0===A.port)&&(e+=":"+A.port);for(const A in this.parameters)this.parameters.hasOwnProperty(A)&&(e+=";"+A,null!==this.parameters[A]&&(e+="="+this.parameters[A]));const t=[];for(const A in this.headers)if(this.headers.hasOwnProperty(A))for(const e in this.headers[A])this.headers[A].hasOwnProperty(e)&&t.push(A+"="+this.headers[A][e]);return t.length>0&&(e+="?"+t.join("&")),e}escapeUser(A){let e;try{e=decodeURIComponent(A)}catch(A){throw A}return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%2B/gi,"+").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}headerize(A){const e={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},t=A.toLowerCase().replace(/_/g,"-").split("-"),s=t.length;let i="";for(let A=0;A<s;A++)0!==A&&(i+="-"),i+=t[A].charAt(0).toUpperCase()+t[A].substring(1);return e[i]&&(i=e[i]),i}}function p(A,e){if(A.scheme!==e.scheme)return!1;if(A.user!==e.user||A.host!==e.host||A.port!==e.port)return!1;if(!function(A,e){const t=Object.keys(A.parameters),s=Object.keys(e.parameters),i=t.filter(A=>s.includes(A));return!!i.every(t=>A.parameters[t]===e.parameters[t])&&(!!["user","ttl","method","transport"].every(t=>A.hasParam(t)&&e.hasParam(t)||!A.hasParam(t)&&!e.hasParam(t))&&!!["maddr"].every(t=>A.hasParam(t)&&e.hasParam(t)||!A.hasParam(t)&&!e.hasParam(t)))}(A,e))return!1;const t=Object.keys(A.headers),s=Object.keys(e.headers);if(0!==t.length||0!==s.length){if(t.length!==s.length)return!1;const i=t.filter(A=>s.includes(A));if(i.length!==s.length)return!1;if(!i.every(t=>A.headers[t].length&&e.headers[t].length&&A.headers[t][0]===e.headers[t][0]))return!1}return!0}function u(A,e,t){return t=t||" ",A.length>e?A:(e-=A.length,A+(t+=t.repeat(e)).slice(0,e))}class m extends Error{constructor(A,e,t,s){super(),this.message=A,this.expected=e,this.found=t,this.location=s,this.name="SyntaxError","function"==typeof Object.setPrototypeOf?Object.setPrototypeOf(this,m.prototype):this.__proto__=m.prototype,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,m)}static buildMessage(A,e){function t(A){return A.charCodeAt(0).toString(16).toUpperCase()}function s(A){return A.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,A=>"\\x0"+t(A)).replace(/[\x10-\x1F\x7F-\x9F]/g,A=>"\\x"+t(A))}function i(A){return A.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,A=>"\\x0"+t(A)).replace(/[\x10-\x1F\x7F-\x9F]/g,A=>"\\x"+t(A))}function n(A){switch(A.type){case"literal":return'"'+s(A.text)+'"';case"class":const e=A.parts.map(A=>Array.isArray(A)?i(A[0])+"-"+i(A[1]):i(A));return"["+(A.inverted?"^":"")+e+"]";case"any":return"any character";case"end":return"end of input";case"other":return A.description}}return"Expected "+function(A){const e=A.map(n);let t,s;if(e.sort(),e.length>0){for(t=1,s=1;t<e.length;t++)e[t-1]!==e[t]&&(e[s]=e[t],s++);e.length=s}switch(e.length){case 1:return e[0];case 2:return e[0]+" or "+e[1];default:return e.slice(0,-1).join(", ")+", or "+e[e.length-1]}}(A)+" but "+(((o=e)?'"'+s(o)+'"':"end of input")+" found.");var o}format(A){let e="Error: "+this.message;if(this.location){let t,s=null;for(t=0;t<A.length;t++)if(A[t].source===this.location.source){s=A[t].text.split(/\r\n|\n|\r/g);break}let i=this.location.start,n=this.location.source+":"+i.line+":"+i.column;if(s){let A=this.location.end,t=u("",i.line.toString().length," "),o=s[i.line-1],r=i.line===A.line?A.column:o.length+1;e+="\n --\x3e "+n+"\n"+t+" |\n"+i.line+" | "+o+"\n"+t+" | "+u("",i.column-1," ")+u("",r-i.column,"^")}else e+="\n at "+n}return e}}const E=function(A,e){const t={},s=(e=void 0!==e?e:{}).grammarSource,i={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",C("\r\n",!1),/^[0-9]/,I([["0","9"]],!1,!1),/^[a-zA-Z]/,I([["a","z"],["A","Z"]],!1,!1),/^[0-9a-fA-F]/,I([["0","9"],["a","f"],["A","F"]],!1,!1),/^[\0-\xFF]/,I([["\0","ÿ"]],!1,!1),/^["]/,I(['"'],!1,!1)," ",C(" ",!1),"\t",C("\t",!1),/^[a-zA-Z0-9]/,I([["a","z"],["A","Z"],["0","9"]],!1,!1),";",C(";",!1),"/",C("/",!1),"?",C("?",!1),":",C(":",!1),"@",C("@",!1),"&",C("&",!1),"=",C("=",!1),"+",C("+",!1),"$",C("$",!1),",",C(",",!1),"-",C("-",!1),"_",C("_",!1),".",C(".",!1),"!",C("!",!1),"~",C("~",!1),"*",C("*",!1),"'",C("'",!1),"(",C("(",!1),")",C(")",!1),"%",C("%",!1),function(){return" "},function(){return":"},/^[!-~]/,I([["!","~"]],!1,!1),/^[\x80-\uFFFF]/,I([["",""]],!1,!1),/^[\x80-\xBF]/,I([["","¿"]],!1,!1),/^[a-f]/,I([["a","f"]],!1,!1),"`",C("`",!1),"<",C("<",!1),">",C(">",!1),"\\",C("\\",!1),"[",C("[",!1),"]",C("]",!1),"{",C("{",!1),"}",C("}",!1),function(){return"*"},function(){return"/"},function(){return"="},function(){return"("},function(){return")"},function(){return">"},function(){return"<"},function(){return","},function(){return";"},function(){return":"},function(){return'"'},/^[!-']/,I([["!","'"]],!1,!1),/^[*-[]/,I([["*","["]],!1,!1),/^[\]-~]/,I([["]","~"]],!1,!1),function(A){return A},/^[#-[]/,I([["#","["]],!1,!1),/^[\0-\t]/,I([["\0","\t"]],!1,!1),/^[\v-\f]/,I([["\v","\f"]],!1,!1),/^[\x0E-\x7F]/,I([["",""]],!1,!1),function(){(e=e||{data:{}}).data.uri=new d(e.data.scheme,e.data.user,e.data.host,e.data.port),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port},function(){(e=e||{data:{}}).data.uri=new d(e.data.scheme,e.data.user,e.data.host,e.data.port,e.data.uri_params,e.data.uri_headers),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port,delete e.data.uri_params,"SIP_URI"===e.startRule&&(e.data=e.data.uri)},"sips",C("sips",!0),"sip",C("sip",!0),function(A){(e=e||{data:{}}).data.scheme=A},function(){(e=e||{data:{}}).data.user=decodeURIComponent(u().slice(0,-1))},function(){(e=e||{data:{}}).data.password=u()},function(){return(e=e||{data:{}}).data.host=u(),e.data.host},function(){return(e=e||{data:{}}).data.host_type="domain",u()},/^[a-zA-Z0-9_\-]/,I([["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),/^[a-zA-Z0-9\-]/,I([["a","z"],["A","Z"],["0","9"],"-"],!1,!1),function(){return(e=e||{data:{}}).data.host_type="IPv6",u()},"::",C("::",!1),function(){return(e=e||{data:{}}).data.host_type="IPv6",u()},function(){return(e=e||{data:{}}).data.host_type="IPv4",u()},"25",C("25",!1),/^[0-5]/,I([["0","5"]],!1,!1),"2",C("2",!1),/^[0-4]/,I([["0","4"]],!1,!1),"1",C("1",!1),/^[1-9]/,I([["1","9"]],!1,!1),function(A){return e=e||{data:{}},A=parseInt(A.join("")),e.data.port=A,A},"transport=",C("transport=",!0),"udp",C("udp",!0),"tcp",C("tcp",!0),"sctp",C("sctp",!0),"tls",C("tls",!0),function(A){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.transport=A.toLowerCase()},"user=",C("user=",!0),"phone",C("phone",!0),"ip",C("ip",!0),function(A){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.user=A.toLowerCase()},"method=",C("method=",!0),function(A){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.method=A},"ttl=",C("ttl=",!0),function(A){(e=e||{data:{}}).data.params||(e.data.params={}),e.data.params.ttl=A},"maddr=",C("maddr=",!0),function(A){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.maddr=A},"lr",C("lr",!0),function(){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),e.data.uri_params.lr=void 0},function(A,t){(e=e||{data:{}}).data.uri_params||(e.data.uri_params={}),t=null===t?void 0:t[1],e.data.uri_params[A.toLowerCase()]=t},function(A,t){A=A.join("").toLowerCase(),t=t.join(""),(e=e||{data:{}}).data.uri_headers||(e.data.uri_headers={}),e.data.uri_headers[A]?e.data.uri_headers[A].push(t):e.data.uri_headers[A]=[t]},function(){"Refer_To"===(e=e||{data:{}}).startRule&&(e.data.uri=new d(e.data.scheme,e.data.user,e.data.host,e.data.port,e.data.uri_params,e.data.uri_headers),delete e.data.scheme,delete e.data.user,delete e.data.host,delete e.data.host_type,delete e.data.port,delete e.data.uri_params)},"//",C("//",!1),function(){(e=e||{data:{}}).data.scheme=u()},C("SIP",!0),function(){(e=e||{data:{}}).data.sip_version=u()},"INVITE",C("INVITE",!1),"ACK",C("ACK",!1),"VXACH",C("VXACH",!1),"OPTIONS",C("OPTIONS",!1),"BYE",C("BYE",!1),"CANCEL",C("CANCEL",!1),"REGISTER",C("REGISTER",!1),"SUBSCRIBE",C("SUBSCRIBE",!1),"NOTIFY",C("NOTIFY",!1),"REFER",C("REFER",!1),"PUBLISH",C("PUBLISH",!1),function(){return(e=e||{data:{}}).data.method=u(),e.data.method},function(A){(e=e||{data:{}}).data.status_code=parseInt(A.join(""))},function(){(e=e||{data:{}}).data.reason_phrase=u()},function(){(e=e||{data:{}}).data=u()},function(){var A,t;for(t=(e=e||{data:{}}).data.multi_header.length,A=0;A<t;A++)if(null===e.data.multi_header[A].parsed){e.data=null;break}null!==e.data?e.data=e.data.multi_header:e.data=-1},function(){var A;(e=e||{data:{}}).data.multi_header||(e.data.multi_header=[]);try{A=new q(e.data.uri,e.data.displayName,e.data.params),delete e.data.uri,delete e.data.displayName,delete e.data.params}catch(e){A=null}e.data.multi_header.push({position:a,offset:E().start.offset,parsed:A})},function(A){'"'===(A=u().trim())[0]&&(A=A.substring(1,A.length-1)),(e=e||{data:{}}).data.displayName=A},"q",C("q",!0),function(A){(e=e||{data:{}}).data.params||(e.data.params={}),e.data.params.q=A},"expires",C("expires",!0),function(A){(e=e||{data:{}}).data.params||(e.data.params={}),e.data.params.expires=A},function(A){return parseInt(A.join(""))},"0",C("0",!1),function(){return parseFloat(u())},function(A,t){(e=e||{data:{}}).data.params||(e.data.params={}),t=null===t?void 0:t[1],e.data.params[A.toLowerCase()]=t},"render",C("render",!0),"session",C("session",!0),"icon",C("icon",!0),"alert",C("alert",!0),function(){"Content_Disposition"===(e=e||{data:{}}).startRule&&(e.data.type=u().toLowerCase())},"handling",C("handling",!0),"optional",C("optional",!0),"required",C("required",!0),function(A){(e=e||{data:{}}).data=parseInt(A.join(""))},function(){(e=e||{data:{}}).data=u()},"text",C("text",!0),"image",C("image",!0),"audio",C("audio",!0),"video",C("video",!0),"application",C("application",!0),"message",C("message",!0),"multipart",C("multipart",!0),"x-",C("x-",!0),function(A){(e=e||{data:{}}).data.value=parseInt(A.join(""))},function(A){(e=e||{data:{}}).data=A},function(A){(e=e||{data:{}}).data.event=A.toLowerCase()},function(){var A=(e=e||{data:{}}).data.tag;e.data=new q(e.data.uri,e.data.displayName,e.data.params),A&&e.data.setParam("tag",A)},"tag",C("tag",!0),function(A){(e=e||{data:{}}).data.tag=A},function(A){(e=e||{data:{}}).data=parseInt(A.join(""))},function(A){(e=e||{data:{}}).data=A},function(){(e=e||{data:{}}).data=new q(e.data.uri,e.data.displayName,e.data.params)},"digest",C("Digest",!0),"realm",C("realm",!0),function(A){(e=e||{data:{}}).data.realm=A},"domain",C("domain",!0),"nonce",C("nonce",!0),function(A){(e=e||{data:{}}).data.nonce=A},"opaque",C("opaque",!0),function(A){(e=e||{data:{}}).data.opaque=A},"stale",C("stale",!0),"true",C("true",!0),function(){(e=e||{data:{}}).data.stale=!0},"false",C("false",!0),function(){(e=e||{data:{}}).data.stale=!1},"algorithm",C("algorithm",!0),"md5",C("MD5",!0),"md5-sess",C("MD5-sess",!0),function(A){(e=e||{data:{}}).data.algorithm=A.toUpperCase()},"qop",C("qop",!0),"auth-int",C("auth-int",!0),"auth",C("auth",!0),function(A){(e=e||{data:{}}).data.qop||(e.data.qop=[]),e.data.qop.push(A.toLowerCase())},function(A){(e=e||{data:{}}).data.value=parseInt(A.join(""))},function(){var A,t;for(t=(e=e||{data:{}}).data.multi_header.length,A=0;A<t;A++)if(null===e.data.multi_header[A].parsed){e.data=null;break}null!==e.data?e.data=e.data.multi_header:e.data=-1},function(){var A;(e=e||{data:{}}).data.multi_header||(e.data.multi_header=[]);try{A=new q(e.data.uri,e.data.displayName,e.data.params),delete e.data.uri,delete e.data.displayName,delete e.data.params}catch(e){A=null}e.data.multi_header.push({position:a,offset:E().start.offset,parsed:A})},function(){(e=e||{data:{}}).data=new q(e.data.uri,e.data.displayName,e.data.params)},function(){(e=e||{data:{}}).data.replaces_from_tag&&e.data.replaces_to_tag||(e.data=-1)},function(){(e=e||{data:{}}).data={call_id:e.data}},"from-tag",C("from-tag",!0),function(A){(e=e||{data:{}}).data.replaces_from_tag=A},"to-tag",C("to-tag",!0),function(A){(e=e||{data:{}}).data.replaces_to_tag=A},"early-only",C("early-only",!0),function(){(e=e||{data:{}}).data.early_only=!0},function(A,e){return e},function(A,e){return function(A,e){return[A].concat(e)}(A,e)},function(A){"Require"===(e=e||{data:{}}).startRule&&(e.data=A||[])},function(A){(e=e||{data:{}}).data.value=parseInt(A.join(""))},"active",C("active",!0),"pending",C("pending",!0),"terminated",C("terminated",!0),function(){(e=e||{data:{}}).data.state=u()},"reason",C("reason",!0),function(A){e=e||{data:{}},void 0!==A&&(e.data.reason=A)},function(A){e=e||{data:{}},void 0!==A&&(e.data.expires=A)},"retry_after",C("retry_after",!0),function(A){e=e||{data:{}},void 0!==A&&(e.data.retry_after=A)},"deactivated",C("deactivated",!0),"probation",C("probation",!0),"rejected",C("rejected",!0),"timeout",C("timeout",!0),"giveup",C("giveup",!0),"noresource",C("noresource",!0),"invariant",C("invariant",!0),function(A){"Supported"===(e=e||{data:{}}).startRule&&(e.data=A||[])},function(){var A=(e=e||{data:{}}).data.tag;e.data=new q(e.data.uri,e.data.displayName,e.data.params),A&&e.data.setParam("tag",A)},"ttl",C("ttl",!0),function(A){(e=e||{data:{}}).data.ttl=A},"maddr",C("maddr",!0),function(A){(e=e||{data:{}}).data.maddr=A},"received",C("received",!0),function(A){(e=e||{data:{}}).data.received=A},"branch",C("branch",!0),function(A){(e=e||{data:{}}).data.branch=A},"rport",C("rport",!0),function(A){e=e||{data:{}},void 0!==A&&(e.data.rport=A.join(""))},function(A){(e=e||{data:{}}).data.protocol=A},C("UDP",!0),C("TCP",!0),C("TLS",!0),C("SCTP",!0),function(A){(e=e||{data:{}}).data.transport=A},function(){(e=e||{data:{}}).data.host=u()},function(A){(e=e||{data:{}}).data.port=parseInt(A.join(""))},function(A){return parseInt(A.join(""))},function(A){"Session_Expires"===(e=e||{data:{}}).startRule&&(e.data.deltaSeconds=A)},"refresher",C("refresher",!1),"uas",C("uas",!1),"uac",C("uac",!1),function(A){"Session_Expires"===(e=e||{data:{}}).startRule&&(e.data.refresher=A)},function(A){"Min_SE"===(e=e||{data:{}}).startRule&&(e.data=A)},"stuns",C("stuns",!0),"stun",C("stun",!0),function(A){(e=e||{data:{}}).data.scheme=A},function(A){(e=e||{data:{}}).data.host=A},"?transport=",C("?transport=",!1),"turns",C("turns",!0),"turn",C("turn",!0),function(A){(e=e||{data:{}}).data.transport=A},function(){(e=e||{data:{}}).data=u()},"Referred-By",C("Referred-By",!1),"b",C("b",!1),"cid",C("cid",!1)],r=[B('2 ""6 7!'),B('4"""5!7#'),B('4$""5!7%'),B('4&""5!7\''),B(";'.# &;("),B('4(""5!7)'),B('4*""5!7+'),B('2,""6,7-'),B('2.""6.7/'),B('40""5!71'),B('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'),B(";).# &;,"),B('2F""6F7G.} &2H""6H7I.q &2J""6J7K.e &2L""6L7M.Y &2N""6N7O.M &2P""6P7Q.A &2R""6R7S.5 &2T""6T7U.) &2V""6V7W'),B('%%2X""6X7Y/5#;#/,$;#/#$+#)(#\'#("\'#&\'#/"!&,)'),B('%%$;$0#*;$&/,#; /#$+")("\'#&\'#." &"/=#$;$/�#*;$&&&#/\'$8":Z" )("\'#&\'#'),B(';.." &"'),B("%$;'.# &;(0)*;'.# &;(&/?#28\"\"6879/0$;//'$8#:[# )(#'#(\"'#&'#"),B('%%$;2/�#*;2&&&#/g#$%$;.0#*;.&/,#;2/#$+")("\'#&\'#0=*%$;.0#*;.&/,#;2/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),B('4\\""5!7].# &;3'),B('4^""5!7_'),B('4`""5!7a'),B(';!.) &4b""5!7c'),B('%$;). &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&&&#/"!&,)'),B('%$;). &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&&&#/"!&,)'),B('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.) &;\'.# &;('),B('%$;).ī &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&&&#/"!&,)'),B("%;//?#2P\"\"6P7Q/0$;//'$8#:t# )(#'#(\"'#&'#"),B("%;//?#24\"\"6475/0$;//'$8#:u# )(#'#(\"'#&'#"),B("%;//?#2>\"\"6>7?/0$;//'$8#:v# )(#'#(\"'#&'#"),B("%;//?#2T\"\"6T7U/0$;//'$8#:w# )(#'#(\"'#&'#"),B("%;//?#2V\"\"6V7W/0$;//'$8#:x# )(#'#(\"'#&'#"),B('%2h""6h7i/0#;//\'$8":y" )("\'#&\'#'),B('%;//6#2f""6f7g/\'$8":z" )("\'#&\'#'),B("%;//?#2D\"\"6D7E/0$;//'$8#:{# )(#'#(\"'#&'#"),B("%;//?#22\"\"6273/0$;//'$8#:|# )(#'#(\"'#&'#"),B("%;//?#28\"\"6879/0$;//'$8#:}# )(#'#(\"'#&'#"),B("%;//0#;&/'$8\":~\" )(\"'#&'#"),B("%;&/0#;//'$8\":~\" )(\"'#&'#"),B("%;=/T#$;G.) &;K.# &;F0/*;G.) &;K.# &;F&/,$;>/#$+#)(#'#(\"'#&'#"),B('4""5!7.A &4""5!7.5 &4""5!7.) &;3.# &;.'),B("%%;//Q#;&/H$$;J.# &;K0)*;J.# &;K&/,$;&/#$+$)($'#(#'#(\"'#&'#/\"!&,)"),B("%;//]#;&/T$%$;J.# &;K0)*;J.# &;K&/\"!&,)/1$;&/($8$:
$!!)($'#(#'#(\"'#&'#"),B(';..G &2L""6L7M.; &4""5!7./ &4""5!7.# &;3'),B('%2j""6j7k/J#4""5!7.5 &4""5!7.) &4""5!7/#$+")("\'#&\'#'),B("%;N/M#28\"\"6879/>$;O.\" &\"/0$;S/'$8$:$ )($'#(#'#(\"'#&'#"),B("%;N/d#28\"\"6879/U$;O.\" &\"/G$;S/>$;_/5$;l.\" &\"/'$8&:& )(&'#(%'#($'#(#'#(\"'#&'#"),B('%3""5$7.) &3""5#7/\' 8!:!! )'),B('%;P/]#%28""6879/,#;R/#$+")("\'#&\'#." &"/6$2:""6:7;/\'$8#:# )(#\'#("\'#&\'#'),B("$;+.) &;-.# &;Q/2#0/*;+.) &;-.# &;Q&&&#"),B('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'),B('%$;+._ &;-.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!:! )'),B('%;T/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),B("%;U.) &;\\.# &;X/& 8!:! )"),B('%$%;V/2#2J""6J7K/#$+")("\'#&\'#0<*%;V/2#2J""6J7K/#$+")("\'#&\'#&/D#;W/;$2J""6J7K." &"/\'$8#:# )(#\'#("\'#&\'#'),B('$4""5!7/,#0)*4""5!7&&&#'),B('%4$""5!7%/?#$4""5!70)*4""5!7&/#$+")("\'#&\'#'),B('%2l""6l7m/?#;Y/6$2n""6n7o/\'$8#:# )(#\'#("\'#&\'#'),B('%%;Z/³#28""6879/¤$;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+-)(-\'#(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ސ &%2""67/¤#;Z/$28""6879/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+,)(,\'#(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.۹ &%2""67/#;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ٺ &%2""67/t#;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ؓ &%2""67/\\#;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+&)(&\'#(%\'#($\'#(#\'#("\'#&\'#.ׄ &%2""67/D#;Z/;$28""6879/,$;[/#$+$)($\'#(#\'#("\'#&\'#.֍ &%2""67/,#;[/#$+")("\'#&\'#.ծ &%2""67/,#;Z/#$+")("\'#&\'#.Տ &%;Z/#2""67/$;Z/$28""6879/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$++)(+\'#(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ӈ &%;Z/ª#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$2""67/t$;Z/k$28""6879/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+*)(*\'#()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.а &%;Z/¹#%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/k$2""67/\\$;Z/S$28""6879/D$;Z/;$28""6879/,$;[/#$+))()\'#((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ί &%;Z/È#%28""6879/,#;Z/#$+")("\'#&\'#." &"/¡$%28""6879/,#;Z/#$+")("\'#&\'#." &"/z$%28""6879/,#;Z/#$+")("\'#&\'#." &"/S$2""67/D$;Z/;$28""6879/,$;[/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.˕ &%;Z/×#%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;[/#$+\')(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.ȑ &%;Z/þ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/×$%28""6879/,#;Z/#$+")("\'#&\'#." &"/°$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/b$%28""6879/,#;Z/#$+")("\'#&\'#." &"/;$2""67/,$;Z/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#.Ħ &%;Z/Ĝ#%28""6879/,#;Z/#$+")("\'#&\'#." &"/õ$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Î$%28""6879/,#;Z/#$+")("\'#&\'#." &"/§$%28""6879/,#;Z/#$+")("\'#&\'#." &"/$%28""6879/,#;Z/#$+")("\'#&\'#." &"/Y$%28""6879/,#;Z/#$+")("\'#&\'#." &"/2$2""67/#$+()((\'#(\'\'#(&\'#(%\'#($\'#(#\'#("\'#&\'#/& 8!: ! )'),B('%;#/M#;#." &"/?$;#." &"/1$;#." &"/#$+$)($\'#(#\'#("\'#&\'#'),B("%;Z/;#28\"\"6879/,$;Z/#$+#)(#'#(\"'#&'#.# &;\\"),B("%;]/o#2J\"\"6J7K/`$;]/W$2J\"\"6J7K/H$;]/?$2J\"\"6J7K/0$;]/'$8':¡' )(''#(&'#(%'#($'#(#'#(\"'#&'#"),B('%2¢""6¢7£/2#4¤""5!7¥/#$+")("\'#&\'#. &%2¦""6¦7§/;#4¨""5!7©/,$;!/#$+#)(#\'#("\'#&\'#.j &%2ª""6ª7«/5#;!/,$;!/#$+#)(#\'#("\'#&\'#.B &%4¬""5!7/,#;!/#$+")("\'#&\'#.# &;!'),B('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:®!! )'),B('$%22""6273/,#;`/#$+")("\'#&\'#0<*%22""6273/,#;`/#$+")("\'#&\'#&'),B(";a.A &;b.; &;c.5 &;d./ &;e.) &;f.# &;g"),B('%3¯""5*7°/a#3±""5#7².G &3³""5#7´.; &3µ""5$7¶./ &3·""5#7¸.# &;6/($8":¹"! )("\'#&\'#'),B('%3º""5%7»/I#3¼""5%7½./ &3¾""5"7¿.# &;6/($8":À"! )("\'#&\'#'),B('%3Á""5\'7Â/1#;/($8":Ã"! )("\'#&\'#'),B('%3Ä""5$7Å/1#;ð/($8":Æ"! )("\'#&\'#'),B('%3Ç""5&7È/1#;T/($8":É"! )("\'#&\'#'),B('%3Ê""5"7Ë/N#%2>""6>7?/,#;6/#$+")("\'#&\'#." &"/\'$8":Ì" )("\'#&\'#'),B('%;h/P#%2>""6>7?/,#;i/#$+")("\'#&\'#." &"/)$8":Í""! )("\'#&\'#'),B('%$;j/�#*;j&&&#/"!&,)'),B('%$;j/�#*;j&&&#/"!&,)'),B(";k.) &;+.# &;-"),B('2l""6l7m.e &2n""6n7o.Y &24""6475.M &28""6879.A &2<""6<7=.5 &2@""6@7A.) &2B""6B7C'),B('%26""6677/n#;m/e$$%2<""6<7=/,#;m/#$+")("\'#&\'#0<*%2<""6<7=/,#;m/#$+")("\'#&\'#&/#$+#)(#\'#("\'#&\'#'),B('%;n/A#2>""6>7?/2$;o/)$8#:Î#"" )(#\'#("\'#&\'#'),B("$;p.) &;+.# &;-/2#0/*;p.) &;+.# &;-&&&#"),B("$;p.) &;+.# &;-0/*;p.) &;+.# &;-&"),B('2l""6l7m.e &2n""6n7o.Y &24""6475.M &26""6677.A &28""6879.5 &2@""6@7A.) &2B""6B7C'),B(";.# &;r"),B("%;/G#;'/>$;s/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),B(";M.# &;t"),B("%;/E#28\"\"6879/6$;u.# &;x/'$8#:Ï# )(#'#(\"'#&'#"),B('%;v.# &;w/J#%26""6677/,#;/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),B('%2Ð""6Ð7Ñ/:#;/1$;w." &"/#$+#)(#\'#("\'#&\'#'),B('%24""6475/,#;{/#$+")("\'#&\'#'),B("%;z/3#$;y0#*;y&/#$+\")(\"'#&'#"),B(";*.) &;+.# &;-"),B(';+. &;-. &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'),B('%;|/e#$%24""6475/,#;|/#$+")("\'#&\'#0<*%24""6475/,#;|/#$+")("\'#&\'#&/#$+")("\'#&\'#'),B('%$;~0#*;~&/e#$%22""6273/,#;}/#$+")("\'#&\'#0<*%22""6273/,#;}/#$+")("\'#&\'#&/#$+")("\'#&\'#'),B("$;~0#*;~&"),B(';+.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'),B('%%;"/#$;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K0M*;".G &;!.A &2@""6@7A.5 &2F""6F7G.) &2J""6J7K&/#$+")("\'#&\'#/& 8!:Ò! )'),B(";.# &;"),B('%%;O/2#2:""6:7;/#$+")("\'#&\'#." &"/,#;S/#$+")("\'#&\'#." &"'),B('$;+. &;-.} &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&&&#'),B("$;y0#*;y&"),B('%3""5#7Ó/q#24""6475/b$$;!/�#*;!&&&#/L$2J""6J7K/=$$;!/�#*;!&&&#/\'$8%:Ô% )(%\'#($\'#(#\'#("\'#&\'#'),B('2Õ""6Õ7Ö'),B('2×""6×7Ø'),B('2Ù""6Ù7Ú'),B('2Û""6Û7Ü'),B('2Ý""6Ý7Þ'),B('2ß""6ß7à'),B('2á""6á7â'),B('2ã""6ã7ä'),B('2å""6å7æ'),B('2ç""6ç7è'),B('2é""6é7ê'),B("%;
.Y &;.S &;.M &;.G &;.A &;.; &;.5 &;./ &;.) &;.# &;6/& 8!:ë! )"),B("%;/G#;'/>$;/5$;'/,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),B("%;/' 8!:ì!! )"),B("%;!/5#;!/,$;!/#$+#)(#'#(\"'#&'#"),B("%$;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(0G*;*.A &;+.; &;-.5 &;3./ &;4.) &;'.# &;(&/& 8!:í! )"),B("%;¶/Y#$%;A/,#;¶/#$+\")(\"'#&'#06*%;A/,#;¶/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B('%;9/N#%2:""6:7;/,#;9/#$+")("\'#&\'#." &"/\'$8":î" )("\'#&\'#'),B("%;:.c &%;/Y#$%;A/,#;/#$+\")(\"'#&'#06*%;A/,#;/#$+\")(\"'#&'#&/#$+\")(\"'#&'#/& 8!:ï! )"),B("%;L.# &;/]#$%;B/,#;/#$+\")(\"'#&'#06*%;B/,#;/#$+\")(\"'#&'#&/'$8\":ð\" )(\"'#&'#"),B("%;.\" &\"/>#;@/5$;M/,$;?/#$+$)($'#(#'#(\"'#&'#"),B("%%;6/Y#$%;./,#;6/#$+\")(\"'#&'#06*%;./,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#.# &;H/' 8!:ñ!! )"),B(";.) &;.# &; "),B("%3ò\"\"5!7ó/:#;</1$;/($8#:ô#! )(#'#(\"'#&'#"),B("%3õ\"\"5'7ö/:#;</1$;/($8#:÷#! )(#'#(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:ø!! )"),B('%2ù""6ù7ú/o#%2J""6J7K/M#;!." &"/?$;!." &"/1$;!." &"/#$+$)($\'#(#\'#("\'#&\'#." &"/\'$8":û" )("\'#&\'#'),B('%;6/J#%;</,#;¡/#$+")("\'#&\'#." &"/)$8":ü""! )("\'#&\'#'),B(";6.) &;T.# &;H"),B("%;£/Y#$%;B/,#;¤/#$+\")(\"'#&'#06*%;B/,#;¤/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B('%3ý""5&7þ.G &3ÿ""5\'7Ā.; &3ā""5$7Ă./ &3ă""5%7Ą.# &;6/& 8!:ą! )'),B(";¥.# &; "),B('%3Ć""5(7ć/M#;</D$3Ĉ""5(7ĉ./ &3Ċ""5(7ċ.# &;6/#$+#)(#\'#("\'#&\'#'),B("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:Č!! )"),B("%;©/& 8!:č! )"),B("%;ª/k#;;/b$;¯/Y$$%;B/,#;°/#$+\")(\"'#&'#06*%;B/,#;°/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),B(";«.# &;¬"),B('3Ď""5$7ď.S &3Đ""5%7đ.G &3Ē""5%7ē.; &3Ĕ""5%7ĕ./ &3Ė""5+7ė.# &;'),B('3Ę""5\'7ę./ &3Ě""5)7ě.# &;'),B(";6.# &;®"),B('%3Ĝ""5"7ĝ/,#;6/#$+")("\'#&\'#'),B(";.# &;6"),B("%;6/5#;</,$;±/#$+#)(#'#(\"'#&'#"),B(";6.# &;H"),B("%;³/5#;./,$;/#$+#)(#'#(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:Ğ!! )"),B("%;/' 8!:ğ!! )"),B('%;¶/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ġ"!!)("\'#&\'#'),B('%%;7/e#$%2J""6J7K/,#;7/#$+")("\'#&\'#0<*%2J""6J7K/,#;7/#$+")("\'#&\'#&/#$+")("\'#&\'#/"!&,)'),B("%;L.# &;/]#$%;B/,#;¸/#$+\")(\"'#&'#06*%;B/,#;¸/#$+\")(\"'#&'#&/'$8\":ġ\" )(\"'#&'#"),B(";¹.# &; "),B("%3Ģ\"\"5#7ģ/:#;</1$;6/($8#:Ĥ#! )(#'#(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:ĥ!! )"),B("%;/' 8!:Ħ!! )"),B("%$;0#*;&/x#;@/o$;M/f$;?/]$$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8%:ħ% )(%'#($'#(#'#(\"'#&'#"),B(";¾"),B("%3Ĩ\"\"5&7ĩ/k#;./b$;Á/Y$$%;A/,#;Á/#$+\")(\"'#&'#06*%;A/,#;Á/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#.# &;¿"),B("%;6/k#;./b$;À/Y$$%;A/,#;À/#$+\")(\"'#&'#06*%;A/,#;À/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),B("%;6/;#;</2$;6.# &;H/#$+#)(#'#(\"'#&'#"),B(";Â.G &;Ä.A &;Æ.; &;È.5 &;É./ &;Ê.) &;Ë.# &;À"),B("%3Ī\"\"5%7ī/5#;</,$;Ã/#$+#)(#'#(\"'#&'#"),B("%;I/' 8!:Ĭ!! )"),B("%3ĭ\"\"5&7Į/#;</$;D/
$;Å/|$$%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#0C*%$;'/�#*;'&&&#/,#;Å/#$+\")(\"'#&'#&/,$;E/#$+&)(&'#(%'#($'#(#'#(\"'#&'#"),B(";t.# &;w"),B("%3į\"\"5%7İ/5#;</,$;Ç/#$+#)(#'#(\"'#&'#"),B("%;I/' 8!:ı!! )"),B("%3IJ\"\"5&7ij/:#;</1$;I/($8#:Ĵ#! )(#'#(\"'#&'#"),B('%3ĵ""5%7Ķ/]#;</T$%3ķ""5$7ĸ/& 8!:Ĺ! ).4 &%3ĺ""5%7Ļ/& 8!:ļ! )/#$+#)(#\'#("\'#&\'#'),B('%3Ľ""5)7ľ/R#;</I$3Ŀ""5#7ŀ./ &3Ł""5(7ł.# &;6/($8#:Ń#! )(#\'#("\'#&\'#'),B('%3ń""5#7Ņ/#;</$;D/$%;Ì/e#$%2D""6D7E/,#;Ì/#$+")("\'#&\'#0<*%2D""6D7E/,#;Ì/#$+")("\'#&\'#&/#$+")("\'#&\'#/,$;E/#$+%)(%\'#($\'#(#\'#("\'#&\'#'),B('%3ņ""5(7Ň./ &3ň""5$7ʼn.# &;6/\' 8!:Ŋ!! )'),B("%;6/Y#$%;A/,#;6/#$+\")(\"'#&'#06*%;A/,#;6/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%;Ï/G#;./>$;Ï/5$;./,$;/#$+%)(%'#($'#(#'#(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:ŋ!! )"),B("%;Ñ/]#$%;A/,#;Ñ/#$+\")(\"'#&'#06*%;A/,#;Ñ/#$+\")(\"'#&'#&/'$8\":Ō\" )(\"'#&'#"),B("%;/]#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/'$8\":ō\" )(\"'#&'#"),B('%;L.O &;.I &%;@." &"/:#;t/1$;?." &"/#$+#)(#\'#("\'#&\'#/]#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/\'$8":Ŏ" )("\'#&\'#'),B("%;Ô/]#$%;B/,#;Õ/#$+\")(\"'#&'#06*%;B/,#;Õ/#$+\")(\"'#&'#&/'$8\":ŏ\" )(\"'#&'#"),B("%;/& 8!:Ő! )"),B('%3ő""5(7Œ/:#;</1$;6/($8#:œ#! )(#\'#("\'#&\'#.g &%3Ŕ""5&7ŕ/:#;</1$;6/($8#:Ŗ#! )(#\'#("\'#&\'#.: &%3ŗ""5*7Ř/& 8!:ř! ).# &; '),B('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:Ŝ!! )'),B("%;Ø/Y#$%;A/,#;Ø/#$+\")(\"'#&'#06*%;A/,#;Ø/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%;/Y#$%;B/,#; /#$+\")(\"'#&'#06*%;B/,#; /#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%$;!/�#*;!&&&#/' 8!:ŝ!! )"),B("%;Û/Y#$%;B/,#;Ü/#$+\")(\"'#&'#06*%;B/,#;Ü/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B('%3Ş""5&7ş.; &3Š""5\'7š./ &3Ţ""5*7ţ.# &;6/& 8!:Ť! )'),B("%3ť\"\"5&7Ŧ/:#;</1$;Ý/($8#:ŧ#! )(#'#(\"'#&'#.} &%3õ\"\"5'7ö/:#;</1$;/($8#:Ũ#! )(#'#(\"'#&'#.P &%3ũ\"\"5+7Ū/:#;</1$;/($8#:ū#! )(#'#(\"'#&'#.# &; "),B('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'),B(';1." &"'),B('%%;6/k#$%;A/2#;6/)$8":Ś""$ )("\'#&\'#0<*%;A/2#;6/)$8":Ś""$ )("\'#&\'#&/)$8":ś""! )("\'#&\'#." &"/\' 8!:ź!! )'),B("%;L.# &;/]#$%;B/,#;á/#$+\")(\"'#&'#06*%;B/,#;á/#$+\")(\"'#&'#&/'$8\":Ż\" )(\"'#&'#"),B(";¹.# &; "),B("%;ã/Y#$%;A/,#;ã/#$+\")(\"'#&'#06*%;A/,#;ã/#$+\")(\"'#&'#&/#$+\")(\"'#&'#"),B("%;ê/k#;./b$;í/Y$$%;B/,#;ä/#$+\")(\"'#&'#06*%;B/,#;ä/#$+\")(\"'#&'#&/#$+$)($'#(#'#(\"'#&'#"),B(";å.; &;æ.5 &;ç./ &;è.) &;é.# &; "),B("%3ż\"\"5#7Ž/:#;</1$;ð/($8#:ž#! )(#'#(\"'#&'#"),B("%3ſ\"\"5%7ƀ/:#;</1$;T/($8#:Ɓ#! )(#'#(\"'#&'#"),B("%3Ƃ\"\"5(7ƃ/F#;</=$;\\.) &;Y.# &;X/($8#:Ƅ#! )(#'#(\"'#&'#"),B("%3ƅ\"\"5&7Ɔ/:#;</1$;6/($8#:Ƈ#! )(#'#(\"'#&'#"),B("%3ƈ\"\"5%7Ɖ/A#;</8$$;!0#*;!&/($8#:Ɗ#! )(#'#(\"'#&'#"),B("%;ë/G#;;/>$;6/5$;;/,$;ì/#$+%)(%'#($'#(#'#(\"'#&'#"),B('%3""5#7Ó.# &;6/\' 8!:Ƌ!! )'),B('%3±""5#7ƌ.G &3³""5#7ƍ.; &3·""5#7Ǝ./ &3µ""5$7Ə.# &;6/\' 8!:Ɛ!! )'),B('%;î/D#%;C/,#;ï/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),B("%;U.) &;\\.# &;X/& 8!:Ƒ! )"),B('%%;!." &"/[#;!." &"/M$;!." &"/?$;!." &"/1$;!." &"/#$+%)(%\'#($\'#(#\'#("\'#&\'#/\' 8!:ƒ!! )'),B('%%;!/?#;!." &"/1$;!." &"/#$+#)(#\'#("\'#&\'#/\' 8!:Ɠ!! )'),B(";¾"),B('%;/^#$%;B/,#;ó/#$+")("\'#&\'#06*%;B/,#;ó/#$+")("\'#&\'#&/($8":Ɣ"!!)("\'#&\'#'),B(";ô.# &; "),B('%2ƕ""6ƕ7Ɩ/L#;</C$2Ɨ""6Ɨ7Ƙ.) &2ƙ""6ƙ7ƚ/($8#:ƛ#! )(#\'#("\'#&\'#'),B('%;/^#$%;B/,#; /#$+")("\'#&\'#06*%;B/,#; /#$+")("\'#&\'#&/($8":Ɯ"!!)("\'#&\'#'),B("%;6/5#;0/,$;÷/#$+#)(#'#(\"'#&'#"),B("$;2.) &;4.# &;.0/*;2.) &;4.# &;.&"),B("$;%0#*;%&"),B("%;ú/;#28\"\"6879/,$;û/#$+#)(#'#(\"'#&'#"),B('%3Ɲ""5%7ƞ.) &3Ɵ""5$7Ơ/\' 8!:ơ!! )'),B('%;ü/J#%28""6879/,#;^/#$+")("\'#&\'#." &"/#$+")("\'#&\'#'),B("%;\\.) &;X.# &;/' 8!:Ƣ!! )"),B(';".S &;!.M &2F""6F7G.A &2J""6J7K.5 &2H""6H7I.) &2N""6N7O'),B('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?'),B('%;Ā/b#28""6879/S$;û/J$%2ƣ""6ƣ7Ƥ/,#;ì/#$+")("\'#&\'#." &"/#$+$)($\'#(#\'#("\'#&\'#'),B('%3ƥ""5%7Ʀ.) &3Ƨ""5$7ƨ/\' 8!:ơ!! )'),B('%3±""5#7².6 &3³""5#7´.* &$;+0#*;+&/\' 8!:Ʃ!! )'),B("%;Ą/#2F\"\"6F7G/x$;ă/o$2F\"\"6F7G/`$;ă/W$2F\"\"6F7G/H$;ă/?$2F\"\"6F7G/0$;ą/'$8):ƪ) )()'#(('#(''#(&'#(%'#($'#(#'#(\"'#&'#"),B("%;#/>#;#/5$;#/,$;#/#$+$)($'#(#'#(\"'#&'#"),B("%;ă/,#;ă/#$+\")(\"'#&'#"),B("%;ă/5#;ă/,$;ă/#$+#)(#'#(\"'#&'#"),B("%;q/T#$;m0#*;m&/D$%; /,#;ø/#$+\")(\"'#&'#.\" &\"/#$+#)(#'#(\"'#&'#"),B('%2ƫ""6ƫ7Ƭ.) &2ƭ""6ƭ7Ʈ/w#;0/n$;Ĉ/e$$%;B/2#;ĉ.# &; /#$+")("\'#&\'#0<*%;B/2#;ĉ.# &; /#$+")("\'#&\'#&/#$+$)($\'#(#\'#("\'#&\'#'),B(";.# &;L"),B("%2Ư\"\"6Ư7ư/5#;</,$;Ċ/#$+#)(#'#(\"'#&'#"),B("%;D/S#;,/J$2:\"\"6:7;/;$;,.# &;T/,$;E/#$+%)(%'#($'#(#'#(\"'#&'#")];let a=0,V=0;const c=[{line:1,column:1}];let l,h=0,g=[],p=0;if(void 0!==e.startRule){if(!(e.startRule in i))throw new Error("Can't start parsing from rule \""+e.startRule+'".');n=i[e.startRule]}function u(){return A.substring(V,a)}function E(){return w(V,a)}function C(A,e){return{type:"literal",text:A,ignoreCase:e}}function I(A,e,t){return{type:"class",parts:A,inverted:e,ignoreCase:t}}function M(e){let t,s=c[e];if(s)return s;for(t=e-1;!c[t];)t--;for(s=c[t],s={line:s.line,column:s.column};t<e;)10===A.charCodeAt(t)?(s.line++,s.column=1):s.column++,t++;return c[e]=s,s}function w(A,e){const t=M(A),i=M(e);return{source:s,start:{offset:A,line:t.line,column:t.column},end:{offset:e,line:i.line,column:i.column}}}function f(A){a<h||(a>h&&(h=a,g=[]),g.push(A))}function B(A){return A.split("").map(A=>A.charCodeAt(0)-32)}if(e.data={},l=function e(s){const i=r[s];let n=0;const c=[];let l=i.length;const h=[],g=[];let q;for(;;){for(;n<l;)switch(i[n]){case 0:g.push(o[i[n+1]]),n+=2;break;case 1:g.push(void 0),n++;break;case 2:g.push(null),n++;break;case 3:g.push(t),n++;break;case 4:g.push([]),n++;break;case 5:g.push(a),n++;break;case 6:g.pop(),n++;break;case 7:a=g.pop(),n++;break;case 8:g.length-=i[n+1],n+=2;break;case 9:g.splice(-2,1),n++;break;case 10:g[g.length-2].push(g.pop()),n++;break;case 11:g.push(g.splice(g.length-i[n+1],i[n+1])),n+=2;break;case 12:g.push(A.substring(g.pop(),a)),n++;break;case 13:h.push(l),c.push(n+3+i[n+1]+i[n+2]),g[g.length-1]?(l=n+3+i[n+1],n+=3):(l=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 14:h.push(l),c.push(n+3+i[n+1]+i[n+2]),g[g.length-1]===t?(l=n+3+i[n+1],n+=3):(l=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 15:h.push(l),c.push(n+3+i[n+1]+i[n+2]),g[g.length-1]!==t?(l=n+3+i[n+1],n+=3):(l=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 16:g[g.length-1]!==t?(h.push(l),c.push(n),l=n+2+i[n+1],n+=2):n+=2+i[n+1];break;case 17:h.push(l),c.push(n+3+i[n+1]+i[n+2]),A.length>a?(l=n+3+i[n+1],n+=3):(l=n+3+i[n+1]+i[n+2],n+=3+i[n+1]);break;case 18:h.push(l),c.push(n+4+i[n+2]+i[n+3]),A.substr(a,o[i[n+1]].length)===o[i[n+1]]?(l=n+4+i[n+2],n+=4):(l=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 19:h.push(l),c.push(n+4+i[n+2]+i[n+3]),A.substr(a,o[i[n+1]].length).toLowerCase()===o[i[n+1]]?(l=n+4+i[n+2],n+=4):(l=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 20:h.push(l),c.push(n+4+i[n+2]+i[n+3]),o[i[n+1]].test(A.charAt(a))?(l=n+4+i[n+2],n+=4):(l=n+4+i[n+2]+i[n+3],n+=4+i[n+2]);break;case 21:g.push(A.substr(a,i[n+1])),a+=i[n+1],n+=2;break;case 22:g.push(o[i[n+1]]),a+=o[i[n+1]].length,n+=2;break;case 23:g.push(t),0===p&&f(o[i[n+1]]),n+=2;break;case 24:V=g[g.length-1-i[n+1]],n+=2;break;case 25:V=a,n++;break;case 26:q=i.slice(n+4,n+4+i[n+3]).map(function(A){return g[g.length-1-A]}),g.splice(g.length-i[n+2],i[n+2],o[i[n+1]].apply(null,q)),n+=4+i[n+3];break;case 27:g.push(e(i[n+1])),n+=2;break;case 28:p++,n++;break;case 29:p--,n++;break;default:throw new Error("Invalid opcode: "+i[n]+".")}if(!(h.length>0))break;l=h.pop(),n=c.pop()}return g[0]}(n),l!==t&&a===A.length)return l;throw l!==t&&a<A.length&&f({type:"end"}),S=g,Q=h<A.length?A.charAt(h):null,T=h<A.length?w(h,h+1):w(h,h),new m(m.buildMessage(S,Q),S,Q,T);var S,Q,T};var C;!function(A){A.parse=function(A,e){const t={startRule:e};try{E(A,t)}catch(A){t.data=-1}return t.data},A.nameAddrHeaderParse=function(e){const t=A.parse(e,"Name_Addr_Header");return-1!==t?t:void 0},A.URIParse=function(e){const t=A.parse(e,"SIP_URI");return-1!==t?t:void 0}}(C=C||(C={}));const I={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 M(A,e=32){let t="";for(let s=0;s<A;s++){t+=Math.floor(Math.random()*e).toString(e)}return t}function w(A){return I[A]||""}function f(){return M(10)}function B(A){const e={"Call-Id":"Call-ID",Cseq:"CSeq","Min-Se":"Min-SE",Rack:"RAck",Rseq:"RSeq","Www-Authenticate":"WWW-Authenticate"},t=A.toLowerCase().replace(/_/g,"-").split("-"),s=t.length;let i="";for(let A=0;A<s;A++)0!==A&&(i+="-"),i+=t[A].charAt(0).toUpperCase()+t[A].substring(1);return e[i]&&(i=e[i]),i}function S(A){return encodeURIComponent(A).replace(/%[A-F\d]{2}/g,"U").length}class Q{constructor(){this.headers={}}addHeader(A,e){const t={raw:e};A=B(A),this.headers[A]?this.headers[A].push(t):this.headers[A]=[t]}getHeader(A){const e=this.headers[B(A)];if(e)return e[0]?e[0].raw:void 0}getHeaders(A){const e=this.headers[B(A)],t=[];if(!e)return[];for(const A of e)t.push(A.raw);return t}hasHeader(A){return!!this.headers[B(A)]}parseHeader(A,e=0){if(A=B(A),!this.headers[A])return;if(e>=this.headers[A].length)return;const t=this.headers[A][e],s=t.raw;if(t.parsed)return t.parsed;const i=C.parse(s,A.replace(/-/g,"_"));return-1===i?void this.headers[A].splice(e,1):(t.parsed=i,i)}s(A,e=0){return this.parseHeader(A,e)}setHeader(A,e){this.headers[B(A)]=[{raw:e}]}toString(){return this.data}}class T extends Q{constructor(){super()}}class y extends Q{constructor(){super()}}class D{constructor(A,e,t,s,i,n,o){this.headers={},this.extraHeaders=[],this.options=D.getDefaultOptions(),i&&(this.options=Object.assign(Object.assign({},this.options),i),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=A,this.ruri=e.clone(),this.fromURI=t.clone(),this.fromTag=this.options.fromTag?this.options.fromTag:f(),this.from=D.makeNameAddrHeader(this.fromURI,this.options.fromDisplayName,this.fromTag),this.toURI=s.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+M(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(A,e,t){const s={};return t&&(s.tag=t),new q(A,e,s)}getHeader(A){const e=this.headers[B(A)];if(e){if(e[0])return e[0]}else{const e=new RegExp("^\\s*"+A+"\\s*:","i");for(const A of this.extraHeaders)if(e.test(A))return A.substring(A.indexOf(":")+1).trim()}}getHeaders(A){const e=[],t=this.headers[B(A)];if(t)for(const A of t)e.push(A);else{const t=new RegExp("^\\s*"+A+"\\s*:","i");for(const A of this.extraHeaders)t.test(A)&&e.push(A.substring(A.indexOf(":")+1).trim())}return e}hasHeader(A){if(this.headers[B(A)])return!0;{const e=new RegExp("^\\s*"+A+"\\s*:","i");for(const A of this.extraHeaders)if(e.test(A))return!0}return!1}setHeader(A,e){this.headers[B(A)]=e instanceof Array?e:[e]}setViaHeader(A,e){this.options.hackViaTcp&&(e="TCP");let t="SIP/2.0/"+e;t+=" "+this.options.viaHost+";branch="+A,this.options.forceRport&&(t+=";rport"),this.setHeader("via",t),this.branch=A}toString(){let A="";A+=this.method+" "+this.ruri.toRaw()+" SIP/2.0\r\n";for(const e in this.headers)if(this.headers[e])for(const t of this.headers[e])A+=e+": "+t+"\r\n";for(const e of this.extraHeaders)A+=e.trim()+"\r\n";return A+="Supported: "+this.options.optionTags.join(", ")+"\r\n",A+="User-Agent: "+this.options.userAgentString+"\r\n",this.body?"string"==typeof this.body?(A+="Content-Length: "+S(this.body)+"\r\n\r\n",A+=this.body):this.body.body&&this.body.contentType?(A+="Content-Type: "+this.body.contentType+"\r\n",A+="Content-Length: "+S(this.body.body)+"\r\n\r\n",A+=this.body.body):A+="Content-Length: 0\r\n\r\n":A+="Content-Length: 0\r\n\r\n",A}}function R(A){return"application/sdp"===A?"session":"render"}function U(A){const e="string"==typeof A?A:A.body,t="string"==typeof A?"application/sdp":A.contentType;return{contentDisposition:R(t),contentType:t,content:e}}function k(A){return!(!A||"string"!=typeof A.content||"string"!=typeof A.contentType||void 0!==A.contentDisposition)||"string"==typeof A.contentDisposition}function G(A){let e,t,s;if(A instanceof T&&A.body){const i=A.parseHeader("Content-Disposition");e=i?i.type:void 0,t=A.parseHeader("Content-Type"),s=A.body}if(A instanceof y&&A.body){const i=A.parseHeader("Content-Disposition");e=i?i.type:void 0,t=A.parseHeader("Content-Type"),s=A.body}if(A instanceof D&&A.body)if(e=A.getHeader("Content-Disposition"),t=A.getHeader("Content-Type"),"string"==typeof A.body){if(!t)throw new Error("Header content type header does not equal body content type.");s=A.body}else{if(t&&t!==A.body.contentType)throw new Error("Header content type header does not equal body content type.");t=A.body.contentType,s=A.body.body}if(k(A)&&(e=A.contentDisposition,t=A.contentType,s=A.content),s){if(t&&!e&&(e=R(t)),!e)throw new Error("Content disposition undefined.");if(!t)throw new Error("Content type undefined.");return{contentDisposition:e,contentType:t,content:s}}}var F,Y;!function(A){A.Initial="Initial",A.Early="Early",A.AckWait="AckWait",A.Confirmed="Confirmed",A.Terminated="Terminated"}(F=F||(F={})),function(A){A.Initial="Initial",A.HaveLocalOffer="HaveLocalOffer",A.HaveRemoteOffer="HaveRemoteOffer",A.Stable="Stable",A.Closed="Closed"}(Y=Y||(Y={}));const x=500,v=5e3,Z={T1:x,T2:4e3,T4:v,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 O extends t{constructor(A){super(A||"Transaction state error.")}}var N;!function(A){A.ACK="ACK",A.BYE="BYE",A.CANCEL="CANCEL",A.INFO="INFO",A.INVITE="INVITE",A.MESSAGE="MESSAGE",A.NOTIFY="NOTIFY",A.OPTIONS="OPTIONS",A.REGISTER="REGISTER",A.UPDATE="UPDATE",A.SUBSCRIBE="SUBSCRIBE",A.PUBLISH="PUBLISH",A.REFER="REFER",A.PRACK="PRACK"}(N=N||(N={}));const K=[N.ACK,N.BYE,N.CANCEL,N.INFO,N.INVITE,N.MESSAGE,N.NOTIFY,N.OPTIONS,N.PRACK,N.REFER,N.REGISTER,N.SUBSCRIBE];class b{constructor(A){this.incomingMessageRequest=A}get request(){return this.incomingMessageRequest.message}accept(A){return this.incomingMessageRequest.accept(A),Promise.resolve()}reject(A){return this.incomingMessageRequest.reject(A),Promise.resolve()}}let J=class{constructor(A){this.incomingNotifyRequest=A}get request(){return this.incomingNotifyRequest.message}accept(A){return this.incomingNotifyRequest.accept(A),Promise.resolve()}reject(A){return this.incomingNotifyRequest.reject(A),Promise.resolve()}};class L{constructor(A,e){this.incomingReferRequest=A,this.session=e}get referTo(){const A=this.incomingReferRequest.message.parseHeader("refer-to");if(!(A instanceof q))throw new Error("Failed to parse Refer-To header.");return A}get referredBy(){return this.incomingReferRequest.message.getHeader("referred-by")}get replaces(){const A=this.referTo.uri.getHeader("replaces");return A instanceof Array?A[0]:A}get request(){return this.incomingReferRequest.message}accept(A={statusCode:202}){return this.incomingReferRequest.accept(A),Promise.resolve()}reject(A){return this.incomingReferRequest.reject(A),Promise.resolve()}makeInviter(A){if(this.inviter)return this.inviter;const e=this.referTo.uri.clone();e.clearHeaders();const t=((A=A||{}).extraHeaders||[]).slice(),s=this.replaces;s&&t.push("Replaces: "+decodeURIComponent(s));const i=this.referredBy;return i&&t.push("Referred-By: "+i),A.extraHeaders=t,this.inviter=this.session.userAgent._makeInviter(e,A),this.inviter._referred=this.session,this.session._referral=this.inviter,this.inviter}}var H,j;!function(A){A.Initial="Initial",A.Establishing="Establishing",A.Established="Established",A.Terminating="Terminating",A.Terminated="Terminated"}(H=H||(H={}));class W{constructor(A,e={}){this.pendingReinvite=!1,this.pendingReinviteAck=!1,this._state=H.Initial,this.delegate=e.delegate,this._stateEventEmitter=new l,this._userAgent=A}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 H.Initial:case H.Establishing:break;case H.Established:return new Promise(A=>{this._bye({onAccept:()=>A(),onRedirect:()=>A(),onReject:()=>A()})});case H.Terminating:case H.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(A){this._sessionDescriptionHandlerModifiers=A.slice()}get sessionDescriptionHandlerOptions(){return this._sessionDescriptionHandlerOptions||{}}set sessionDescriptionHandlerOptions(A){this._sessionDescriptionHandlerOptions=Object.assign({},A)}get sessionDescriptionHandlerModifiersReInvite(){return this._sessionDescriptionHandlerModifiersReInvite||[]}set sessionDescriptionHandlerModifiersReInvite(A){this._sessionDescriptionHandlerModifiersReInvite=A.slice()}get sessionDescriptionHandlerOptionsReInvite(){return this._sessionDescriptionHandlerOptionsReInvite||{}}set sessionDescriptionHandlerOptionsReInvite(A){this._sessionDescriptionHandlerOptionsReInvite=Object.assign({},A)}get state(){return this._state}get stateChange(){return this._stateEventEmitter}get userAgent(){return this._userAgent}bye(A={}){let e="Session.bye() may only be called if established session.";switch(this.state){case H.Initial:"function"==typeof this.cancel?(e+=" However Inviter.invite() has not yet been called.",e+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(e+=" However Invitation.accept() has not yet been called.",e+=" Perhaps you should have called Invitation.reject()?");break;case H.Establishing:"function"==typeof this.cancel?(e+=" However a dialog does not yet exist.",e+=" Perhaps you should have called Inviter.cancel()?"):"function"==typeof this.reject&&(e+=" However Invitation.accept() has not yet been called (or not yet resolved).",e+=" Perhaps you should have called Invitation.reject()?");break;case H.Established:{const e=A.requestDelegate,t=this.copyRequestOptions(A.requestOptions);return this._bye(e,t)}case H.Terminating:e+=" However this session is already terminating.","function"==typeof this.cancel?e+=" Perhaps you have already called Inviter.cancel()?":"function"==typeof this.reject&&(e+=" Perhaps you have already called Session.bye()?");break;case H.Terminated:e+=" However this session is already terminated.";break;default:throw new Error("Unknown state")}return this.logger.error(e),Promise.reject(new Error(`Invalid session state ${this.state}`))}info(A={}){if(this.state!==H.Established){const A="Session.info() may only be called if established session.";return this.logger.error(A),Promise.reject(new Error(`Invalid session state ${this.state}`))}const e=A.requestDelegate,t=this.copyRequestOptions(A.requestOptions);return this._info(e,t)}invite(A={}){if(this.logger.log("Session.invite"),this.state!==H.Established)return Promise.reject(new Error(`Invalid session state ${this.state}`));if(this.pendingReinvite)return Promise.reject(new i("Reinvite in progress. Please wait until complete, then try again."));this.pendingReinvite=!0,A.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiersReInvite=A.sessionDescriptionHandlerModifiers),A.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptionsReInvite=A.sessionDescriptionHandlerOptions);const e={onAccept:e=>{const t=G(e.message);if(!t)return this.logger.error("Received 2xx response to re-INVITE without a session description"),this.ackAndBye(e,400,"Missing session description"),this.stateTransition(H.Terminated),void(this.pendingReinvite=!1);if(A.withoutSdp){const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setOfferAndGetAnswer(t,s).then(A=>{e.ack({body:A})}).catch(A=>{this.logger.error("Failed to handle offer in 2xx response to re-INVITE"),this.logger.error(A.message),this.state===H.Terminated?e.ack():(this.ackAndBye(e,488,"Bad Media Description"),this.stateTransition(H.Terminated))}).then(()=>{this.pendingReinvite=!1,A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e)})}else{const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.setAnswer(t,s).then(()=>{e.ack()}).catch(A=>{this.logger.error("Failed to handle answer in 2xx response to re-INVITE"),this.logger.error(A.message),this.state!==H.Terminated?(this.ackAndBye(e,488,"Bad Media Description"),this.stateTransition(H.Terminated)):e.ack()}).then(()=>{this.pendingReinvite=!1,A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e)})}},onProgress:A=>{},onRedirect:A=>{},onReject:e=>{this.logger.warn("Received a non-2xx response to re-INVITE"),this.pendingReinvite=!1,A.withoutSdp?A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e):this.rollbackOffer().catch(A=>{if(this.logger.error("Failed to rollback offer on non-2xx response to re-INVITE"),this.logger.error(A.message),this.state!==H.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const A=[];A.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated)}}).then(()=>{A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e)})},onTrying:A=>{}},t=A.requestOptions||{};if(t.extraHeaders=(t.extraHeaders||[]).slice(),t.extraHeaders.push("Allow: "+K.toString()),t.extraHeaders.push("Contact: "+this._contact),A.withoutSdp){if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return Promise.resolve(this.dialog.invite(e,t))}const s={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};return this.getOffer(s).then(A=>{if(!this.dialog)throw this.pendingReinvite=!1,new Error("Dialog undefined.");return t.body=A,this.dialog.invite(e,t)}).catch(A=>{throw this.logger.error(A.message),this.logger.error("Failed to send re-INVITE"),this.pendingReinvite=!1,A})}message(A={}){if(this.state!==H.Established){const A="Session.message() may only be called if established session.";return this.logger.error(A),Promise.reject(new Error(`Invalid session state ${this.state}`))}const e=A.requestDelegate,t=this.copyRequestOptions(A.requestOptions);return this._message(e,t)}refer(A,e={}){if(this.state!==H.Established){const A="Session.refer() may only be called if established session.";return this.logger.error(A),Promise.reject(new Error(`Invalid session state ${this.state}`))}if(A instanceof W&&!A.dialog){const A="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(A),Promise.reject(new Error(`Invalid session state ${this.state}`))}const t=e.requestDelegate,s=this.copyRequestOptions(e.requestOptions);return s.extraHeaders=s.extraHeaders?s.extraHeaders.concat(this.referExtraHeaders(this.referToString(A))):this.referExtraHeaders(this.referToString(A)),this._refer(e.onNotify,t,s)}_bye(A,e){if(!this.dialog)return Promise.reject(new Error("Session dialog undefined."));const t=this.dialog;switch(t.sessionState){case F.Initial:case F.Early:throw new Error(`Invalid dialog state ${t.sessionState}`);case F.AckWait:return this.stateTransition(H.Terminating),new Promise(s=>{t.delegate={onAck:()=>{const i=t.bye(A,e);return this.stateTransition(H.Terminated),s(i),Promise.resolve()},onAckTimeout:()=>{const i=t.bye(A,e);this.stateTransition(H.Terminated),s(i)}}});case F.Confirmed:{const s=t.bye(A,e);return this.stateTransition(H.Terminated),Promise.resolve(s)}case F.Terminated:throw new Error(`Invalid dialog state ${t.sessionState}`);default:throw new Error("Unrecognized state.")}}_info(A,e){return this.dialog?Promise.resolve(this.dialog.info(A,e)):Promise.reject(new Error("Session dialog undefined."))}_message(A,e){return this.dialog?Promise.resolve(this.dialog.message(A,e)):Promise.reject(new Error("Session dialog undefined."))}_refer(A,e,t){return this.dialog?(this.onNotify=A,Promise.resolve(this.dialog.refer(e,t))):Promise.reject(new Error("Session dialog undefined."))}ackAndBye(A,e,t){A.ack();const s=[];e&&s.push("Reason: "+this.getReasonHeaderValue(e,t)),A.session.bye(void 0,{extraHeaders:s})}onAckRequest(A){if(this.logger.log("Session.onAckRequest"),this.state!==H.Established&&this.state!==H.Terminating)return this.logger.error(`ACK received while in state ${this.state}, dropping request`),Promise.resolve();const e=this.dialog;if(!e)throw new Error("Dialog undefined.");const t={sessionDescriptionHandlerOptions:this.pendingReinviteAck?this.sessionDescriptionHandlerOptionsReInvite:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.pendingReinviteAck?this._sessionDescriptionHandlerModifiersReInvite:this._sessionDescriptionHandlerModifiers};if(this.delegate&&this.delegate.onAck){const e=new a(A);this.delegate.onAck(e)}switch(this.pendingReinviteAck=!1,e.signalingState){case Y.Initial:{this.logger.error(`Invalid signaling state ${e.signalingState}.`);const A=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return e.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated),Promise.resolve()}case Y.Stable:{const s=G(A.message);return s?"render"===s.contentDisposition?(this._renderbody=s.content,this._rendertype=s.contentType,Promise.resolve()):"session"!==s.contentDisposition?Promise.resolve():this.setAnswer(s,t).catch(A=>{this.logger.error(A.message);const t=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];e.bye(void 0,{extraHeaders:t}),this.stateTransition(H.Terminated)}):Promise.resolve()}case Y.HaveLocalOffer:{this.logger.error(`Invalid signaling state ${e.signalingState}.`);const A=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return e.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated),Promise.resolve()}case Y.HaveRemoteOffer:{this.logger.error(`Invalid signaling state ${e.signalingState}.`);const A=["Reason: "+this.getReasonHeaderValue(488,"Bad Media Description")];return e.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated),Promise.resolve()}case Y.Closed:default:throw new Error(`Invalid signaling state ${e.signalingState}.`)}}onByeRequest(A){if(this.logger.log("Session.onByeRequest"),this.state===H.Established){if(this.delegate&&this.delegate.onBye){const e=new V(A);this.delegate.onBye(e)}else A.accept();this.stateTransition(H.Terminated)}else this.logger.error(`BYE received while in state ${this.state}, dropping request`)}onInfoRequest(A){if(this.logger.log("Session.onInfoRequest"),this.state===H.Established)if(this.delegate&&this.delegate.onInfo){const e=new h(A);this.delegate.onInfo(e)}else A.accept();else this.logger.error(`INFO received while in state ${this.state}, dropping request`)}onInviteRequest(A){if(this.logger.log("Session.onInviteRequest"),this.state!==H.Established)return void this.logger.error(`INVITE received while in state ${this.state}, dropping request`);this.pendingReinviteAck=!0;const e=["Contact: "+this._contact];if(A.message.hasHeader("P-Asserted-Identity")){const e=A.message.getHeader("P-Asserted-Identity");if(!e)throw new Error("Header undefined.");this._assertedIdentity=C.nameAddrHeaderParse(e)}const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptionsReInvite,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiersReInvite};this.generateResponseOfferAnswerInDialog(t).then(t=>{const s=A.accept({statusCode:200,extraHeaders:e,body:t});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(A.message,s.message,200)}).catch(e=>{if(this.logger.error(e.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===Y.Stable){const e=A.reject({statusCode:488});return void(this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(A.message,e.message,488))}this.rollbackOffer().then(()=>{const e=A.reject({statusCode:488});this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(A.message,e.message,488)}).catch(e=>{this.logger.error(e.message),this.logger.error("Failed to rollback offer on re-INVITE request");const t=A.reject({statusCode:488});if(this.state!==H.Terminated){if(!this.dialog)throw new Error("Dialog undefined.");const A=[];A.push("Reason: "+this.getReasonHeaderValue(500,"Internal Server Error")),this.dialog.bye(void 0,{extraHeaders:A}),this.stateTransition(H.Terminated)}this.delegate&&this.delegate.onInvite&&this.delegate.onInvite(A.message,t.message,488)})})}onMessageRequest(A){if(this.logger.log("Session.onMessageRequest"),this.state===H.Established)if(this.delegate&&this.delegate.onMessage){const e=new b(A);this.delegate.onMessage(e)}else A.accept();else this.logger.error(`MESSAGE received while in state ${this.state}, dropping request`)}onNotifyRequest(A){if(this.logger.log("Session.onNotifyRequest"),this.state===H.Established){if(this.onNotify){const e=new J(A);return void this.onNotify(e)}if(this.delegate&&this.delegate.onNotify){const e=new J(A);this.delegate.onNotify(e)}else A.accept()}else this.logger.error(`NOTIFY received while in state ${this.state}, dropping request`)}onPrackRequest(A){if(this.logger.log("Session.onPrackRequest"),this.state===H.Established)throw new Error("Unimplemented.");this.logger.error(`PRACK received while in state ${this.state}, dropping request`)}onReferRequest(A){if(this.logger.log("Session.onReferRequest"),this.state!==H.Established)return void this.logger.error(`REFER received while in state ${this.state}, dropping request`);if(!A.message.hasHeader("refer-to"))return this.logger.warn("Invalid REFER packet. A refer-to header is required. Rejecting."),void A.reject();const e=new L(A,this);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(e):(this.logger.log("No delegate available to handle REFER, automatically accepting and following."),e.accept().then(()=>e.makeInviter(this._referralInviterOptions).invite()).catch(A=>{this.logger.error(A.message)}))}generateResponseOfferAnswer(A,e){if(this.dialog)return this.generateResponseOfferAnswerInDialog(e);const t=G(A.message);return t&&"session"===t.contentDisposition?this.setOfferAndGetAnswer(t,e):this.getOffer(e)}generateResponseOfferAnswerInDialog(A){if(!this.dialog)throw new Error("Dialog undefined.");switch(this.dialog.signalingState){case Y.Initial:return this.getOffer(A);case Y.HaveLocalOffer:return Promise.resolve(void 0);case Y.HaveRemoteOffer:if(!this.dialog.offer)throw new Error(`Session offer undefined in signaling state ${this.dialog.signalingState}.`);return this.setOfferAndGetAnswer(this.dialog.offer,A);case Y.Stable:return this.state!==H.Established?Promise.resolve(void 0):this.getOffer(A);case Y.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}getOffer(A){const e=this.setupSessionDescriptionHandler(),t=A.sessionDescriptionHandlerOptions,s=A.sessionDescriptionHandlerModifiers;try{return e.getDescription(t,s).then(A=>U(A)).catch(A=>{this.logger.error("Session.getOffer: SDH getDescription rejected...");const e=A instanceof Error?A:new Error("Session.getOffer unknown error.");throw this.logger.error(e.message),e})}catch(A){this.logger.error("Session.getOffer: SDH getDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}}rollbackOffer(){const A=this.setupSessionDescriptionHandler();if(void 0===A.rollbackDescription)return Promise.resolve();try{return A.rollbackDescription().catch(A=>{this.logger.error("Session.rollbackOffer: SDH rollbackDescription rejected...");const e=A instanceof Error?A:new Error("Session.rollbackOffer unknown error.");throw this.logger.error(e.message),e})}catch(A){this.logger.error("Session.rollbackOffer: SDH rollbackDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}}setAnswer(A,e){const t=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,n=e.sessionDescriptionHandlerModifiers;try{if(!t.hasDescription(A.contentType))return Promise.reject(new s)}catch(A){this.logger.error("Session.setAnswer: SDH hasDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}try{return t.setDescription(A.content,i,n).catch(A=>{this.logger.error("Session.setAnswer: SDH setDescription rejected...");const e=A instanceof Error?A:new Error("Session.setAnswer unknown error.");throw this.logger.error(e.message),e})}catch(A){this.logger.error("Session.setAnswer: SDH setDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}}setOfferAndGetAnswer(A,e){const t=this.setupSessionDescriptionHandler(),i=e.sessionDescriptionHandlerOptions,n=e.sessionDescriptionHandlerModifiers;try{if(!t.hasDescription(A.contentType))return Promise.reject(new s)}catch(A){this.logger.error("Session.setOfferAndGetAnswer: SDH hasDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}try{return t.setDescription(A.content,i,n).then(()=>t.getDescription(i,n)).then(A=>U(A)).catch(A=>{this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription rejected...");const e=A instanceof Error?A:new Error("Session.setOfferAndGetAnswer unknown error.");throw this.logger.error(e.message),e})}catch(A){this.logger.error("Session.setOfferAndGetAnswer: SDH setDescription or getDescription threw...");const e=A instanceof Error?A:new Error(A);return this.logger.error(e.message),Promise.reject(e)}}setSessionDescriptionHandler(A){if(this._sessionDescriptionHandler)throw new Error("Session description handler defined.");this._sessionDescriptionHandler=A}setupSessionDescriptionHandler(){var A;return this._sessionDescriptionHandler||(this._sessionDescriptionHandler=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions),(null===(A=this.delegate)||void 0===A?void 0:A.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(this._sessionDescriptionHandler,!1)),this._sessionDescriptionHandler}stateTransition(A){const e=()=>{throw new Error(`Invalid state transition from ${this._state} to ${A}`)};switch(this._state){case H.Initial:A!==H.Establishing&&A!==H.Established&&A!==H.Terminating&&A!==H.Terminated&&e();break;case H.Establishing:A!==H.Established&&A!==H.Terminating&&A!==H.Terminated&&e();break;case H.Established:A!==H.Terminating&&A!==H.Terminated&&e();break;case H.Terminating:A!==H.Terminated&&e();break;case H.Terminated:e();break;default:throw new Error("Unrecognized state.")}this._state=A,this.logger.log(`Session ${this.id} transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),A===H.Terminated&&this.dispose()}copyRequestOptions(A={}){return{extraHeaders:A.extraHeaders?A.extraHeaders.slice():void 0,body:A.body?{contentDisposition:A.body.contentDisposition||"render",contentType:A.body.contentType||"text/plain",content:A.body.content||""}:void 0}}getReasonHeaderValue(A,e){const t=A;let s=w(A);return!s&&e&&(s=e),"SIP;cause="+t+';text="'+s+'"'}referExtraHeaders(A){const e=[];return e.push("Referred-By: <"+this.userAgent.configuration.uri+">"),e.push("Contact: "+this._contact),e.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),e.push("Refer-To: "+A),e}referToString(A){let e;if(A instanceof d)e=A.toString();else{if(!A.dialog)throw new Error("Dialog undefined.");const t=A.remoteIdentity.friendlyName,s=A.dialog.remoteTarget.toString(),i=A.dialog.callId,n=A.dialog.remoteTag,o=A.dialog.localTag;e=`"${t}" <${s}?Replaces=${encodeURIComponent(`${i};to-tag=${n};from-tag=${o}`)}>`}return e}}!function(A){A.Required="Required",A.Supported="Supported",A.Unsupported="Unsupported"}(j=j||(j={}));const P={"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 W{constructor(A,e){super(A),this.incomingInviteRequest=e,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=A.getLogger("sip.Invitation");const t=this.incomingInviteRequest.message,s=t.getHeader("require");s&&s.toLowerCase().includes("100rel")&&(this.rel100="required");const i=t.getHeader("supported");if(i&&i.toLowerCase().includes("100rel")&&(this.rel100="supported"),t.toTag=e.toTag,"string"!=typeof t.toTag)throw new TypeError("toTag should have been a string.");if(this.userNoAnswerTimer=setTimeout(()=>{e.reject({statusCode:480}),this.stateTransition(H.Terminated)},this.userAgent.configuration.noAnswerTimeout?1e3*this.userAgent.configuration.noAnswerTimeout:6e4),t.hasHeader("expires")){const A=1e3*Number(t.getHeader("expires")||0);this.expiresTimer=setTimeout(()=>{this.state===H.Initial&&(e.reject({statusCode:487}),this.stateTransition(H.Terminated))},A)}const n=this.request.getHeader("P-Asserted-Identity");n&&(this._assertedIdentity=C.nameAddrHeaderParse(n)),this._contact=this.userAgent.contact.toString();const o=t.parseHeader("Content-Disposition");o&&"render"===o.type&&(this._renderbody=t.body,this._rendertype=t.getHeader("Content-Type")),this._id=t.callId+t.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 H.Initial:case H.Establishing:return this.reject().then(()=>super.dispose());case H.Established:case H.Terminating:case H.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(A={}){if(this.logger.log("Invitation.accept"),this.state!==H.Initial){const A=new Error(`Invalid session state ${this.state}`);return this.logger.error(A.message),Promise.reject(A)}return A.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=A.sessionDescriptionHandlerModifiers),A.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=A.sessionDescriptionHandlerOptions),this.stateTransition(H.Establishing),this.sendAccept(A).then(({message:A,session:e})=>{e.delegate={onAck:A=>this.onAckRequest(A),onAckTimeout:()=>this.onAckTimeout(),onBye:A=>this.onByeRequest(A),onInfo:A=>this.onInfoRequest(A),onInvite:A=>this.onInviteRequest(A),onMessage:A=>this.onMessageRequest(A),onNotify:A=>this.onNotifyRequest(A),onPrack:A=>this.onPrackRequest(A),onRefer:A=>this.onReferRequest(A)},this._dialog=e,this.stateTransition(H.Established),this._replacee&&this._replacee._bye()}).catch(A=>this.handleResponseError(A))}progress(A={}){if(this.logger.log("Invitation.progress"),this.state!==H.Initial){const A=new Error(`Invalid session state ${this.state}`);return this.logger.error(A.message),Promise.reject(A)}const e=A.statusCode||180;if(e<100||e>199)throw new TypeError("Invalid statusCode: "+e);return A.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=A.sessionDescriptionHandlerModifiers),A.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=A.sessionDescriptionHandlerOptions),this.waitingForPrack?(this.logger.warn("Unexpected call for progress while waiting for prack, ignoring"),Promise.resolve()):100===A.statusCode?this.sendProgressTrying().then(()=>{}).catch(A=>this.handleResponseError(A)):"required"===this.rel100||"supported"===this.rel100&&A.rel100||"supported"===this.rel100&&this.userAgent.configuration.sipExtension100rel===j.Required?this.sendProgressReliableWaitForPrack(A).then(()=>{}).catch(A=>this.handleResponseError(A)):this.sendProgress(A).then(()=>{}).catch(A=>this.handleResponseError(A))}reject(A={}){if(this.logger.log("Invitation.reject"),this.state!==H.Initial&&this.state!==H.Establishing){const A=new Error(`Invalid session state ${this.state}`);return this.logger.error(A.message),Promise.reject(A)}const e=A.statusCode||480,t=A.reasonPhrase?A.reasonPhrase:w(e),s=A.extraHeaders||[];if(e<300||e>699)throw new TypeError("Invalid statusCode: "+e);const i=A.body?U(A.body):void 0;return e<400?this.incomingInviteRequest.redirect([],{statusCode:e,reasonPhrase:t,extraHeaders:s,body:i}):this.incomingInviteRequest.reject({statusCode:e,reasonPhrase:t,extraHeaders:s,body:i}),this.stateTransition(H.Terminated),Promise.resolve()}_onCancel(A){if(this.logger.log("Invitation._onCancel"),this.state===H.Initial||this.state===H.Establishing){if(this.delegate&&this.delegate.onCancel){const e=new c(A);this.delegate.onCancel(e)}this.isCanceled=!0,this.incomingInviteRequest.reject({statusCode:487}),this.stateTransition(H.Terminated)}else this.logger.error(`CANCEL received while in state ${this.state}, dropping request`)}handlePrackOfferAnswer(A){if(!this.dialog)throw new Error("Dialog undefined.");const e=G(A.message);if(!e||"session"!==e.contentDisposition)return Promise.resolve(void 0);const t={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers};switch(this.dialog.signalingState){case Y.Initial:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Y.Stable:return this.setAnswer(e,t).then(()=>{});case Y.HaveLocalOffer:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`);case Y.HaveRemoteOffer:return this.setOfferAndGetAnswer(e,t);case Y.Closed:default:throw new Error(`Invalid signaling state ${this.dialog.signalingState}.`)}}handleResponseError(A){let e=480;if(A instanceof Error?this.logger.error(A.message):this.logger.error(A),A instanceof s?(this.logger.error("A session description handler occurred while sending response (content type unsupported"),e=415):A instanceof n?this.logger.error("A session description handler occurred while sending response"):A instanceof o?this.logger.error("Session ended before response could be formulated and sent (while waiting for PRACK)"):A instanceof O&&this.logger.error("Session changed state before response could be formulated and sent"),this.state===H.Initial||this.state===H.Establishing)try{this.incomingInviteRequest.reject({statusCode:e}),this.stateTransition(H.Terminated)}catch(A){throw this.logger.error("An error occurred attempting to reject the request while handling another error"),A}if(!this.isCanceled)throw A;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(H.Terminated)}sendAccept(A={}){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},t=A.extraHeaders||[];return this.waitingForPrack?this.waitForArrivalOfPrack().then(()=>clearTimeout(this.userNoAnswerTimer)).then(()=>this.generateResponseOfferAnswer(this.incomingInviteRequest,e)).then(A=>this.incomingInviteRequest.accept({statusCode:200,body:A,extraHeaders:t})):(clearTimeout(this.userNoAnswerTimer),this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(A=>this.incomingInviteRequest.accept({statusCode:200,body:A,extraHeaders:t})))}sendProgress(A={}){const e=A.statusCode||180,t=A.reasonPhrase,s=(A.extraHeaders||[]).slice(),i=A.body?U(A.body):void 0;if(183===e&&!i)return this.sendProgressWithSDP(A);try{const A=this.incomingInviteRequest.progress({statusCode:e,reasonPhrase:t,extraHeaders:s,body:i});return this._dialog=A.session,Promise.resolve(A)}catch(A){return Promise.reject(A)}}sendProgressWithSDP(A={}){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},t=A.statusCode||183,s=A.reasonPhrase,i=(A.extraHeaders||[]).slice();return this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(A=>this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:A})).then(A=>(this._dialog=A.session,A))}sendProgressReliable(A={}){return A.extraHeaders=(A.extraHeaders||[]).slice(),A.extraHeaders.push("Require: 100rel"),A.extraHeaders.push("RSeq: "+Math.floor(1e4*Math.random())),this.sendProgressWithSDP(A)}sendProgressReliableWaitForPrack(A={}){const e={sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions,sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers},t=A.statusCode||183,s=A.reasonPhrase,i=(A.extraHeaders||[]).slice();let n;return i.push("Require: 100rel"),i.push("RSeq: "+this.rseq++),new Promise((A,r)=>{this.waitingForPrack=!0,this.generateResponseOfferAnswer(this.incomingInviteRequest,e).then(A=>(n=A,this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:n}))).then(e=>{let a,V;this._dialog=e.session,e.session.delegate={onPrack:t=>{a=t,clearTimeout(c),clearTimeout(g),this.waitingForPrack&&(this.waitingForPrack=!1,this.handlePrackOfferAnswer(a).then(t=>{try{V=a.accept({statusCode:200,body:t}),this.prackArrived(),A({prackRequest:a,prackResponse:V,progressResponse:e})}catch(A){r(A)}}).catch(A=>r(A)))}};const c=setTimeout(()=>{this.waitingForPrack&&(this.waitingForPrack=!1,this.logger.warn("No PRACK received, rejecting INVITE."),clearTimeout(g),this.reject({statusCode:504}).then(()=>r(new o)).catch(A=>r(A)))},64*Z.T1),l=()=>{try{this.incomingInviteRequest.progress({statusCode:t,reasonPhrase:s,extraHeaders:i,body:n})}catch(A){return this.waitingForPrack=!1,void r(A)}g=setTimeout(l,h*=2)};let h=Z.T1,g=setTimeout(l,h)}).catch(A=>{this.waitingForPrack=!1,r(A)})})}sendProgressTrying(){try{const A=this.incomingInviteRequest.trying();return Promise.resolve(A)}catch(A){return Promise.reject(A)}}waitForArrivalOfPrack(){if(this.waitingForPrackPromise)throw new Error("Already waiting for PRACK");return this.waitingForPrackPromise=new Promise((A,e)=>{this.waitingForPrackResolve=A,this.waitingForPrackReject=e}),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 X extends W{constructor(A,e,t={}){super(A,t),this.disposed=!1,this.earlyMedia=!1,this.earlyMediaSessionDescriptionHandlers=new Map,this.isCanceled=!1,this.inviteWithoutSdp=!1,this.logger=A.getLogger("sip.Inviter"),this.earlyMedia=void 0!==t.earlyMedia?t.earlyMedia:this.earlyMedia,this.fromTag=f(),this.inviteWithoutSdp=void 0!==t.inviteWithoutSdp?t.inviteWithoutSdp:this.inviteWithoutSdp;const s=Object.assign({},t);s.params=Object.assign({},t.params);const i=t.anonymous||!1,n=A.contact.toString({anonymous:i,outbound:i?!A.contact.tempGruu:!A.contact.pubGruu});i&&A.configuration.uri&&(s.params.fromDisplayName="Anonymous",s.params.fromUri="sip:anonymous@anonymous.invalid");let o=A.userAgentCore.configuration.aor;if(s.params.fromUri&&(o="string"==typeof s.params.fromUri?C.URIParse(s.params.fromUri):s.params.fromUri),!o)throw new TypeError("Invalid from URI: "+s.params.fromUri);let r=e;if(s.params.toUri&&(r="string"==typeof s.params.toUri?C.URIParse(s.params.toUri):s.params.toUri),!r)throw new TypeError("Invalid to URI: "+s.params.toUri);const a=Object.assign({},s.params);a.fromTag=this.fromTag;const V=(s.extraHeaders||[]).slice();i&&A.configuration.uri&&(V.push("P-Preferred-Identity: "+A.configuration.uri.toString()),V.push("Privacy: id")),V.push("Contact: "+n),V.push("Allow: "+["ACK","CANCEL","INVITE","MESSAGE","BYE","OPTIONS","INFO","NOTIFY","REFER"].toString()),A.configuration.sipExtension100rel===j.Required&&V.push("Require: 100rel"),A.configuration.sipExtensionReplaces===j.Required&&V.push("Require: replaces"),s.extraHeaders=V;this.outgoingRequestMessage=A.userAgentCore.makeOutgoingRequestMessage(N.INVITE,e,o,r,a,V,undefined),this._contact=n,this._referralInviterOptions=s,this._renderbody=t.renderbody,this._rendertype=t.rendertype,t.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=t.sessionDescriptionHandlerModifiers),t.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=t.sessionDescriptionHandlerOptions),t.sessionDescriptionHandlerModifiersReInvite&&(this.sessionDescriptionHandlerModifiersReInvite=t.sessionDescriptionHandlerModifiersReInvite),t.sessionDescriptionHandlerOptionsReInvite&&(this.sessionDescriptionHandlerOptionsReInvite=t.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 H.Initial:case H.Establishing:return this.cancel().then(()=>super.dispose());case H.Established:case H.Terminating:case H.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(A={}){if(this.logger.log("Inviter.cancel"),this.state!==H.Initial&&this.state!==H.Establishing){const A=new Error(`Invalid session state ${this.state}`);return this.logger.error(A.message),Promise.reject(A)}if(this.isCanceled=!0,this.stateTransition(H.Terminating),this.outgoingInviteRequest){let e;A.statusCode&&A.reasonPhrase&&(e=function(A,e){if(A&&A<200||A>699)throw new TypeError("Invalid statusCode: "+A);if(A)return"SIP;cause="+A+';text="'+(w(A)||e)+'"'}(A.statusCode,A.reasonPhrase)),this.outgoingInviteRequest.cancel(e,A)}else this.logger.warn("Canceled session before INVITE was sent"),this.stateTransition(H.Terminated);return Promise.resolve()}invite(A={}){if(this.logger.log("Inviter.invite"),this.state!==H.Initial)return super.invite(A);if(A.sessionDescriptionHandlerModifiers&&(this.sessionDescriptionHandlerModifiers=A.sessionDescriptionHandlerModifiers),A.sessionDescriptionHandlerOptions&&(this.sessionDescriptionHandlerOptions=A.sessionDescriptionHandlerOptions),A.withoutSdp||this.inviteWithoutSdp)return this._renderbody&&this._rendertype&&(this.outgoingRequestMessage.body={contentType:this._rendertype,body:this._renderbody}),this.stateTransition(H.Establishing),Promise.resolve(this.sendInvite(A));const e={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.getOffer(e).then(e=>(this.outgoingRequestMessage.body={body:e.content,contentType:e.contentType},this.stateTransition(H.Establishing),this.sendInvite(A))).catch(A=>{throw this.logger.log(A.message),this.state!==H.Terminated&&this.stateTransition(H.Terminated),A})}sendInvite(A={}){return this.outgoingInviteRequest=this.userAgent.userAgentCore.invite(this.outgoingRequestMessage,{onAccept:e=>this.dialog?(this.logger.log("Additional confirmed dialog, sending ACK and BYE"),void this.ackAndBye(e)):this.isCanceled?(this.logger.log("Canceled session accepted, sending ACK and BYE"),this.ackAndBye(e),void this.stateTransition(H.Terminated)):(this.notifyReferer(e),void this.onAccept(e).then(()=>{this.disposeEarlyMedia()}).catch(()=>{this.disposeEarlyMedia()}).then(()=>{A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e)})),onProgress:e=>{this.isCanceled||(this.notifyReferer(e),this.onProgress(e).catch(()=>{this.disposeEarlyMedia()}).then(()=>{A.requestDelegate&&A.requestDelegate.onProgress&&A.requestDelegate.onProgress(e)}))},onRedirect:e=>{this.notifyReferer(e),this.onRedirect(e),A.requestDelegate&&A.requestDelegate.onRedirect&&A.requestDelegate.onRedirect(e)},onReject:e=>{this.notifyReferer(e),this.onReject(e),A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e)},onTrying:e=>{this.notifyReferer(e),this.onTrying(e),A.requestDelegate&&A.requestDelegate.onTrying&&A.requestDelegate.onTrying(e)}}),this.outgoingInviteRequest}disposeEarlyMedia(){this.earlyMediaSessionDescriptionHandlers.forEach(A=>{A.close()}),this.earlyMediaSessionDescriptionHandlers.clear()}notifyReferer(A){if(!this._referred)return;if(!(this._referred instanceof W))throw new Error("Referred session not instance of session");if(!this._referred.dialog)return;if(!A.message.statusCode)throw new Error("Status code undefined.");if(!A.message.reasonPhrase)throw new Error("Reason phrase undefined.");const e=`SIP/2.0 ${A.message.statusCode} ${A.message.reasonPhrase}`.trim();this._referred.dialog.notify(void 0,{extraHeaders:["Event: refer","Subscription-State: terminated"],body:{contentDisposition:"render",contentType:"message/sipfrag",content:e}}).delegate={onReject:()=>{this._referred=void 0}}}onAccept(A){if(this.logger.log("Inviter.onAccept"),this.state!==H.Establishing)return this.logger.error(`Accept received while in state ${this.state}, dropping response`),Promise.reject(new Error(`Invalid session state ${this.state}`));const e=A.message,t=A.session;switch(e.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=C.nameAddrHeaderParse(e.getHeader("P-Asserted-Identity"))),t.delegate={onAck:A=>this.onAckRequest(A),onBye:A=>this.onByeRequest(A),onInfo:A=>this.onInfoRequest(A),onInvite:A=>this.onInviteRequest(A),onMessage:A=>this.onMessageRequest(A),onNotify:A=>this.onNotifyRequest(A),onPrack:A=>this.onPrackRequest(A),onRefer:A=>this.onReferRequest(A)},this._dialog=t,t.signalingState){case Y.Initial:case Y.HaveLocalOffer:return this.logger.error("Received 2xx response to INVITE without a session description"),this.ackAndBye(A,400,"Missing session description"),this.stateTransition(H.Terminated),Promise.reject(new Error("Bad Media Description"));case Y.HaveRemoteOffer:{if(!this._dialog.offer)throw new Error(`Session offer undefined in signaling state ${this._dialog.signalingState}.`);const e={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setOfferAndGetAnswer(this._dialog.offer,e).then(e=>{A.ack({body:e}),this.stateTransition(H.Established)}).catch(e=>{throw this.ackAndBye(A,488,"Invalid session description"),this.stateTransition(H.Terminated),e})}case Y.Stable:{if(this.earlyMediaSessionDescriptionHandlers.size>0){const e=this.earlyMediaSessionDescriptionHandlers.get(t.id);if(!e)throw new Error("Session description handler undefined.");return this.setSessionDescriptionHandler(e),this.earlyMediaSessionDescriptionHandlers.delete(t.id),A.ack(),this.stateTransition(H.Established),Promise.resolve()}if(this.earlyMediaDialog){if(this.earlyMediaDialog!==t){if(this.earlyMedia){const A="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(A)}const e=new Error("Early media dialog does not equal confirmed dialog, terminating session");return this.logger.error(e.message),this.ackAndBye(A,488,"Not Acceptable Here"),this.stateTransition(H.Terminated),Promise.reject(e)}return A.ack(),this.stateTransition(H.Established),Promise.resolve()}const e=t.answer;if(!e)throw new Error("Answer is undefined.");const s={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(e,s).then(()=>{let e;this._renderbody&&this._rendertype&&(e={body:{contentDisposition:"render",contentType:this._rendertype,content:this._renderbody}}),A.ack(e),this.stateTransition(H.Established)}).catch(e=>{throw this.logger.error(e.message),this.ackAndBye(A,488,"Not Acceptable Here"),this.stateTransition(H.Terminated),e})}case Y.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onProgress(A){var e;if(this.logger.log("Inviter.onProgress"),this.state!==H.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 t=A.message,s=A.session;t.hasHeader("P-Asserted-Identity")&&(this._assertedIdentity=C.nameAddrHeaderParse(t.getHeader("P-Asserted-Identity")));const i=t.getHeader("require"),n=t.getHeader("rseq"),o=!!(i&&i.includes("100rel")&&n?Number(n):void 0),r=[];switch(o&&r.push("RAck: "+t.getHeader("rseq")+" "+t.getHeader("cseq")),s.signalingState){case Y.Initial:return o&&(this.logger.warn("First reliable provisional response received MUST contain an offer when INVITE does not contain an offer."),A.prack({extraHeaders:r})),Promise.resolve();case Y.HaveLocalOffer:return o&&A.prack({extraHeaders:r}),Promise.resolve();case Y.HaveRemoteOffer:if(!o)return this.logger.warn("Non-reliable provisional response MUST NOT contain an initial offer, discarding response."),Promise.resolve();{const i=this.sessionDescriptionHandlerFactory(this,this.userAgent.configuration.sessionDescriptionHandlerFactoryOptions||{});return(null===(e=this.delegate)||void 0===e?void 0:e.onSessionDescriptionHandler)&&this.delegate.onSessionDescriptionHandler(i,!0),this.earlyMediaSessionDescriptionHandlers.set(s.id,i),i.setDescription(t.body,this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers).then(()=>i.getDescription(this.sessionDescriptionHandlerOptions,this.sessionDescriptionHandlerModifiers)).then(e=>{const t={contentDisposition:"session",contentType:e.contentType,content:e.body};A.prack({extraHeaders:r,body:t})}).catch(A=>{throw this.stateTransition(H.Terminated),A})}case Y.Stable:if(o&&A.prack({extraHeaders:r}),this.earlyMedia&&!this.earlyMediaDialog){this.earlyMediaDialog=s;const A=s.answer;if(!A)throw new Error("Answer is undefined.");const e={sessionDescriptionHandlerModifiers:this.sessionDescriptionHandlerModifiers,sessionDescriptionHandlerOptions:this.sessionDescriptionHandlerOptions};return this.setAnswer(A,e).catch(A=>{throw this.stateTransition(H.Terminated),A})}return Promise.resolve();case Y.Closed:return Promise.reject(new Error("Terminated."));default:throw new Error("Unknown session signaling state.")}}onRedirect(A){this.logger.log("Inviter.onRedirect"),this.state===H.Establishing||this.state===H.Terminating?this.stateTransition(H.Terminated):this.logger.error(`Redirect received while in state ${this.state}, dropping response`)}onReject(A){this.logger.log("Inviter.onReject"),this.state===H.Establishing||this.state===H.Terminating?this.stateTransition(H.Terminated):this.logger.error(`Reject received while in state ${this.state}, dropping response`)}onTrying(A){this.logger.log("Inviter.onTrying"),this.state===H.Establishing||this.logger.error(`Trying received while in state ${this.state}, dropping response`)}}var _,$,AA,eA,tA,sA,iA;!function(A){A.Initial="Initial",A.Registered="Registered",A.Unregistered="Unregistered",A.Terminated="Terminated"}(_=_||(_={}));class nA{constructor(A,e={}){this.disposed=!1,this._contacts=[],this._retryAfter=void 0,this._state=_.Initial,this._waiting=!1,this._stateEventEmitter=new l,this._waitingEventEmitter=new l,this.userAgent=A;const t=A.configuration.uri.clone();if(t.user=void 0,this.options=Object.assign(Object.assign(Object.assign({},nA.defaultOptions()),{registrar:t}),nA.stripUndefinedProperties(e)),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===C.parse(this.options.instanceId,"uuid"))throw new Error("Invalid instanceId.");if(this.options.regId&&this.options.regId<0)throw new Error("Invalid regId.");const s=this.options.registrar,i=this.options.params&&this.options.params.fromUri||A.userAgentCore.configuration.aor,n=this.options.params&&this.options.params.toUri||A.configuration.uri,o=this.options.params||{},r=(e.extraHeaders||[]).slice();if(this.request=A.userAgentCore.makeOutgoingRequestMessage(N.REGISTER,s,i,n,o,r,void 0),this.expires=this.options.expires||nA.defaultExpires,this.expires<0)throw new Error("Invalid expires.");if(this.refreshFrequency=this.options.refreshFrequency||nA.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=A.getLogger("sip.Registerer"),this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(A=>{const e=this.options[A];if("registrar"===A)this.logger.log("· "+A+": "+e);else this.logger.log("· "+A+": "+JSON.stringify(e))})),this.id=this.request.callId+this.request.from.parameters.tag,this.userAgent._registerers[this.id]=this}static defaultOptions(){return{expires:nA.defaultExpires,extraContactHeaderParams:[],extraHeaders:[],logConfiguration:!0,instanceId:"",params:{},regId:0,registrar:new d("sip","anonymous","anonymous.invalid"),refreshFrequency:nA.defaultRefreshFrequency}}static stripUndefinedProperties(A){return Object.keys(A).reduce((e,t)=>(void 0!==A[t]&&(e[t]=A[t]),e),{})}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(A=>{const e=()=>{if(!this.waiting&&this._state===_.Registered)return this.stateChange.addListener(()=>{this.terminated(),A()},{once:!0}),void this.unregister();this.terminated(),A()};this.waiting?this.waitingChange.addListener(()=>{e()},{once:!0}):e()}))}register(A={}){if(this.state===_.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 A=new i("REGISTER request already in progress, waiting for final response");return Promise.reject(A)}A.requestOptions&&(this.options=Object.assign(Object.assign({},this.options),A.requestOptions));const e=(this.options.extraHeaders||[]).slice();e.push("Contact: "+this.generateContactHeader(this.expires)),e.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=e,this.waitingToggle(!0);const t=this.userAgent.userAgentCore.register(this.request,{onAccept:e=>{let t;e.message.hasHeader("expires")&&(t=Number(e.message.getHeader("expires"))),this._contacts=e.message.getHeaders("contact");let s,i=this._contacts.length;if(!i)return this.logger.error("No Contact header in response to REGISTER, dropping response."),void this.unregistered();for(;i--;){if(s=e.message.parseHeader("contact",i),!s)throw new Error("Contact undefined");if(this.userAgent.contact.pubGruu&&p(s.uri,this.userAgent.contact.pubGruu)){t=Number(s.getParam("expires"));break}if(""===this.userAgent.configuration.contactName){if(s.uri.user===this.userAgent.contact.uri.user){t=Number(s.getParam("expires"));break}}else if(p(s.uri,this.userAgent.contact.uri)){t=Number(s.getParam("expires"));break}s=void 0}if(void 0===s)return this.logger.error("No Contact header pointing to us, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(void 0===t)return this.logger.error("Contact pointing to us is missing expires parameter, dropping response"),this.unregistered(),void this.waitingToggle(!1);if(s.hasParam("temp-gruu")){const A=s.getParam("temp-gruu");A&&(this.userAgent.contact.tempGruu=C.URIParse(A.replace(/"/g,"")))}if(s.hasParam("pub-gruu")){const A=s.getParam("pub-gruu");A&&(this.userAgent.contact.pubGruu=C.URIParse(A.replace(/"/g,"")))}this.registered(t),A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e),this.waitingToggle(!1)},onProgress:e=>{A.requestDelegate&&A.requestDelegate.onProgress&&A.requestDelegate.onProgress(e)},onRedirect:e=>{this.logger.error("Redirect received. Not supported."),this.unregistered(),A.requestDelegate&&A.requestDelegate.onRedirect&&A.requestDelegate.onRedirect(e),this.waitingToggle(!1)},onReject:e=>{if(423===e.message.statusCode)return e.message.hasHeader("min-expires")?(this.expires=Number(e.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 ${e.message.statusCode}`);let t=NaN;if(500===e.message.statusCode||503===e.message.statusCode){const A=e.message.getHeader("retry-after");A&&(t=Number.parseInt(A,void 0))}this._retryAfter=isNaN(t)?void 0:t,this.unregistered(),A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e),this._retryAfter=void 0,this.waitingToggle(!1)},onTrying:e=>{A.requestDelegate&&A.requestDelegate.onTrying&&A.requestDelegate.onTrying(e)}});return Promise.resolve(t)}unregister(A={}){if(this.state===_.Terminated)throw this.stateError(),new Error("Registerer terminated. Unable to register.");if(this.disposed&&this.state!==_.Registered)throw this.stateError(),new Error("Registerer disposed. Unable to register.");if(this.waiting){this.waitingWarning();const A=new i("REGISTER request already in progress, waiting for final response");return Promise.reject(A)}this._state===_.Registered||A.all||this.logger.warn("Not currently registered, but sending an unregister anyway.");const e=(A.requestOptions&&A.requestOptions.extraHeaders||[]).slice();this.request.extraHeaders=e,A.all?(e.push("Contact: *"),e.push("Expires: 0")):e.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 t=this.userAgent.userAgentCore.register(this.request,{onAccept:e=>{this._contacts=e.message.getHeaders("contact"),this.unregistered(),A.requestDelegate&&A.requestDelegate.onAccept&&A.requestDelegate.onAccept(e),this.waitingToggle(!1)},onProgress:e=>{A.requestDelegate&&A.requestDelegate.onProgress&&A.requestDelegate.onProgress(e)},onRedirect:e=>{this.logger.error("Unregister redirected. Not currently supported."),this.unregistered(),A.requestDelegate&&A.requestDelegate.onRedirect&&A.requestDelegate.onRedirect(e),this.waitingToggle(!1)},onReject:e=>{this.logger.error(`Unregister rejected with status code ${e.message.statusCode}`),this.unregistered(),A.requestDelegate&&A.requestDelegate.onReject&&A.requestDelegate.onReject(e),this.waitingToggle(!1)},onTrying:e=>{A.requestDelegate&&A.requestDelegate.onTrying&&A.requestDelegate.onTrying(e)}});return Promise.resolve(t)}clearTimers(){void 0!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=void 0),void 0!==this.registrationExpiredTimer&&(clearTimeout(this.registrationExpiredTimer),this.registrationExpiredTimer=void 0)}generateContactHeader(A){let e=this.userAgent.contact.toString({register:!0});return this.options.regId&&this.options.instanceId&&(e+=";reg-id="+this.options.regId,e+=';+sip.instance="<urn:uuid:'+this.options.instanceId+'>"'),this.options.extraContactHeaderParams&&this.options.extraContactHeaderParams.forEach(A=>{e+=";"+A}),e+=";expires="+A,e}registered(A){this.clearTimers(),this.registrationTimer=setTimeout(()=>{this.registrationTimer=void 0,this.register()},this.refreshFrequency/100*A*1e3),this.registrationExpiredTimer=setTimeout(()=>{this.logger.warn("Registration expired"),this.unregistered()},1e3*A),this._state!==_.Registered&&this.stateTransition(_.Registered)}unregistered(){this.clearTimers(),this._state!==_.Unregistered&&this.stateTransition(_.Unregistered)}terminated(){this.clearTimers(),this._state!==_.Terminated&&this.stateTransition(_.Terminated)}stateTransition(A){const e=()=>{throw new Error(`Invalid state transition from ${this._state} to ${A}`)};switch(this._state){case _.Initial:A!==_.Registered&&A!==_.Unregistered&&A!==_.Terminated&&e();break;case _.Registered:A!==_.Unregistered&&A!==_.Terminated&&e();break;case _.Unregistered:A!==_.Registered&&A!==_.Terminated&&e();break;case _.Terminated:e();break;default:throw new Error("Unrecognized state.")}this._state=A,this.logger.log(`Registration transitioned to state ${this._state}`),this._stateEventEmitter.emit(this._state),A===_.Terminated&&this.dispose()}get waiting(){return this._waiting}get waitingChange(){return this._waitingEventEmitter}waitingToggle(A){if(this._waiting===A)throw new Error(`Invalid waiting transition from ${this._waiting} to ${A}`);this._waiting=A,this.logger.log(`Waiting toggled to ${this._waiting}`),this._waitingEventEmitter.emit(this._waiting)}waitingWarning(){let A="An attempt was made to send a REGISTER request while a prior one was still in progress.";A+=" RFC 3261 requires UAs MUST NOT send a new registration until they have received a final response",A+=" from the registrar for the previous one or the previous REGISTER request has timed out.",A+=" Note that if the transport disconnects, you still must wait for the prior request to time out before",A+=" 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 A=`An attempt was made to send a REGISTER request when the Registerer ${this.state===_.Terminated?"is in 'Terminated' state":"has been disposed"}.`;A+=" The Registerer transitions to 'Terminated' when Registerer.dispose() is called.",A+=" Perhaps you called UserAgent.stop() which dipsoses of all Registerers?",this.logger.error(A)}}nA.defaultExpires=600,nA.defaultRefreshFrequency=99,function(A){A.Initial="Initial",A.NotifyWait="NotifyWait",A.Pending="Pending",A.Active="Active",A.Terminated="Terminated"}($=$||($={})),function(A){A.Connecting="Connecting",A.Connected="Connected",A.Disconnecting="Disconnecting",A.Disconnected="Disconnected"}(AA=AA||(AA={})),function(A){A.Started="Started",A.Stopped="Stopped"}(eA=eA||(eA={}));class oA{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(A,e=!1){return this.onePassHasher.start().appendStr(A).end(e)}static hashAsciiStr(A,e=!1){return this.onePassHasher.start().appendAsciiStr(A).end(e)}static _hex(A){const e=oA.hexChars,t=oA.hexOut;let s,i,n,o;for(o=0;o<4;o+=1)for(i=8*o,s=A[o],n=0;n<8;n+=2)t[i+1+n]=e.charAt(15&s),s>>>=4,t[i+0+n]=e.charAt(15&s),s>>>=4;return t.join("")}static _md5cycle(A,e){let t=A[0],s=A[1],i=A[2],n=A[3];t+=(s&i|~s&n)+e[0]-680876936|0,t=(t<<7|t>>>25)+s|0,n+=(t&s|~t&i)+e[1]-389564586|0,n=(n<<12|n>>>20)+t|0,i+=(n&t|~n&s)+e[2]+606105819|0,i=(i<<17|i>>>15)+n|0,s+=(i&n|~i&t)+e[3]-1044525330|0,s=(s<<22|s>>>10)+i|0,t+=(s&i|~s&n)+e[4]-176418897|0,t=(t<<7|t>>>25)+s|0,n+=(t&s|~t&i)+e[5]+1200080426|0,n=(n<<12|n>>>20)+t|0,i+=(n&t|~n&s)+e[6]-1473231341|0,i=(i<<17|i>>>15)+n|0,s+=(i&n|~i&t)+e[7]-45705983|0,s=(s<<22|s>>>10)+i|0,t+=(s&i|~s&n)+e[8]+1770035416|0,t=(t<<7|t>>>25)+s|0,n+=(t&s|~t&i)+e[9]-1958414417|0,n=(n<<12|n>>>20)+t|0,i+=(n&t|~n&s)+e[10]-42063|0,i=(i<<17|i>>>15)+n|0,s+=(i&n|~i&t)+e[11]-1990404162|0,s=(s<<22|s>>>10)+i|0,t+=(s&i|~s&n)+e[12]+1804603682|0,t=(t<<7|t>>>25)+s|0,n+=(t&s|~t&i)+e[13]-40341101|0,n=(n<<12|n>>>20)+t|0,i+=(n&t|~n&s)+e[14]-1502002290|0,i=(i<<17|i>>>15)+n|0,s+=(i&n|~i&t)+e[15]+1236535329|0,s=(s<<22|s>>>10)+i|0,t+=(s&n|i&~n)+e[1]-165796510|0,t=(t<<5|t>>>27)+s|0,n+=(t&i|s&~i)+e[6]-1069501632|0,n=(n<<9|n>>>23)+t|0,i+=(n&s|t&~s)+e[11]+643717713|0,i=(i<<14|i>>>18)+n|0,s+=(i&t|n&~t)+e[0]-373897302|0,s=(s<<20|s>>>12)+i|0,t+=(s&n|i&~n)+e[5]-701558691|0,t=(t<<5|t>>>27)+s|0,n+=(t&i|s&~i)+e[10]+38016083|0,n=(n<<9|n>>>23)+t|0,i+=(n&s|t&~s)+e[15]-660478335|0,i=(i<<14|i>>>18)+n|0,s+=(i&t|n&~t)+e[4]-405537848|0,s=(s<<20|s>>>12)+i|0,t+=(s&n|i&~n)+e[9]+568446438|0,t=(t<<5|t>>>27)+s|0,n+=(t&i|s&~i)+e[14]-1019803690|0,n=(n<<9|n>>>23)+t|0,i+=(n&s|t&~s)+e[3]-187363961|0,i=(i<<14|i>>>18)+n|0,s+=(i&t|n&~t)+e[8]+1163531501|0,s=(s<<20|s>>>12)+i|0,t+=(s&n|i&~n)+e[13]-1444681467|0,t=(t<<5|t>>>27)+s|0,n+=(t&i|s&~i)+e[2]-51403784|0,n=(n<<9|n>>>23)+t|0,i+=(n&s|t&~s)+e[7]+1735328473|0,i=(i<<14|i>>>18)+n|0,s+=(i&t|n&~t)+e[12]-1926607734|0,s=(s<<20|s>>>12)+i|0,t+=(s^i^n)+e[5]-378558|0,t=(t<<4|t>>>28)+s|0,n+=(t^s^i)+e[8]-2022574463|0,n=(n<<11|n>>>21)+t|0,i+=(n^t^s)+e[11]+1839030562|0,i=(i<<16|i>>>16)+n|0,s+=(i^n^t)+e[14]-35309556|0,s=(s<<23|s>>>9)+i|0,t+=(s^i^n)+e[1]-1530992060|0,t=(t<<4|t>>>28)+s|0,n+=(t^s^i)+e[4]+1272893353|0,n=(n<<11|n>>>21)+t|0,i+=(n^t^s)+e[7]-155497632|0,i=(i<<16|i>>>16)+n|0,s+=(i^n^t)+e[10]-1094730640|0,s=(s<<23|s>>>9)+i|0,t+=(s^i^n)+e[13]+681279174|0,t=(t<<4|t>>>28)+s|0,n+=(t^s^i)+e[0]-358537222|0,n=(n<<11|n>>>21)+t|0,i+=(n^t^s)+e[3]-722521979|0,i=(i<<16|i>>>16)+n|0,s+=(i^n^t)+e[6]+76029189|0,s=(s<<23|s>>>9)+i|0,t+=(s^i^n)+e[9]-640364487|0,t=(t<<4|t>>>28)+s|0,n+=(t^s^i)+e[12]-421815835|0,n=(n<<11|n>>>21)+t|0,i+=(n^t^s)+e[15]+530742520|0,i=(i<<16|i>>>16)+n|0,s+=(i^n^t)+e[2]-995338651|0,s=(s<<23|s>>>9)+i|0,t+=(i^(s|~n))+e[0]-198630844|0,t=(t<<6|t>>>26)+s|0,n+=(s^(t|~i))+e[7]+1126891415|0,n=(n<<10|n>>>22)+t|0,i+=(t^(n|~s))+e[14]-1416354905|0,i=(i<<15|i>>>17)+n|0,s+=(n^(i|~t))+e[5]-57434055|0,s=(s<<21|s>>>11)+i|0,t+=(i^(s|~n))+e[12]+1700485571|0,t=(t<<6|t>>>26)+s|0,n+=(s^(t|~i))+e[3]-1894986606|0,n=(n<<10|n>>>22)+t|0,i+=(t^(n|~s))+e[10]-1051523|0,i=(i<<15|i>>>17)+n|0,s+=(n^(i|~t))+e[1]-2054922799|0,s=(s<<21|s>>>11)+i|0,t+=(i^(s|~n))+e[8]+1873313359|0,t=(t<<6|t>>>26)+s|0,n+=(s^(t|~i))+e[15]-30611744|0,n=(n<<10|n>>>22)+t|0,i+=(t^(n|~s))+e[6]-1560198380|0,i=(i<<15|i>>>17)+n|0,s+=(n^(i|~t))+e[13]+1309151649|0,s=(s<<21|s>>>11)+i|0,t+=(i^(s|~n))+e[4]-145523070|0,t=(t<<6|t>>>26)+s|0,n+=(s^(t|~i))+e[11]-1120210379|0,n=(n<<10|n>>>22)+t|0,i+=(t^(n|~s))+e[2]+718787259|0,i=(i<<15|i>>>17)+n|0,s+=(n^(i|~t))+e[9]-343485551|0,s=(s<<21|s>>>11)+i|0,A[0]=t+A[0]|0,A[1]=s+A[1]|0,A[2]=i+A[2]|0,A[3]=n+A[3]|0}start(){return this._dataLength=0,this._bufferLength=0,this._state.set(oA.stateIdentity),this}appendStr(A){const e=this._buffer8,t=this._buffer32;let s,i,n=this._bufferLength;for(i=0;i<A.length;i+=1){if(s=A.charCodeAt(i),s<128)e[n++]=s;else if(s<2048)e[n++]=(s>>>6)+192,e[n++]=63&s|128;else if(s<55296||s>56319)e[n++]=(s>>>12)+224,e[n++]=s>>>6&63|128,e[n++]=63&s|128;else{if(s=1024*(s-55296)+(A.charCodeAt(++i)-56320)+65536,s>1114111)throw new Error("Unicode standard supports code points up to U+10FFFF");e[n++]=(s>>>18)+240,e[n++]=s>>>12&63|128,e[n++]=s>>>6&63|128,e[n++]=63&s|128}n>=64&&(this._dataLength+=64,oA._md5cycle(this._state,t),n-=64,t[0]=t[16])}return this._bufferLength=n,this}appendAsciiStr(A){const e=this._buffer8,t=this._buffer32;let s,i=this._bufferLength,n=0;for(;;){for(s=Math.min(A.length-n,64-i);s--;)e[i++]=A.charCodeAt(n++);if(i<64)break;this._dataLength+=64,oA._md5cycle(this._state,t),i=0}return this._bufferLength=i,this}appendByteArray(A){const e=this._buffer8,t=this._buffer32;let s,i=this._bufferLength,n=0;for(;;){for(s=Math.min(A.length-n,64-i);s--;)e[i++]=A[n++];if(i<64)break;this._dataLength+=64,oA._md5cycle(this._state,t),i=0}return this._bufferLength=i,this}getState(){const A=this,e=A._state;return{buffer:String.fromCharCode.apply(null,A._buffer8),buflen:A._bufferLength,length:A._dataLength,state:[e[0],e[1],e[2],e[3]]}}setState(A){const e=A.buffer,t=A.state,s=this._state;let i;for(this._dataLength=A.length,this._bufferLength=A.buflen,s[0]=t[0],s[1]=t[1],s[2]=t[2],s[3]=t[3],i=0;i<e.length;i+=1)this._buffer8[i]=e.charCodeAt(i)}end(A=!1){const e=this._bufferLength,t=this._buffer8,s=this._buffer32,i=1+(e>>2);let n;if(this._dataLength+=e,t[e]=128,t[e+1]=t[e+2]=t[e+3]=0,s.set(oA.buffer32Identity.subarray(i),i),e>55&&(oA._md5cycle(this._state,s),s.set(oA.buffer32Identity)),n=8*this._dataLength,n<=4294967295)s[14]=n;else{const A=n.toString(16).match(/(.*?)(.{0,8})$/);if(null===A)return;const e=parseInt(A[2],16),t=parseInt(A[1],16)||0;s[14]=e,s[15]=t}return oA._md5cycle(this._state,s),A?this._state:oA._hex(this._state)}}function rA(A){return oA.hashStr(A)}oA.stateIdentity=new Int32Array([1732584193,-271733879,-1732584194,271733878]),oA.buffer32Identity=new Int32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),oA.hexChars="0123456789abcdef",oA.hexOut=[],oA.onePassHasher=new oA,"5d41402abc4b2a76b9719d911017c592"!==oA.hashStr("hello")&&console.error("Md5 self test failed.");class aA{constructor(A,e,t,s){this.logger=A.getLogger("sipjs.digestauthentication"),this.username=t,this.password=s,this.ha1=e,this.nc=0,this.ncHex="00000000"}authenticate(A,e,t){if(this.algorithm=e.algorithm,this.realm=e.realm,this.nonce=e.nonce,this.opaque=e.opaque,this.stale=e.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(e.qop)if(e.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(e.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=A.method,this.uri=A.ruri,this.cnonce=M(12),this.nc+=1,this.updateNcHex(),4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.calculateResponse(t),!0}toString(){const A=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return A.push("algorithm="+this.algorithm),A.push('username="'+this.username+'"'),A.push('realm="'+this.realm+'"'),A.push('nonce="'+this.nonce+'"'),A.push('uri="'+this.uri+'"'),A.push('response="'+this.response+'"'),this.opaque&&A.push('opaque="'+this.opaque+'"'),this.qop&&(A.push("qop="+this.qop),A.push('cnonce="'+this.cnonce+'"'),A.push("nc="+this.ncHex)),"Digest "+A.join(", ")}updateNcHex(){const A=Number(this.nc).toString(16);this.ncHex="00000000".substr(0,8-A.length)+A}calculateResponse(A){let e,t;e=this.ha1,""!==e&&void 0!==e||(e=rA(this.username+":"+this.realm+":"+this.password)),"auth"===this.qop?(t=rA(this.method+":"+this.uri),this.response=rA(e+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+t)):"auth-int"===this.qop?(t=rA(this.method+":"+this.uri+":"+rA(A||"")),this.response=rA(e+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+t)):void 0===this.qop&&(t=rA(this.method+":"+this.uri),this.response=rA(e+":"+this.nonce+":"+t))}}!function(A){A[A.error=0]="error",A[A.warn=1]="warn",A[A.log=2]="log",A[A.debug=3]="debug"}(tA=tA||(tA={}));class VA{constructor(A,e,t){this.logger=A,this.category=e,this.label=t}error(A){this.genericLog(tA.error,A)}warn(A){this.genericLog(tA.warn,A)}log(A){this.genericLog(tA.log,A)}debug(A){this.genericLog(tA.debug,A)}genericLog(A,e){this.logger.genericLog(A,this.category,this.label,e)}get level(){return this.logger.level}set level(A){this.logger.level=A}}class cA{constructor(){this.builtinEnabled=!0,this._level=tA.log,this.loggers={},this.logger=this.getLogger("sip:loggerfactory")}get level(){return this._level}set level(A){A>=0&&A<=3?this._level=A:A>3?this._level=3:tA.hasOwnProperty(A)?this._level=A:this.logger.error("invalid 'level' parameter value: "+JSON.stringify(A))}get connector(){return this._connector}set connector(A){A?"function"==typeof A?this._connector=A:this.logger.error("invalid 'connector' parameter value: "+JSON.stringify(A)):this._connector=void 0}getLogger(A,e){if(e&&3===this.level)return new VA(this,A,e);if(this.loggers[A])return this.loggers[A];{const e=new VA(this,A);return this.loggers[A]=e,e}}genericLog(A,e,t,s){this.level>=A&&this.builtinEnabled&&this.print(A,e,t,s),this.connector&&this.connector(tA[A],e,t,s)}print(A,e,t,s){if("string"==typeof s){const A=[new Date,e];t&&A.push(t),s=A.concat(s).join(" | ")}switch(A){case tA.error:console.error(s);break;case tA.warn:console.warn(s);case tA.log:case tA.debug:}}}function lA(A,e){const t="\r\n";if(e.statusCode<100||e.statusCode>699)throw new TypeError("Invalid statusCode: "+e.statusCode);const s=e.reasonPhrase?e.reasonPhrase:w(e.statusCode);let i="SIP/2.0 "+e.statusCode+" "+s+t;e.statusCode>=100&&e.statusCode,e.statusCode;const n="From: "+A.getHeader("From")+t,o="Call-ID: "+A.callId+t,r="CSeq: "+A.cseq+" "+A.method+t,a=A.getHeaders("via").reduce((A,e)=>A+"Via: "+e+t,"");let V="To: "+A.getHeader("to");if(e.statusCode>100&&!A.parseHeader("to").hasParam("tag")){let A=e.toTag;A||(A=f()),V+=";tag="+A}V+=t;let c="";e.supported&&(c="Supported: "+e.supported.join(", ")+t);let l="";e.userAgent&&(l="User-Agent: "+e.userAgent+t);let h="";return e.extraHeaders&&(h=e.extraHeaders.reduce((A,e)=>A+e.trim()+t,"")),i+=a,i+=n,i+=V,i+=r,i+=o,i+=c,i+=l,i+=h,e.body?(i+="Content-Type: "+e.body.contentType+t,i+="Content-Length: "+S(e.body.content)+t+t,i+=e.body.content):i+="Content-Length: 0\r\n\r\n",{message:i}}!function(A){function e(A,e){let t=e,s=0,i=0;if(A.substring(t,t+2).match(/(^\r\n)/))return-2;for(;0===s;){if(i=A.indexOf("\r\n",t),-1===i)return i;!A.substring(i+2,i+4).match(/(^\r\n)/)&&A.charAt(i+2).match(/(^\s+)/)?t=i+2:s=i}return s}function t(A,e,t,s){const i=e.indexOf(":",t),n=e.substring(t,i).trim(),o=e.substring(i+1,s).trim();let r;switch(n.toLowerCase()){case"via":case"v":A.addHeader("via",o),1===A.getHeaders("via").length?(r=A.parseHeader("Via"),r&&(A.via=r,A.viaBranch=r.branch)):r=0;break;case"from":case"f":A.setHeader("from",o),r=A.parseHeader("from"),r&&(A.from=r,A.fromTag=r.getParam("tag"));break;case"to":case"t":A.setHeader("to",o),r=A.parseHeader("to"),r&&(A.to=r,A.toTag=r.getParam("tag"));break;case"record-route":if(r=C.parse(o,"Record_Route"),-1===r){r=void 0;break}if(!(r instanceof Array)){r=void 0;break}r.forEach(e=>{A.addHeader("record-route",o.substring(e.position,e.offset)),A.headers["Record-Route"][A.getHeaders("record-route").length-1].parsed=e.parsed});break;case"call-id":case"i":A.setHeader("call-id",o),r=A.parseHeader("call-id"),r&&(A.callId=o);break;case"contact":case"m":if(r=C.parse(o,"Contact"),-1===r){r=void 0;break}if(!(r instanceof Array)){r=void 0;break}r.forEach(e=>{A.addHeader("contact",o.substring(e.position,e.offset)),A.headers.Contact[A.getHeaders("contact").length-1].parsed=e.parsed});break;case"content-length":case"l":A.setHeader("content-length",o),r=A.parseHeader("content-length");break;case"content-type":case"c":A.setHeader("content-type",o),r=A.parseHeader("content-type");break;case"cseq":A.setHeader("cseq",o),r=A.parseHeader("cseq"),r&&(A.cseq=r.value),A instanceof y&&(A.method=r.method);break;case"max-forwards":A.setHeader("max-forwards",o),r=A.parseHeader("max-forwards");break;case"www-authenticate":A.setHeader("www-authenticate",o),r=A.parseHeader("www-authenticate");break;case"proxy-authenticate":A.setHeader("proxy-authenticate",o),r=A.parseHeader("proxy-authenticate");break;case"refer-to":case"r":A.setHeader("refer-to",o),r=A.parseHeader("refer-to"),r&&(A.referTo=r);break;default:A.addHeader(n.toLowerCase(),o),r=0}return void 0!==r||{error:"error parsing header '"+n+"'"}}A.getHeader=e,A.parseHeader=t,A.parseMessage=function(A,s){let i=0,n=A.indexOf("\r\n");if(-1===n)return void s.warn("no CRLF found, not a SIP message, discarded");const o=A.substring(0,n),r=C.parse(o,"Request_Response");let a,V;if(-1!==r){for(r.status_code?(a=new y,a.statusCode=r.status_code,a.reasonPhrase=r.reason_phrase):(a=new T,a.method=r.method,a.ruri=r.uri),a.data=A,i=n+2;;){if(n=e(A,i),-2===n){V=i+2;break}if(-1===n)return void s.error("malformed message");const o=t(a,A,i,n);if(o&&!0!==o)return void s.error(o.error);i=n+2}return a.hasHeader("content-length")?a.body=A.substr(V,Number(a.getHeader("content-length"))):a.body=A.substring(V),a}s.warn('error parsing first line of SIP message: "'+o+'"')}}(sA=sA||(sA={}));class hA extends t{constructor(A){super(A||"Unspecified transport error.")}}class gA{constructor(A,e,t,s,i){this._transport=A,this._user=e,this._id=t,this._state=s,this.listeners=new Array,this.logger=e.loggerFactory.getLogger(i,t),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(A,e){const t=()=>{this.removeStateChangeListener(t),A()};!0===(null==e?void 0:e.once)?this.listeners.push(t):this.listeners.push(A)}notifyStateChangeListeners(){this.listeners.slice().forEach(A=>A())}removeStateChangeListener(A){this.listeners=this.listeners.filter(e=>e!==A)}logTransportError(A,e){this.logger.error(A.message),this.logger.error(`Transport error occurred in ${this.typeToString()} with id ${this.id}.`),this.logger.error(e)}send(A){return this.transport.send(A).catch(A=>{if(A instanceof hA)throw this.onTransportError(A),A;let e;throw e=A&&"string"==typeof A.message?new hA(A.message):new hA,this.onTransportError(e),e})}setState(A){this.logger.debug(`State change to "${A}" on ${this.typeToString()} with id ${this.id}.`),this._state=A,this._user.onStateChange&&this._user.onStateChange(A),this.notifyStateChangeListeners()}typeToString(){return"UnknownType"}}class qA extends gA{constructor(A,e,t,s,i){super(e,t,A.viaBranch,s,i),this._request=A,this.user=t}get request(){return this._request}}!function(A){A.Accepted="Accepted",A.Calling="Calling",A.Completed="Completed",A.Confirmed="Confirmed",A.Proceeding="Proceeding",A.Terminated="Terminated",A.Trying="Trying"}(iA=iA||(iA={}));class dA extends qA{constructor(A,e,t){super(A,e,t,iA.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(A){switch(this.state){case iA.Proceeding:if(A.method===N.INVITE)return void(this.lastProvisionalResponse&&this.send(this.lastProvisionalResponse).catch(A=>{this.logTransportError(A,"Failed to send retransmission of provisional response.")}));break;case iA.Accepted:if(A.method===N.INVITE)return;break;case iA.Completed:if(A.method===N.INVITE){if(!this.lastFinalResponse)throw new Error("Last final response undefined.");return void this.send(this.lastFinalResponse).catch(A=>{this.logTransportError(A,"Failed to send retransmission of final response.")})}if(A.method===N.ACK)return void this.stateTransition(iA.Confirmed);break;case iA.Confirmed:case iA.Terminated:if(A.method===N.INVITE||A.method===N.ACK)return;break;default:throw new Error(`Invalid state ${this.state}`)}const e=`INVITE server transaction received unexpected ${A.method} request while in state ${this.state}.`;this.logger.warn(e)}receiveResponse(A,e){if(A<100||A>699)throw new Error(`Invalid status code ${A}`);switch(this.state){case iA.Proceeding:if(A>=100&&A<=199)return this.lastProvisionalResponse=e,A>100&&this.startProgressExtensionTimer(),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send 1xx response.")});if(A>=200&&A<=299)return this.lastFinalResponse=e,this.stateTransition(iA.Accepted),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send 2xx response.")});if(A>=300&&A<=699)return this.lastFinalResponse=e,this.stateTransition(iA.Completed),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send non-2xx final response.")});break;case iA.Accepted:if(A>=200&&A<=299)return void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send 2xx response.")});break;case iA.Completed:case iA.Confirmed:case iA.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const t=`INVITE server transaction received unexpected ${A} response from TU while in state ${this.state}.`;throw this.logger.error(t),new Error(t)}retransmitAcceptedResponse(){this.state===iA.Accepted&&this.lastFinalResponse&&this.send(this.lastFinalResponse).catch(A=>{this.logTransportError(A,"Failed to send 2xx response.")})}onTransportError(A){this.user.onTransportError&&this.user.onTransportError(A)}typeToString(){return"INVITE server transaction"}stateTransition(A){const e=()=>{throw new Error(`Invalid state transition from ${this.state} to ${A}`)};switch(A){case iA.Proceeding:e();break;case iA.Accepted:case iA.Completed:this.state!==iA.Proceeding&&e();break;case iA.Confirmed:this.state!==iA.Completed&&e();break;case iA.Terminated:this.state!==iA.Accepted&&this.state!==iA.Completed&&this.state!==iA.Confirmed&&e();break;default:e()}this.stopProgressExtensionTimer(),A===iA.Accepted&&(this.L=setTimeout(()=>this.timerL(),Z.TIMER_L)),A===iA.Completed&&(this.H=setTimeout(()=>this.timerH(),Z.TIMER_H)),A===iA.Confirmed&&(this.I=setTimeout(()=>this.timerI(),Z.TIMER_I)),A===iA.Terminated&&this.dispose(),this.setState(A)}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(A=>{this.logTransportError(A,"Failed to send retransmission of provisional response.")})},Z.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===iA.Completed&&(this.logger.warn("ACK to negative final response was never received, terminating transaction."),this.stateTransition(iA.Terminated))}timerI(){this.logger.debug(`Timer I expired for INVITE server transaction ${this.id}.`),this.stateTransition(iA.Terminated)}timerL(){this.logger.debug(`Timer L expired for INVITE server transaction ${this.id}.`),this.state===iA.Accepted&&this.stateTransition(iA.Terminated)}}class pA extends gA{constructor(A,e,t,s,i){super(e,t,pA.makeId(A),s,i),this._request=A,this.user=t,A.setViaHeader(this.id,e.protocol)}static makeId(A){if("CANCEL"===A.method){if(!A.branch)throw new Error("Outgoing CANCEL request without a branch.");return A.branch}return"z9hG4bK"+Math.floor(1e7*Math.random())}get request(){return this._request}onRequestTimeout(){this.user.onRequestTimeout&&this.user.onRequestTimeout()}}class uA extends pA{constructor(A,e,t){super(A,e,t,iA.Trying,"sip.transaction.nict"),this.F=setTimeout(()=>this.timerF(),Z.TIMER_F),this.send(A.toString()).catch(A=>{this.logTransportError(A,"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(A){const e=A.statusCode;if(!e||e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case iA.Trying:if(e>=100&&e<=199)return this.stateTransition(iA.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=200&&e<=699)return this.stateTransition(iA.Completed),408===e?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(A));break;case iA.Proceeding:if(e>=100&&e<=199&&this.user.receiveResponse)return this.user.receiveResponse(A);if(e>=200&&e<=699)return this.stateTransition(iA.Completed),408===e?void this.onRequestTimeout():void(this.user.receiveResponse&&this.user.receiveResponse(A));break;case iA.Completed:case iA.Terminated:return;default:throw new Error(`Invalid state ${this.state}`)}const t=`Non-INVITE client transaction received unexpected ${e} response while in state ${this.state}.`;this.logger.warn(t)}onTransportError(A){this.user.onTransportError&&this.user.onTransportError(A),this.stateTransition(iA.Terminated,!0)}typeToString(){return"non-INVITE client transaction"}stateTransition(A,e=!1){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${A}`)};switch(A){case iA.Trying:t();break;case iA.Proceeding:this.state!==iA.Trying&&t();break;case iA.Completed:this.state!==iA.Trying&&this.state!==iA.Proceeding&&t();break;case iA.Terminated:this.state!==iA.Trying&&this.state!==iA.Proceeding&&this.state!==iA.Completed&&(e||t());break;default:t()}A===iA.Completed&&(this.F&&(clearTimeout(this.F),this.F=void 0),this.K=setTimeout(()=>this.timerK(),Z.TIMER_K)),A===iA.Terminated&&this.dispose(),this.setState(A)}timerF(){this.logger.debug(`Timer F expired for non-INVITE client transaction ${this.id}.`),this.state!==iA.Trying&&this.state!==iA.Proceeding||(this.onRequestTimeout(),this.stateTransition(iA.Terminated))}timerK(){this.state===iA.Completed&&this.stateTransition(iA.Terminated)}}class mA{constructor(A,e){this.core=A,this.dialogState=e,this.core.dialogs.set(this.id,this)}static initialDialogStateForUserAgentClient(A,e){const t=e.getHeaders("record-route").reverse(),s=e.parseHeader("contact");if(!s)throw new Error("Contact undefined.");if(!(s instanceof q))throw new Error("Contact not instance of NameAddrHeader.");const i=s.uri,n=A.cseq,o=A.callId,r=A.fromTag,a=e.toTag;if(!o)throw new Error("Call id undefined.");if(!r)throw new Error("From tag undefined.");if(!a)throw new Error("To tag undefined.");if(!A.from)throw new Error("From undefined.");if(!A.to)throw new Error("To undefined.");const V=A.from.uri,c=A.to.uri;if(!e.statusCode)throw new Error("Incoming response status code undefined.");return{id:o+r+a,early:e.statusCode<200,callId:o,localTag:r,remoteTag:a,localSequenceNumber:n,remoteSequenceNumber:undefined,localURI:V,remoteURI:c,remoteTarget:i,routeSet:t,secure:!1}}static initialDialogStateForUserAgentServer(A,e,t=!1){const s=A.getHeaders("record-route"),i=A.parseHeader("contact");if(!i)throw new Error("Contact undefined.");if(!(i instanceof q))throw new Error("Contact not instance of NameAddrHeader.");const n=i.uri,o=A.cseq,r=A.callId,a=e,V=A.fromTag,c=A.from.uri;return{id:r+a+V,early:t,callId:r,localTag:a,remoteTag:V,localSequenceNumber:undefined,remoteSequenceNumber:o,localURI:A.to.uri,remoteURI:c,remoteTarget:n,routeSet:s,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(A){if(A.method!==N.ACK){if(this.remoteSequenceNumber){if(A.cseq<=this.remoteSequenceNumber)throw new Error("Out of sequence in dialog request. Did you forget to call sequenceGuard()?");this.dialogState.remoteSequenceNumber=A.cseq}this.remoteSequenceNumber||(this.dialogState.remoteSequenceNumber=A.cseq)}}recomputeRouteSet(A){this.dialogState.routeSet=A.getHeaders("record-route").reverse()}createOutgoingRequestMessage(A,e){const t=this.remoteURI,s=this.remoteTag,i=this.localURI,n=this.localTag,o=this.callId;let r;r=e&&e.cseq?e.cseq:this.dialogState.localSequenceNumber?this.dialogState.localSequenceNumber+=1:this.dialogState.localSequenceNumber=1;const a=this.remoteTarget,V=this.routeSet,c=e&&e.extraHeaders,l=e&&e.body;return this.userAgentCore.makeOutgoingRequestMessage(A,a,i,t,{callId:o,cseq:r,fromTag:n,toTag:s,routeSet:V},c,l)}incrementLocalSequenceNumber(){if(!this.dialogState.localSequenceNumber)throw new Error("Local sequence number undefined.");this.dialogState.localSequenceNumber+=1}sequenceGuard(A){return A.method===N.ACK||(!(this.remoteSequenceNumber&&A.cseq<=this.remoteSequenceNumber)||(this.core.replyStateless(A,{statusCode:500}),!1))}}class EA extends pA{constructor(A,e,t){super(A,e,t,iA.Calling,"sip.transaction.ict"),this.ackRetransmissionCache=new Map,this.B=setTimeout(()=>this.timerB(),Z.TIMER_B),this.send(A.toString()).catch(A=>{this.logTransportError(A,"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(A){const e=A.toTag;if(!e)throw new Error("To tag undefined.");const t="z9hG4bK"+Math.floor(1e7*Math.random());A.setViaHeader(t,this.transport.protocol),this.ackRetransmissionCache.set(e,A),this.send(A.toString()).catch(A=>{this.logTransportError(A,"Failed to send ACK to 2xx response.")})}receiveResponse(A){const e=A.statusCode;if(!e||e<100||e>699)throw new Error(`Invalid status code ${e}`);switch(this.state){case iA.Calling:if(e>=100&&e<=199)return this.stateTransition(iA.Proceeding),void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=200&&e<=299)return this.ackRetransmissionCache.set(A.toTag,void 0),this.stateTransition(iA.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=300&&e<=699)return this.stateTransition(iA.Completed),this.ack(A),void(this.user.receiveResponse&&this.user.receiveResponse(A));break;case iA.Proceeding:if(e>=100&&e<=199)return void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=200&&e<=299)return this.ackRetransmissionCache.set(A.toTag,void 0),this.stateTransition(iA.Accepted),void(this.user.receiveResponse&&this.user.receiveResponse(A));if(e>=300&&e<=699)return this.stateTransition(iA.Completed),this.ack(A),void(this.user.receiveResponse&&this.user.receiveResponse(A));break;case iA.Accepted:if(e>=200&&e<=299){if(!this.ackRetransmissionCache.has(A.toTag))return this.ackRetransmissionCache.set(A.toTag,void 0),void(this.user.receiveResponse&&this.user.receiveResponse(A));const e=this.ackRetransmissionCache.get(A.toTag);return e?void this.send(e.toString()).catch(A=>{this.logTransportError(A,"Failed to send retransmission of ACK to 2xx response.")}):void 0}break;case iA.Completed:if(e>=300&&e<=699)return void this.ack(A);break;case iA.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const t=`Received unexpected ${e} response while in state ${this.state}.`;this.logger.warn(t)}onTransportError(A){this.user.onTransportError&&this.user.onTransportError(A),this.stateTransition(iA.Terminated,!0)}typeToString(){return"INVITE client transaction"}ack(A){const e=this.request.ruri,t=this.request.callId,s=this.request.cseq,i=this.request.getHeader("from"),n=A.getHeader("to"),o=this.request.getHeader("via"),r=this.request.getHeader("route");if(!i)throw new Error("From undefined.");if(!n)throw new Error("To undefined.");if(!o)throw new Error("Via undefined.");let a=`ACK ${e} SIP/2.0\r\n`;r&&(a+=`Route: ${r}\r\n`),a+=`Via: ${o}\r\n`,a+=`To: ${n}\r\n`,a+=`From: ${i}\r\n`,a+=`Call-ID: ${t}\r\n`,a+=`CSeq: ${s} ACK\r\n`,a+="Max-Forwards: 70\r\n",a+="Content-Length: 0\r\n\r\n",this.send(a).catch(A=>{this.logTransportError(A,"Failed to send ACK to non-2xx response.")})}stateTransition(A,e=!1){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${A}`)};switch(A){case iA.Calling:t();break;case iA.Proceeding:this.state!==iA.Calling&&t();break;case iA.Accepted:case iA.Completed:this.state!==iA.Calling&&this.state!==iA.Proceeding&&t();break;case iA.Terminated:this.state!==iA.Calling&&this.state!==iA.Accepted&&this.state!==iA.Completed&&(e||t());break;default:t()}this.B&&(clearTimeout(this.B),this.B=void 0),iA.Proceeding,A===iA.Completed&&(this.D=setTimeout(()=>this.timerD(),Z.TIMER_D)),A===iA.Accepted&&(this.M=setTimeout(()=>this.timerM(),Z.TIMER_M)),A===iA.Terminated&&this.dispose(),this.setState(A)}timerA(){}timerB(){this.logger.debug(`Timer B expired for INVITE client transaction ${this.id}.`),this.state===iA.Calling&&(this.onRequestTimeout(),this.stateTransition(iA.Terminated))}timerD(){this.logger.debug(`Timer D expired for INVITE client transaction ${this.id}.`),this.state===iA.Completed&&this.stateTransition(iA.Terminated)}timerM(){this.logger.debug(`Timer M expired for INVITE client transaction ${this.id}.`),this.state===iA.Accepted&&this.stateTransition(iA.Terminated)}}class CA{constructor(A,e,t,s){this.transactionConstructor=A,this.core=e,this.message=t,this.delegate=s,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(A,e={}){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 t=this.core.makeOutgoingRequestMessage(N.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},e.extraHeaders);return t.branch=this.message.branch,this.message.headers.Route&&(t.headers.Route=this.message.headers.Route),A&&t.setHeader("Reason",A),this.transaction.state===iA.Proceeding?new CA(uA,this.core,t):this.transaction.addStateChangeListener(()=>{this.transaction&&this.transaction.state===iA.Proceeding&&new CA(uA,this.core,t)},{once:!0}),t}authenticationGuard(A,e){const t=A.statusCode;if(!t)throw new Error("Response status code undefined.");if(401!==t&&407!==t)return!0;let s,i;if(401===t?(s=A.parseHeader("www-authenticate"),i="authorization"):(s=A.parseHeader("proxy-authenticate"),i="proxy-authorization"),!s)return this.logger.warn(t+" with wrong or missing challenge, cannot authenticate"),!0;if(this.challenged&&(this.stale||!0!==s.stale))return this.logger.warn(t+" 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,s))return!0;this.challenged=!0,s.stale&&(this.stale=!0);let n=this.message.cseq+=1;return e&&e.localSequenceNumber&&(e.incrementLocalSequenceNumber(),n=this.message.cseq=e.localSequenceNumber),this.message.setHeader("cseq",n+" "+this.message.method),this.message.setHeader(i,this.credentials.toString()),this.init(),!1}onRequestTimeout(){this.logger.warn("User agent client request timed out. Generating internal 408 Request Timeout.");const A=new y;A.statusCode=408,A.reasonPhrase="Request Timeout",this.receiveResponse(A)}onTransportError(A){this.logger.error(A.message),this.logger.error("User agent client request transport error. Generating internal 503 Service Unavailable.");const e=new y;e.statusCode=503,e.reasonPhrase="Service Unavailable",this.receiveResponse(e)}receiveResponse(A){if(!this.authenticationGuard(A))return;const e=A.statusCode?A.statusCode.toString():"";if(!e)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(e):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:A});break;case/^1[0-9]{2}$/.test(e):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:A});break;case/^2[0-9]{2}$/.test(e):this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:A});break;case/^3[0-9]{2}$/.test(e):this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:A});break;case/^[4-6][0-9]{2}$/.test(e):this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:A});break;default:throw new Error(`Invalid status code ${e}`)}}init(){const A={loggerFactory:this.loggerFactory,onRequestTimeout:()=>this.onRequestTimeout(),onStateChange:A=>{A===iA.Terminated&&(this.core.userAgentClients.delete(t),e===this._transaction&&this.dispose())},onTransportError:A=>this.onTransportError(A),receiveResponse:A=>this.receiveResponse(A)},e=new this.transactionConstructor(this.message,this.core.transport,A);this._transaction=e;const t=e.id+e.request.method;this.core.userAgentClients.set(t,this)}}class IA extends CA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.BYE,t);super(uA,A.userAgentCore,s,e),A.dispose()}}class MA extends qA{constructor(A,e,t){super(A,e,t,iA.Trying,"sip.transaction.nist")}dispose(){this.J&&(clearTimeout(this.J),this.J=void 0),super.dispose()}get kind(){return"nist"}receiveRequest(A){switch(this.state){case iA.Trying:break;case iA.Proceeding:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(A=>{this.logTransportError(A,"Failed to send retransmission of provisional response.")});break;case iA.Completed:if(!this.lastResponse)throw new Error("Last response undefined.");this.send(this.lastResponse).catch(A=>{this.logTransportError(A,"Failed to send retransmission of final response.")});break;case iA.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}}receiveResponse(A,e){if(A<100||A>699)throw new Error(`Invalid status code ${A}`);if(A>100&&A<=199)throw new Error("Provisional response other than 100 not allowed.");switch(this.state){case iA.Trying:if(this.lastResponse=e,A>=100&&A<200)return this.stateTransition(iA.Proceeding),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send provisional response.")});if(A>=200&&A<=699)return this.stateTransition(iA.Completed),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send final response.")});break;case iA.Proceeding:if(this.lastResponse=e,A>=200&&A<=699)return this.stateTransition(iA.Completed),void this.send(e).catch(A=>{this.logTransportError(A,"Failed to send final response.")});break;case iA.Completed:return;case iA.Terminated:break;default:throw new Error(`Invalid state ${this.state}`)}const t=`Non-INVITE server transaction received unexpected ${A} response from TU while in state ${this.state}.`;throw this.logger.error(t),new Error(t)}onTransportError(A){this.user.onTransportError&&this.user.onTransportError(A),this.stateTransition(iA.Terminated,!0)}typeToString(){return"non-INVITE server transaction"}stateTransition(A,e=!1){const t=()=>{throw new Error(`Invalid state transition from ${this.state} to ${A}`)};switch(A){case iA.Trying:t();break;case iA.Proceeding:this.state!==iA.Trying&&t();break;case iA.Completed:this.state!==iA.Trying&&this.state!==iA.Proceeding&&t();break;case iA.Terminated:this.state!==iA.Proceeding&&this.state!==iA.Completed&&(e||t());break;default:t()}A===iA.Completed&&(this.J=setTimeout(()=>this.timerJ(),Z.TIMER_J)),A===iA.Terminated&&this.dispose(),this.setState(A)}timerJ(){this.logger.debug(`Timer J expired for NON-INVITE server transaction ${this.id}.`),this.state===iA.Completed&&this.stateTransition(iA.Terminated)}}class wA{constructor(A,e,t,s){this.transactionConstructor=A,this.core=e,this.message=t,this.delegate=s,this.logger=this.loggerFactory.getLogger("sip.user-agent-server"),this.toTag=t.toTag?t.toTag:f(),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(A={statusCode:200}){if(!this.acceptable)throw new O(`${this.message.method} not acceptable in state ${this.transaction.state}.`);const e=A.statusCode;if(e<200||e>299)throw new TypeError(`Invalid statusCode: ${e}`);return this.reply(A)}progress(A={statusCode:180}){if(!this.progressable)throw new O(`${this.message.method} not progressable in state ${this.transaction.state}.`);const e=A.statusCode;if(e<101||e>199)throw new TypeError(`Invalid statusCode: ${e}`);return this.reply(A)}redirect(A,e={statusCode:302}){if(!this.redirectable)throw new O(`${this.message.method} not redirectable in state ${this.transaction.state}.`);const t=e.statusCode;if(t<300||t>399)throw new TypeError(`Invalid statusCode: ${t}`);const s=new Array;A.forEach(A=>s.push(`Contact: ${A.toString()}`)),e.extraHeaders=(e.extraHeaders||[]).concat(s);return this.reply(e)}reject(A={statusCode:480}){if(!this.rejectable)throw new O(`${this.message.method} not rejectable in state ${this.transaction.state}.`);const e=A.statusCode;if(e<400||e>699)throw new TypeError(`Invalid statusCode: ${e}`);return this.reply(A)}trying(A){if(!this.tryingable)throw new O(`${this.message.method} not tryingable in state ${this.transaction.state}.`);return this.reply({statusCode:100})}receiveCancel(A){this.delegate&&this.delegate.onCancel&&this.delegate.onCancel(A)}get acceptable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding||this.transaction.state===iA.Accepted;if(this.transaction instanceof MA)return this.transaction.state===iA.Trying||this.transaction.state===iA.Proceeding;throw new Error("Unknown transaction type.")}get progressable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding;if(this.transaction instanceof MA)return!1;throw new Error("Unknown transaction type.")}get redirectable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding;if(this.transaction instanceof MA)return this.transaction.state===iA.Trying||this.transaction.state===iA.Proceeding;throw new Error("Unknown transaction type.")}get rejectable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding;if(this.transaction instanceof MA)return this.transaction.state===iA.Trying||this.transaction.state===iA.Proceeding;throw new Error("Unknown transaction type.")}get tryingable(){if(this.transaction instanceof dA)return this.transaction.state===iA.Proceeding;if(this.transaction instanceof MA)return this.transaction.state===iA.Trying;throw new Error("Unknown transaction type.")}reply(A){A.toTag||100===A.statusCode||(A.toTag=this.toTag),A.userAgent=A.userAgent||this.core.configuration.userAgentHeaderFieldValue,A.supported=A.supported||this.core.configuration.supportedOptionTagsResponse;const e=lA(this.message,A);return this.transaction.receiveResponse(A.statusCode,e.message),e}init(){const A={loggerFactory:this.loggerFactory,onStateChange:A=>{A===iA.Terminated&&(this.core.userAgentServers.delete(t),this.dispose())},onTransportError:A=>{this.logger.error(A.message),this.delegate&&this.delegate.onTransportError?this.delegate.onTransportError(A):this.logger.error("User agent server response transport error.")}},e=new this.transactionConstructor(this.message,this.core.transport,A);this._transaction=e;const t=e.id;this.core.userAgentServers.set(e.id,this)}}class fA extends wA{constructor(A,e,t){super(MA,A.userAgentCore,e,t)}}class BA extends CA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.INFO,t);super(uA,A.userAgentCore,s,e)}}class SA extends wA{constructor(A,e,t){super(MA,A.userAgentCore,e,t)}}class QA extends CA{constructor(A,e,t){super(uA,A,e,t)}}class TA extends wA{constructor(A,e,t){super(MA,A,e,t)}}class yA extends CA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.NOTIFY,t);super(uA,A.userAgentCore,s,e)}}class DA extends wA{constructor(A,e,t){const s=void 0!==A.userAgentCore?A.userAgentCore:A;super(MA,s,e,t)}}class RA extends CA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.PRACK,t);super(uA,A.userAgentCore,s,e),A.signalingStateTransition(s)}}class UA extends wA{constructor(A,e,t){super(MA,A.userAgentCore,e,t),A.signalingStateTransition(e),this.dialog=A}accept(A={statusCode:200}){return A.body&&this.dialog.signalingStateTransition(A.body),super.accept(A)}}class kA extends CA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.INVITE,t);super(EA,A.userAgentCore,s,e),this.delegate=e,A.signalingStateTransition(s),A.reinviteUserAgentClient=this,this.dialog=A}receiveResponse(A){if(!this.authenticationGuard(A,this.dialog))return;const e=A.statusCode?A.statusCode.toString():"";if(!e)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(e):this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:A});break;case/^1[0-9]{2}$/.test(e):this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:A,session:this.dialog,prack:A=>{throw new Error("Unimplemented.")}});break;case/^2[0-9]{2}$/.test(e):this.dialog.signalingStateTransition(A),this.delegate&&this.delegate.onAccept&&this.delegate.onAccept({message:A,session:this.dialog,ack:A=>this.dialog.ack(A)});break;case/^3[0-9]{2}$/.test(e):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:A});break;case/^[4-6][0-9]{2}$/.test(e):this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentClient=void 0,this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:A});break;default:throw new Error(`Invalid status code ${e}`)}}}class GA extends wA{constructor(A,e,t){super(dA,A.userAgentCore,e,t),A.reinviteUserAgentServer=this,this.dialog=A}accept(A={statusCode:200}){A.extraHeaders=A.extraHeaders||[],A.extraHeaders=A.extraHeaders.concat(this.dialog.routeSet.map(A=>`Record-Route: ${A}`));const e=super.accept(A),t=this.dialog,s=Object.assign(Object.assign({},e),{session:t});return A.body&&this.dialog.signalingStateTransition(A.body),this.dialog.reConfirm(),s}progress(A={statusCode:180}){const e=super.progress(A),t=this.dialog,s=Object.assign(Object.assign({},e),{session:t});return A.body&&this.dialog.signalingStateTransition(A.body),s}redirect(A,e={statusCode:302}){throw this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,new Error("Unimplemented.")}reject(A={statusCode:488}){return this.dialog.signalingStateRollback(),this.dialog.reinviteUserAgentServer=void 0,super.reject(A)}}class FA extends CA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.REFER,t);super(uA,A.userAgentCore,s,e)}}class YA extends wA{constructor(A,e,t){const s=void 0!==A.userAgentCore?A.userAgentCore:A;super(MA,s,e,t)}}class xA extends mA{constructor(A,e,t,s){super(e,t),this.initialTransaction=A,this._signalingState=Y.Initial,this.ackWait=!1,this.ackProcessing=!1,this.delegate=s,A instanceof dA&&(this.ackWait=!0),this.early||this.start2xxRetransmissionTimer(),this.signalingStateTransition(A.request),this.logger=e.loggerFactory.getLogger("sip.invite-dialog"),this.logger.log(`INVITE dialog ${this.id} constructed`)}dispose(){super.dispose(),this._signalingState=Y.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?F.Early:this.ackWait?F.AckWait:this._signalingState===Y.Closed?F.Terminated:F.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(A={}){let e;if(this.logger.log(`INVITE dialog ${this.id} sending ACK request`),this.reinviteUserAgentClient){if(!(this.reinviteUserAgentClient.transaction instanceof EA))throw new Error("Transaction not instance of InviteClientTransaction.");e=this.reinviteUserAgentClient.transaction,this.reinviteUserAgentClient=void 0}else{if(!(this.initialTransaction instanceof EA))throw new Error("Initial transaction not instance of InviteClientTransaction.");e=this.initialTransaction}const t=this.createOutgoingRequestMessage(N.ACK,{cseq:e.request.cseq,extraHeaders:A.extraHeaders,body:A.body});return e.ackResponse(t),this.signalingStateTransition(t),{message:t}}bye(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending BYE request`),this.initialTransaction instanceof dA){if(this.early)throw new Error("UAS MUST NOT send a BYE on early dialogs.");if(this.ackWait&&this.initialTransaction.state!==iA.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 IA(this,A,e)}info(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending INFO request`),this.early)throw new Error("Dialog not confirmed.");return new BA(this,A,e)}invite(A,e){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 kA(this,A,e)}message(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending MESSAGE request`),this.early)throw new Error("Dialog not confirmed.");const t=this.createOutgoingRequestMessage(N.MESSAGE,e);return new QA(this.core,t,A)}notify(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending NOTIFY request`),this.early)throw new Error("Dialog not confirmed.");return new yA(this,A,e)}prack(A,e){return this.logger.log(`INVITE dialog ${this.id} sending PRACK request`),new RA(this,A,e)}refer(A,e){if(this.logger.log(`INVITE dialog ${this.id} sending REFER request`),this.early)throw new Error("Dialog not confirmed.");return new FA(this,A,e)}receiveRequest(A){if(this.logger.log(`INVITE dialog ${this.id} received ${A.method} request`),A.method!==N.ACK)if(this.sequenceGuard(A)){if(super.receiveRequest(A),A.method===N.INVITE){const e=()=>{const A=this.ackWait?"waiting for initial ACK":"processing initial ACK";this.logger.warn(`INVITE dialog ${this.id} received re-INVITE while ${A}`);let e="RFC 5407 suggests the following to avoid this race condition... ";e+=" Note: Implementation issues are outside the scope of this document,",e+=" but the following tip is provided for avoiding race conditions of",e+=" this type. The caller can delay sending re-INVITE F6 for some period",e+=" of time (2 seconds, perhaps), after which the caller can reasonably",e+=" assume that its ACK has been received. Implementors can decouple the",e+=" actions of the user (e.g., pressing the hold button) from the actions",e+=" of the protocol (the sending of re-INVITE F6), so that the UA can",e+=" behave like this. In this case, it is the implementor's choice as to",e+=" how long to wait. In most cases, such an implementation may be",e+=" useful to prevent the type of race condition shown in this section.",e+=" This document expresses no preference about whether or not they",e+=" should wait for an ACK to be delivered. After considering the impact",e+=" on user experience, implementors should decide whether or not to wait",e+=" for a while, because the user experience depends on the",e+=" 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.")},t=[`Retry-After: ${Math.floor(10*Math.random())+1}`];if(this.ackProcessing)return this.core.replyStateless(A,{statusCode:500,extraHeaders:t}),void e();if(this.ackWait&&this.signalingState!==Y.Stable)return this.core.replyStateless(A,{statusCode:500,extraHeaders:t}),void e();if(this.reinviteUserAgentServer)return void this.core.replyStateless(A,{statusCode:500,extraHeaders:t});if(this.reinviteUserAgentClient)return void this.core.replyStateless(A,{statusCode:491})}if(A.method===N.INVITE){const e=A.parseHeader("contact");if(!e)throw new Error("Contact undefined.");if(!(e instanceof q))throw new Error("Contact not instance of NameAddrHeader.");this.dialogState.remoteTarget=e.uri}switch(A.method){case N.BYE:{const e=new fA(this,A);this.delegate&&this.delegate.onBye?this.delegate.onBye(e):e.accept(),this.dispose()}break;case N.INFO:{const e=new SA(this,A);this.delegate&&this.delegate.onInfo?this.delegate.onInfo(e):e.reject({statusCode:469,extraHeaders:["Recv-Info:"]})}break;case N.INVITE:{const e=new GA(this,A);this.signalingStateTransition(A),this.delegate&&this.delegate.onInvite?this.delegate.onInvite(e):e.reject({statusCode:488})}break;case N.MESSAGE:{const e=new TA(this.core,A);this.delegate&&this.delegate.onMessage?this.delegate.onMessage(e):e.accept()}break;case N.NOTIFY:{const e=new DA(this,A);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(e):e.accept()}break;case N.PRACK:{const e=new UA(this,A);this.delegate&&this.delegate.onPrack?this.delegate.onPrack(e):e.accept()}break;case N.REFER:{const e=new YA(this,A);this.delegate&&this.delegate.onRefer?this.delegate.onRefer(e):e.reject()}break;default:this.logger.log(`INVITE dialog ${this.id} received unimplemented ${A.method} request`),this.core.replyStateless(A,{statusCode:501})}}else this.logger.log(`INVITE dialog ${this.id} rejected out of order ${A.method} request.`);else{if(this.ackWait){if(this.initialTransaction instanceof EA)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${A.method} request, dropping.`);if(this.initialTransaction.request.cseq!==A.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${A.method} request, dropping.`);this.ackWait=!1}else{if(!this.reinviteUserAgentServer)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${A.method} request, dropping.`);if(this.reinviteUserAgentServer.transaction.request.cseq!==A.cseq)return void this.logger.warn(`INVITE dialog ${this.id} received unexpected ${A.method} request, dropping.`);this.reinviteUserAgentServer=void 0}if(this.signalingStateTransition(A),this.delegate&&this.delegate.onAck){const e=this.delegate.onAck({message:A});e instanceof Promise&&(this.ackProcessing=!0,e.then(()=>this.ackProcessing=!1).catch(()=>this.ackProcessing=!1))}}}reliableSequenceGuard(A){const e=A.statusCode;if(!e)throw new Error("Status code undefined");if(e>100&&e<200){const e=A.getHeader("require"),t=A.getHeader("rseq"),s=e&&e.includes("100rel")&&t?Number(t):void 0;if(s){if(this.rseq&&this.rseq+1!==s)return!1;this.rseq=this.rseq?this.rseq+1:s}}return!0}signalingStateRollback(){this._signalingState!==Y.HaveLocalOffer&&this.signalingState!==Y.HaveRemoteOffer||this._rollbackOffer&&this._rollbackAnswer&&(this._signalingState=Y.Stable,this._offer=this._rollbackOffer,this._answer=this._rollbackAnswer)}signalingStateTransition(A){const e=G(A);if(e&&"session"===e.contentDisposition){if(this._signalingState===Y.Stable&&(this._rollbackOffer=this._offer,this._rollbackAnswer=this._answer),A instanceof T)switch(this._signalingState){case Y.Initial:case Y.Stable:this._signalingState=Y.HaveRemoteOffer,this._offer=e,this._answer=void 0;break;case Y.HaveLocalOffer:this._signalingState=Y.Stable,this._answer=e;break;case Y.HaveRemoteOffer:case Y.Closed:break;default:throw new Error("Unexpected signaling state.")}if(A instanceof y)switch(this._signalingState){case Y.Initial:case Y.Stable:this._signalingState=Y.HaveRemoteOffer,this._offer=e,this._answer=void 0;break;case Y.HaveLocalOffer:this._signalingState=Y.Stable,this._answer=e;break;case Y.HaveRemoteOffer:case Y.Closed:break;default:throw new Error("Unexpected signaling state.")}if(A instanceof D)switch(this._signalingState){case Y.Initial:case Y.Stable:this._signalingState=Y.HaveLocalOffer,this._offer=e,this._answer=void 0;break;case Y.HaveLocalOffer:break;case Y.HaveRemoteOffer:this._signalingState=Y.Stable,this._answer=e;break;case Y.Closed:break;default:throw new Error("Unexpected signaling state.")}if(k(A))switch(this._signalingState){case Y.Initial:case Y.Stable:this._signalingState=Y.HaveLocalOffer,this._offer=e,this._answer=void 0;break;case Y.HaveLocalOffer:break;case Y.HaveRemoteOffer:this._signalingState=Y.Stable,this._answer=e;break;case Y.Closed:break;default:throw new Error("Unexpected signaling state.")}}}start2xxRetransmissionTimer(){if(this.initialTransaction instanceof dA){const A=this.initialTransaction;let e=Z.T1;const t=()=>{this.ackWait?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),A.retransmitAcceptedResponse(),e=Math.min(2*e,Z.T2),this.invite2xxTimer=setTimeout(t,e)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(t,e);const s=()=>{A.state===iA.Terminated&&(A.removeStateChangeListener(s),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.ackWait&&(this.delegate&&this.delegate.onAckTimeout?this.delegate.onAckTimeout():this.bye()))};A.addStateChangeListener(s)}}startReInvite2xxRetransmissionTimer(){if(this.reinviteUserAgentServer&&this.reinviteUserAgentServer.transaction instanceof dA){const A=this.reinviteUserAgentServer.transaction;let e=Z.T1;const t=()=>{this.reinviteUserAgentServer?(this.logger.log("No ACK for 2xx response received, attempting retransmission"),A.retransmitAcceptedResponse(),e=Math.min(2*e,Z.T2),this.invite2xxTimer=setTimeout(t,e)):this.invite2xxTimer=void 0};this.invite2xxTimer=setTimeout(t,e);const s=()=>{A.state===iA.Terminated&&(A.removeStateChangeListener(s),this.invite2xxTimer&&(clearTimeout(this.invite2xxTimer),this.invite2xxTimer=void 0),this.reinviteUserAgentServer)};A.addStateChangeListener(s)}}}class vA extends CA{constructor(A,e,t){super(EA,A,e,t),this.confirmedDialogAcks=new Map,this.confirmedDialogs=new Map,this.earlyDialogs=new Map,this.delegate=t}dispose(){this.earlyDialogs.forEach(A=>A.dispose()),this.earlyDialogs.clear(),super.dispose()}onTransportError(A){if(this.transaction.state===iA.Calling)return super.onTransportError(A);this.logger.error(A.message),this.logger.error("User agent client request transport error while sending ACK.")}receiveResponse(A){if(!this.authenticationGuard(A))return;const e=A.statusCode?A.statusCode.toString():"";if(!e)throw new Error("Response status code undefined.");switch(!0){case/^100$/.test(e):return void(this.delegate&&this.delegate.onTrying&&this.delegate.onTrying({message:A}));case/^1[0-9]{2}$/.test(e):{if(!A.toTag)return void this.logger.warn("Non-100 1xx INVITE response received without a to tag, dropping.");if(!A.parseHeader("contact"))return void this.logger.error("Non-100 1xx INVITE response received without a Contact header field, dropping.");const e=mA.initialDialogStateForUserAgentClient(this.message,A);let t=this.earlyDialogs.get(e.id);if(!t){const A=this.transaction;if(!(A instanceof EA))throw new Error("Transaction not instance of InviteClientTransaction.");t=new xA(A,this.core,e),this.earlyDialogs.set(t.id,t)}if(!t.reliableSequenceGuard(A))return void this.logger.warn("1xx INVITE reliable response received out of order or is a retransmission, dropping.");t.signalingState!==Y.Initial&&t.signalingState!==Y.HaveLocalOffer||t.signalingStateTransition(A);const s=t;this.delegate&&this.delegate.onProgress&&this.delegate.onProgress({message:A,session:s,prack:A=>s.prack(void 0,A)})}return;case/^2[0-9]{2}$/.test(e):{if(!A.toTag)return void this.logger.error("2xx INVITE response received without a to tag, dropping.");if(!A.parseHeader("contact"))return void this.logger.error("2xx INVITE response received without a Contact header field, dropping.");const e=mA.initialDialogStateForUserAgentClient(this.message,A);let t=this.confirmedDialogs.get(e.id);if(t){const A=this.confirmedDialogAcks.get(e.id);if(A){const e=this.transaction;if(!(e instanceof EA))throw new Error("Client transaction not instance of InviteClientTransaction.");e.ackResponse(A.message)}return}if(t=this.earlyDialogs.get(e.id),t)t.confirm(),t.recomputeRouteSet(A),this.earlyDialogs.delete(t.id),this.confirmedDialogs.set(t.id,t);else{const A=this.transaction;if(!(A instanceof EA))throw new Error("Transaction not instance of InviteClientTransaction.");t=new xA(A,this.core,e),this.confirmedDialogs.set(t.id,t)}t.signalingState!==Y.Initial&&t.signalingState!==Y.HaveLocalOffer||t.signalingStateTransition(A);const s=t;if(this.delegate&&this.delegate.onAccept)this.delegate.onAccept({message:A,session:s,ack:A=>{const e=s.ack(A);return this.confirmedDialogAcks.set(s.id,e),e}});else{const A=s.ack();this.confirmedDialogAcks.set(s.id,A)}}return;case/^3[0-9]{2}$/.test(e):return this.earlyDialogs.forEach(A=>A.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onRedirect&&this.delegate.onRedirect({message:A}));case/^[4-6][0-9]{2}$/.test(e):return this.earlyDialogs.forEach(A=>A.dispose()),this.earlyDialogs.clear(),void(this.delegate&&this.delegate.onReject&&this.delegate.onReject({message:A}));default:throw new Error(`Invalid status code ${e}`)}}}class ZA extends wA{constructor(A,e,t){super(dA,A,e,t),this.core=A}dispose(){this.earlyDialog&&this.earlyDialog.dispose(),super.dispose()}accept(A={statusCode:200}){if(!this.acceptable)throw new O(`${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 A=this.transaction;if(!(A instanceof dA))throw new Error("Transaction not instance of InviteClientTransaction.");const e=mA.initialDialogStateForUserAgentServer(this.message,this.toTag);this.confirmedDialog=new xA(A,this.core,e)}const e=this.message.getHeaders("record-route").map(A=>`Record-Route: ${A}`),t=`Contact: ${this.core.configuration.contact.toString()}`,s="Allow: "+K.toString();if(!A.body)if(this.confirmedDialog.signalingState===Y.Stable)A.body=this.confirmedDialog.answer;else if(this.confirmedDialog.signalingState===Y.Initial||this.confirmedDialog.signalingState===Y.HaveRemoteOffer)throw new Error("Response must have a body.");A.statusCode=A.statusCode||200,A.extraHeaders=A.extraHeaders||[],A.extraHeaders=A.extraHeaders.concat(e),A.extraHeaders.push(s),A.extraHeaders.push(t);const i=super.accept(A),n=this.confirmedDialog,o=Object.assign(Object.assign({},i),{session:n});return A.body&&this.confirmedDialog.signalingState!==Y.Stable&&this.confirmedDialog.signalingStateTransition(A.body),o}progress(A={statusCode:180}){if(!this.progressable)throw new O(`${this.message.method} not progressable in state ${this.transaction.state}.`);if(!this.earlyDialog){const A=this.transaction;if(!(A instanceof dA))throw new Error("Transaction not instance of InviteClientTransaction.");const e=mA.initialDialogStateForUserAgentServer(this.message,this.toTag,!0);this.earlyDialog=new xA(A,this.core,e)}const e=this.message.getHeaders("record-route").map(A=>`Record-Route: ${A}`),t=`Contact: ${this.core.configuration.contact}`;A.extraHeaders=A.extraHeaders||[],A.extraHeaders=A.extraHeaders.concat(e),A.extraHeaders.push(t);const s=super.progress(A),i=this.earlyDialog,n=Object.assign(Object.assign({},s),{session:i});return A.body&&this.earlyDialog.signalingState!==Y.Stable&&this.earlyDialog.signalingStateTransition(A.body),n}redirect(A,e={statusCode:302}){return super.redirect(A,e)}reject(A={statusCode:486}){return super.reject(A)}}class OA extends CA{constructor(A,e,t){super(uA,A,e,t)}}class NA extends CA{constructor(A,e,t){super(uA,A,e,t)}}class KA extends wA{constructor(A,e,t){super(MA,A,e,t),this.core=A}}class bA extends CA{constructor(A,e,t){const s=A.createOutgoingRequestMessage(N.SUBSCRIBE,t);super(uA,A.userAgentCore,s,e),this.dialog=A}waitNotifyStop(){}receiveResponse(A){if(A.statusCode&&A.statusCode>=200&&A.statusCode<300){const e=A.getHeader("Expires");if(e){const A=Number(e);this.dialog.subscriptionExpires>A&&(this.dialog.subscriptionExpires=A)}else this.logger.warn("Expires header missing in a 200-class response to SUBSCRIBE")}if(A.statusCode&&A.statusCode>=400&&A.statusCode<700){[404,405,410,416,480,481,482,483,484,485,489,501,604].includes(A.statusCode)&&this.dialog.terminate()}super.receiveResponse(A)}}class JA extends mA{constructor(A,e,t,s,i,n){super(s,i),this.delegate=n,this._autoRefresh=!1,this._subscriptionEvent=A,this._subscriptionExpires=e,this._subscriptionExpiresInitial=e,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this._subscriptionRefresh=void 0,this._subscriptionRefreshLastSet=void 0,this._subscriptionState=t,this.logger=s.loggerFactory.getLogger("sip.subscribe-dialog"),this.logger.log(`SUBSCRIBE dialog ${this.id} constructed`)}static initialDialogStateForSubscription(A,e){const t=e.getHeaders("record-route"),s=e.parseHeader("contact");if(!s)throw new Error("Contact undefined.");if(!(s instanceof q))throw new Error("Contact not instance of NameAddrHeader.");const i=s.uri,n=A.cseq,o=A.callId,r=A.fromTag,a=e.fromTag;if(!o)throw new Error("Call id undefined.");if(!r)throw new Error("From tag undefined.");if(!a)throw new Error("To tag undefined.");if(!A.from)throw new Error("From undefined.");if(!A.to)throw new Error("To undefined.");return{id:o+r+a,early:!1,callId:o,localTag:r,remoteTag:a,localSequenceNumber:n,remoteSequenceNumber:undefined,localURI:A.from.uri,remoteURI:A.to.uri,remoteTarget:i,routeSet:t,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(A){this._autoRefresh=!0,this.refreshTimerSet()}get subscriptionEvent(){return this._subscriptionEvent}get subscriptionExpires(){const A=Math.floor(Date.now()/1e3)-this._subscriptionExpiresLastSet,e=this._subscriptionExpires-A;return Math.max(e,0)}set subscriptionExpires(A){if(A<0)throw new Error("Expires must be greater than or equal to zero.");if(this._subscriptionExpires=A,this._subscriptionExpiresLastSet=Math.floor(Date.now()/1e3),this.autoRefresh){const e=this.subscriptionRefresh;(void 0===e||e>=A)&&this.refreshTimerSet()}}get subscriptionExpiresInitial(){return this._subscriptionExpiresInitial}get subscriptionRefresh(){if(void 0===this._subscriptionRefresh||void 0===this._subscriptionRefreshLastSet)return;const A=Math.floor(Date.now()/1e3)-this._subscriptionRefreshLastSet,e=this._subscriptionRefresh-A;return Math.max(e,0)}get subscriptionState(){return this._subscriptionState}receiveRequest(A){if(this.logger.log(`SUBSCRIBE dialog ${this.id} received ${A.method} request`),this.sequenceGuard(A))if(super.receiveRequest(A),A.method===N.NOTIFY)this.onNotify(A);else this.logger.log(`SUBSCRIBE dialog ${this.id} received unimplemented ${A.method} request`),this.core.replyStateless(A,{statusCode:501});else this.logger.log(`SUBSCRIBE dialog ${this.id} rejected out of order ${A.method} request.`)}refresh(){const A="Allow: "+K.toString(),e={};return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push(A),e.extraHeaders.push("Event: "+this.subscriptionEvent),e.extraHeaders.push("Expires: "+this.subscriptionExpiresInitial),e.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,e)}subscribe(A,e={}){var t;if(this.subscriptionState!==$.Pending&&this.subscriptionState!==$.Active)throw new Error(`Invalid state ${this.subscriptionState}. May only re-subscribe while in state "pending" or "active".`);this.logger.log(`SUBSCRIBE dialog ${this.id} sending SUBSCRIBE request`);const s=new bA(this,A,e);return this.N&&(clearTimeout(this.N),this.N=void 0),(null===(t=e.extraHeaders)||void 0===t?void 0:t.includes("Expires: 0"))||(this.N=setTimeout(()=>this.timerN(),Z.TIMER_N)),s}terminate(){this.stateTransition($.Terminated),this.onTerminated()}unsubscribe(){const A="Allow: "+K.toString(),e={};return e.extraHeaders=(e.extraHeaders||[]).slice(),e.extraHeaders.push(A),e.extraHeaders.push("Event: "+this.subscriptionEvent),e.extraHeaders.push("Expires: 0"),e.extraHeaders.push("Contact: "+this.core.configuration.contact.toString()),this.subscribe(void 0,e)}onNotify(A){const e=A.parseHeader("Event").event;if(!e||e!==this.subscriptionEvent)return void this.core.replyStateless(A,{statusCode:489});this.N&&(clearTimeout(this.N),this.N=void 0);const t=A.parseHeader("Subscription-State");if(!t||!t.state)return void this.core.replyStateless(A,{statusCode:489});const s=t.state,i=t.expires?Math.max(t.expires,0):void 0;switch(s){case"pending":this.stateTransition($.Pending,i);break;case"active":this.stateTransition($.Active,i);break;case"terminated":this.stateTransition($.Terminated,i);break;default:this.logger.warn("Unrecognized subscription state.")}const n=new DA(this,A);this.delegate&&this.delegate.onNotify?this.delegate.onNotify(n):n.accept()}onRefresh(A){this.delegate&&this.delegate.onRefresh&&this.delegate.onRefresh(A)}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 A=900*this.subscriptionExpires;this._subscriptionRefresh=Math.floor(A/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())},A)}}stateTransition(A,e){const t=()=>{this.logger.warn(`Invalid subscription state transition from ${this.subscriptionState} to ${A}`)};switch(A){case $.Initial:case $.NotifyWait:return void t();case $.Pending:if(this.subscriptionState!==$.NotifyWait&&this.subscriptionState!==$.Pending)return void t();break;case $.Active:case $.Terminated:if(this.subscriptionState!==$.NotifyWait&&this.subscriptionState!==$.Pending&&this.subscriptionState!==$.Active)return void t();break;default:return void t()}A===$.Pending&&e&&(this.subscriptionExpires=e),A===$.Active&&e&&(this.subscriptionExpires=e),A===$.Terminated&&this.dispose(),this._subscriptionState=A}timerN(){this.logger.warn("Timer N expired for SUBSCRIBE dialog. Timed out waiting for NOTIFY."),this.subscriptionState!==$.Terminated&&(this.stateTransition($.Terminated),this.onTerminated())}}class LA extends CA{constructor(A,e,t){const s=e.getHeader("Event");if(!s)throw new Error("Event undefined");const i=e.getHeader("Expires");if(!i)throw new Error("Expires undefined");super(uA,A,e,t),this.delegate=t,this.subscriberId=e.callId+e.fromTag+s,this.subscriptionExpiresRequested=this.subscriptionExpires=Number(i),this.subscriptionEvent=s,this.subscriptionState=$.NotifyWait,this.waitNotifyStart()}dispose(){super.dispose()}onNotify(A){const e=A.message.parseHeader("Event").event;if(!e||e!==this.subscriptionEvent)return this.logger.warn("Failed to parse event."),void A.reject({statusCode:489});const t=A.message.parseHeader("Subscription-State");if(!t||!t.state)return this.logger.warn("Failed to parse subscription state."),void A.reject({statusCode:489});const s=t.state;switch(s){case"pending":case"active":case"terminated":break;default:return this.logger.warn(`Invalid subscription state ${s}`),void A.reject({statusCode:489})}if("terminated"!==s){if(!A.message.parseHeader("contact"))return this.logger.warn("Failed to parse contact."),void A.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=t.expires?Math.min(this.subscriptionExpires,Math.max(t.expires,0)):this.subscriptionExpires,s){case"pending":this.subscriptionState=$.Pending;break;case"active":this.subscriptionState=$.Active;break;case"terminated":this.subscriptionState=$.Terminated;break;default:throw new Error(`Unrecognized state ${s}.`)}if(this.subscriptionState!==$.Terminated){const e=JA.initialDialogStateForSubscription(this.message,A.message);this.dialog=new JA(this.subscriptionEvent,this.subscriptionExpires,this.subscriptionState,this.core,e)}if(this.delegate&&this.delegate.onNotify){const e=A,t=this.dialog;this.delegate.onNotify({request:e,subscription:t})}else A.accept()}waitNotifyStart(){this.N||(this.core.subscribers.set(this.subscriberId,this),this.N=setTimeout(()=>this.timerN(),Z.TIMER_N))}waitNotifyStop(){this.N&&(this.core.subscribers.delete(this.subscriberId),clearTimeout(this.N),this.N=void 0)}receiveResponse(A){if(this.authenticationGuard(A)){if(A.statusCode&&A.statusCode>=200&&A.statusCode<300){const e=A.getHeader("Expires");if(e){const A=Number(e);A>this.subscriptionExpiresRequested&&this.logger.warn("Expires header in a 200-class response to SUBSCRIBE with a higher value than the one in the request"),A<this.subscriptionExpires&&(this.subscriptionExpires=A)}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)}A.statusCode&&A.statusCode>=300&&A.statusCode<700&&this.waitNotifyStop(),super.receiveResponse(A)}}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 HA extends wA{constructor(A,e,t){super(MA,A,e,t),this.core=A}}const jA=["application/sdp","application/dtmf-relay"];class WA{constructor(A,e={}){this.userAgentClients=new Map,this.userAgentServers=new Map,this.configuration=A,this.delegate=e,this.dialogs=new Map,this.subscribers=new Map,this.logger=A.loggerFactory.getLogger("sip.user-agent-core")}dispose(){this.reset()}reset(){this.dialogs.forEach(A=>A.dispose()),this.dialogs.clear(),this.subscribers.forEach(A=>A.dispose()),this.subscribers.clear(),this.userAgentClients.forEach(A=>A.dispose()),this.userAgentClients.clear(),this.userAgentServers.forEach(A=>A.dispose()),this.userAgentServers.clear()}get loggerFactory(){return this.configuration.loggerFactory}get transport(){const A=this.configuration.transportAccessor();if(!A)throw new Error("Transport undefined.");return A}invite(A,e){return new vA(this,A,e)}message(A,e){return new QA(this,A,e)}publish(A,e){return new OA(this,A,e)}register(A,e){return new NA(this,A,e)}subscribe(A,e){return new LA(this,A,e)}request(A,e){return new CA(uA,this,A,e)}makeOutgoingRequestMessage(A,e,t,s,i,n,o){const r=this.configuration.sipjsId,a=this.configuration.displayName,V=this.configuration.viaForceRport,c=this.configuration.hackViaTcp,l=this.configuration.supportedOptionTags.slice();A===N.REGISTER&&l.push("path","gruu"),A===N.INVITE&&(this.configuration.contact.pubGruu||this.configuration.contact.tempGruu)&&l.push("gruu");const h={callIdPrefix:r,forceRport:V,fromDisplayName:a,hackViaTcp:c,optionTags:l,routeSet:this.configuration.routeSet,userAgentString:this.configuration.userAgentHeaderFieldValue,viaHost:this.configuration.viaHost},g=Object.assign(Object.assign({},h),i);return new D(A,e,t,s,g,n,o)}receiveIncomingRequestFromTransport(A){this.receiveRequestFromTransport(A)}receiveIncomingResponseFromTransport(A){this.receiveResponseFromTransport(A)}replyStateless(A,e){const t=this.configuration.userAgentHeaderFieldValue,s=this.configuration.supportedOptionTagsResponse;e=Object.assign(Object.assign({},e),{userAgent:t,supported:s});const i=lA(A,e);return this.transport.send(i.message).catch(e=>{e instanceof Error&&this.logger.error(e.message),this.logger.error(`Transport error occurred sending stateless reply to ${A.method} request.`)}),i}receiveRequestFromTransport(A){const e=A.viaBranch,t=this.userAgentServers.get(e);A.method===N.ACK&&t&&t.transaction.state===iA.Accepted&&t instanceof ZA?this.logger.warn(`Discarding out of dialog ACK after 2xx response sent on transaction ${e}.`):A.method!==N.CANCEL?t?t.transaction.receiveRequest(A):this.receiveRequest(A):t?(this.replyStateless(A,{statusCode:200}),t.transaction instanceof dA&&t.transaction.state===iA.Proceeding&&t instanceof ZA&&t.receiveCancel(A)):this.replyStateless(A,{statusCode:481})}receiveRequest(A){if(!K.includes(A.method)){const e="Allow: "+K.toString();return void this.replyStateless(A,{statusCode:405,extraHeaders:[e]})}if(!A.ruri)throw new Error("Request-URI undefined.");if("sip"!==A.ruri.scheme)return void this.replyStateless(A,{statusCode:416});const e=A.ruri,t=A=>!!A&&A.user===e.user;if(!t(this.configuration.aor)&&!(t(this.configuration.contact.uri)||t(this.configuration.contact.pubGruu)||t(this.configuration.contact.tempGruu)))return this.logger.warn("Request-URI does not point to us."),void(A.method!==N.ACK&&this.replyStateless(A,{statusCode:404}));if(A.method!==N.INVITE||A.hasHeader("Contact")){if(!A.toTag){const e=A.viaBranch;if(!this.userAgentServers.has(e)){if(Array.from(this.userAgentServers.values()).some(e=>e.transaction.request.fromTag===A.fromTag&&e.transaction.request.callId===A.callId&&e.transaction.request.cseq===A.cseq))return void this.replyStateless(A,{statusCode:482})}}A.toTag?this.receiveInsideDialogRequest(A):this.receiveOutsideDialogRequest(A)}else this.replyStateless(A,{statusCode:400,reasonPhrase:"Missing Contact Header"})}receiveInsideDialogRequest(A){if(A.method===N.NOTIFY){const e=A.parseHeader("Event");if(!e||!e.event)return void this.replyStateless(A,{statusCode:489});const t=A.callId+A.toTag+e.event,s=this.subscribers.get(t);if(s){const e=new DA(this,A);return void s.onNotify(e)}}const e=A.callId+A.toTag+A.fromTag,t=this.dialogs.get(e);if(t){if(A.method===N.OPTIONS){const e="Allow: "+K.toString(),t="Accept: "+jA.toString();return void this.replyStateless(A,{statusCode:200,extraHeaders:[e,t]})}t.receiveRequest(A)}else A.method!==N.ACK&&this.replyStateless(A,{statusCode:481})}receiveOutsideDialogRequest(A){switch(A.method){case N.ACK:break;case N.BYE:this.replyStateless(A,{statusCode:481});break;case N.CANCEL:throw new Error(`Unexpected out of dialog request method ${A.method}.`);case N.INFO:this.replyStateless(A,{statusCode:405});break;case N.INVITE:{const e=new ZA(this,A);this.delegate.onInvite?this.delegate.onInvite(e):e.reject()}break;case N.MESSAGE:{const e=new TA(this,A);this.delegate.onMessage?this.delegate.onMessage(e):e.accept()}break;case N.NOTIFY:{const e=new DA(this,A);this.delegate.onNotify?this.delegate.onNotify(e):e.reject({statusCode:405})}break;case N.OPTIONS:{const e="Allow: "+K.toString(),t="Accept: "+jA.toString();this.replyStateless(A,{statusCode:200,extraHeaders:[e,t]})}break;case N.REFER:{const e=new YA(this,A);this.delegate.onRefer?this.delegate.onRefer(e):e.reject({statusCode:405})}break;case N.REGISTER:{const e=new KA(this,A);this.delegate.onRegister?this.delegate.onRegister(e):e.reject({statusCode:405})}break;case N.SUBSCRIBE:{const e=new HA(this,A);this.delegate.onSubscribe?this.delegate.onSubscribe(e):e.reject({statusCode:480})}break;default:throw new Error(`Unexpected out of dialog request method ${A.method}.`)}}receiveResponseFromTransport(A){if(A.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response, dropping");const e=A.viaBranch+A.method,t=this.userAgentClients.get(e);t?t.transaction.receiveResponse(A):this.logger.warn(`Discarding unmatched ${A.statusCode} response to ${A.method} ${e}.`)}}class PA{constructor(A,e,t){A.debug("SessionDescriptionHandler.constructor"),this.logger=A,this.mediaStreamFactory=e,this.sessionDescriptionHandlerConfiguration=t,this._localMediaStream=new MediaStream,this._remoteMediaStream=new MediaStream,this._peerConnection=new RTCPeerConnection(null==t?void 0:t.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(A){this._peerConnectionDelegate=A}static dispatchAddTrackEvent(A,e){A.dispatchEvent(new MediaStreamTrackEvent("addtrack",{track:e}))}static dispatchRemoveTrackEvent(A,e){A.dispatchEvent(new MediaStreamTrackEvent("removetrack",{track:e}))}close(){this.logger.debug("SessionDescriptionHandler.close"),void 0!==this._peerConnection&&(this._peerConnection.getReceivers().forEach(A=>{A.track&&A.track.stop()}),this._peerConnection.getSenders().forEach(A=>{A.track&&A.track.stop()}),this._dataChannel&&this._dataChannel.close(),this._peerConnection.close(),this._peerConnection=void 0)}enableReceiverTracks(A){const e=this.peerConnection;if(!e)throw new Error("Peer connection closed.");e.getReceivers().forEach(e=>{e.track&&(e.track.enabled=A)})}enableSenderTracks(A){const e=this.peerConnection;if(!e)throw new Error("Peer connection closed.");e.getSenders().forEach(e=>{e.track&&(e.track.enabled=A)})}getDescription(A,e){var t,s;if(this.logger.debug("SessionDescriptionHandler.getDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==A?void 0:A.onDataChannel;const i=null===(t=null==A?void 0:A.offerOptions)||void 0===t?void 0:t.iceRestart,n=void 0===(null==A?void 0:A.iceGatheringTimeout)?null===(s=this.sessionDescriptionHandlerConfiguration)||void 0===s?void 0:s.iceGatheringTimeout:null==A?void 0:A.iceGatheringTimeout;return this.getLocalMediaStream(A).then(()=>this.updateDirection(A)).then(()=>this.createDataChannel(A)).then(()=>this.createLocalOfferOrAnswer(A)).then(A=>this.applyModifiers(A,e)).then(A=>this.setLocalSessionDescription(A)).then(()=>this.waitForIceGatheringComplete(i,n)).then(()=>this.getLocalSessionDescription()).then(A=>({body:A.sdp,contentType:"application/sdp"})).catch(A=>{throw this.logger.error("SessionDescriptionHandler.getDescription failed - "+A),A})}hasDescription(A){return this.logger.debug("SessionDescriptionHandler.hasDescription"),"application/sdp"===A}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(A,e){if(this.logger.debug("SessionDescriptionHandler.sendDtmf"),void 0===this._peerConnection)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - peer connection closed"),!1;const t=this._peerConnection.getSenders();if(0===t.length)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no senders"),!1;const s=t[0].dtmf;if(!s)return this.logger.error("SessionDescriptionHandler.sendDtmf failed - no DTMF sender"),!1;const i=null==e?void 0:e.duration,n=null==e?void 0:e.interToneGap;try{s.insertDTMF(A,i,n)}catch(A){return this.logger.error(A.toString()),!1}return this.logger.log("SessionDescriptionHandler.sendDtmf sent via RTP: "+A.toString()),!0}setDescription(A,e,t){if(this.logger.debug("SessionDescriptionHandler.setDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));this.onDataChannel=null==e?void 0:e.onDataChannel;const s="have-local-offer"===this._peerConnection.signalingState?"answer":"offer";return this.getLocalMediaStream(e).then(()=>this.applyModifiers({sdp:A,type:s},t)).then(A=>this.setRemoteSessionDescription(A)).catch(A=>{throw this.logger.error("SessionDescriptionHandler.setDescription failed - "+A),A})}applyModifiers(A,e){return this.logger.debug("SessionDescriptionHandler.applyModifiers"),e&&0!==e.length?e.reduce((A,e)=>A.then(e),Promise.resolve(A)).then(A=>{if(this.logger.debug("SessionDescriptionHandler.applyModifiers - modified sdp"),!A.sdp||!A.type)throw new Error("Invalid SDP.");return{sdp:A.sdp,type:A.type}}):Promise.resolve(A)}createDataChannel(A){if(void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));if(!0!==(null==A?void 0:A.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==A?void 0:A.dataChannelLabel)||"",null==A?void 0:A.dataChannelOptions),this.onDataChannel&&this.onDataChannel(this._dataChannel),Promise.resolve()}catch(A){return Promise.reject(A)}case"have-remote-offer":return Promise.resolve();default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}createLocalOfferOrAnswer(A){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==A?void 0:A.offerOptions);case"have-remote-offer":return this.logger.debug("SessionDescriptionHandler.createLocalOfferOrAnswer - creating SDP answer"),this._peerConnection.createAnswer(null==A?void 0:A.answerOptions);default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}}getLocalMediaStream(A){if(this.logger.debug("SessionDescriptionHandler.getLocalMediaStream"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));let e=Object.assign({},null==A?void 0:A.constraints);if(this.localMediaStreamConstraints){if(e.audio=e.audio||this.localMediaStreamConstraints.audio,e.video=e.video||this.localMediaStreamConstraints.video,JSON.stringify(this.localMediaStreamConstraints.audio)===JSON.stringify(e.audio)&&JSON.stringify(this.localMediaStreamConstraints.video)===JSON.stringify(e.video))return Promise.resolve()}else void 0===e.audio&&void 0===e.video&&(e={audio:!0});return this.localMediaStreamConstraints=e,this.mediaStreamFactory(e,this,A).then(A=>this.setLocalMediaStream(A))}setLocalMediaStream(A){if(this.logger.debug("SessionDescriptionHandler.setLocalMediaStream"),!this._peerConnection)throw new Error("Peer connection undefined.");const e=this._peerConnection,t=this._localMediaStream,s=[],i=A=>{const i=A.kind;if("audio"!==i&&"video"!==i)throw new Error(`Unknown new track kind ${i}.`);const n=e.getSenders().find(A=>A.track&&A.track.kind===i);n?s.push(new Promise(A=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - replacing sender ${i} track`),A()}).then(()=>n.replaceTrack(A).then(()=>{const e=t.getTracks().find(A=>A.kind===i);e&&(e.stop(),t.removeTrack(e),PA.dispatchRemoveTrackEvent(t,e)),t.addTrack(A),PA.dispatchAddTrackEvent(t,A)}).catch(A=>{throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to replace sender ${i} track`),A}))):s.push(new Promise(A=>{this.logger.debug(`SessionDescriptionHandler.setLocalMediaStream - adding sender ${i} track`),A()}).then(()=>{try{e.addTrack(A,t)}catch(A){throw this.logger.error(`SessionDescriptionHandler.setLocalMediaStream - failed to add sender ${i} track`),A}t.addTrack(A),PA.dispatchAddTrackEvent(t,A)}))},n=A.getAudioTracks();n.length&&i(n[0]);const o=A.getVideoTracks();return o.length&&i(o[0]),s.reduce((A,e)=>A.then(()=>e),Promise.resolve())}getLocalSessionDescription(){if(this.logger.debug("SessionDescriptionHandler.getLocalSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const A=this._peerConnection.localDescription;return A?Promise.resolve(A):Promise.reject(new Error("Failed to get local session description"))}setLocalSessionDescription(A){return this.logger.debug("SessionDescriptionHandler.setLocalSessionDescription"),void 0===this._peerConnection?Promise.reject(new Error("Peer connection closed.")):this._peerConnection.setLocalDescription(A)}setRemoteSessionDescription(A){if(this.logger.debug("SessionDescriptionHandler.setRemoteSessionDescription"),void 0===this._peerConnection)return Promise.reject(new Error("Peer connection closed."));const e=A.sdp;let t;switch(this._peerConnection.signalingState){case"stable":t="offer";break;case"have-local-offer":t="answer";break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return e?this._peerConnection.setRemoteDescription({sdp:e,type:t}):(this.logger.error("SessionDescriptionHandler.setRemoteSessionDescription failed - cannot set null sdp"),Promise.reject(new Error("SDP is undefined")))}setRemoteTrack(A){this.logger.debug("SessionDescriptionHandler.setRemoteTrack");const e=this._remoteMediaStream;e.getTrackById(A.id)?this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - have remote ${A.kind} track`):"audio"===A.kind?(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${A.kind} track`),e.getAudioTracks().forEach(A=>{A.stop(),e.removeTrack(A),PA.dispatchRemoveTrackEvent(e,A)}),e.addTrack(A),PA.dispatchAddTrackEvent(e,A)):"video"===A.kind&&(this.logger.debug(`SessionDescriptionHandler.setRemoteTrack - adding remote ${A.kind} track`),e.getVideoTracks().forEach(A=>{A.stop(),e.removeTrack(A),PA.dispatchRemoveTrackEvent(e,A)}),e.addTrack(A),PA.dispatchAddTrackEvent(e,A))}updateDirection(A){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 e=e=>{switch(e){case"inactive":case"recvonly":return(null==A?void 0:A.hold)?"inactive":"recvonly";case"sendonly":case"sendrecv":return(null==A?void 0:A.hold)?"sendonly":"sendrecv";case"stopped":return"stopped";default:throw new Error("Should never happen")}};this._peerConnection.getTransceivers().forEach(A=>{if(A.direction){const t=e(A.direction);A.direction!==t&&(A.direction=t)}})}break;case"have-remote-offer":this.logger.debug("SessionDescriptionHandler.updateDirection - setting answer direction");{const e=(()=>{const A=this._peerConnection.remoteDescription;if(!A)throw new Error("Failed to read remote offer");const e=/a=sendrecv\r\n|a=sendonly\r\n|a=recvonly\r\n|a=inactive\r\n/.exec(A.sdp);if(e)switch(e[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"})(),t=(()=>{switch(e){case"inactive":return"inactive";case"recvonly":return"sendonly";case"sendonly":return(null==A?void 0:A.hold)?"inactive":"recvonly";case"sendrecv":return(null==A?void 0:A.hold)?"sendonly":"sendrecv";default:throw new Error("Should never happen")}})();this._peerConnection.getTransceivers().forEach(A=>{A.direction&&"stopped"!==A.direction&&A.direction!==t&&(A.direction=t)})}break;default:return Promise.reject(new Error("Invalid signaling state "+this._peerConnection.signalingState))}return Promise.resolve()}waitForIceGatheringComplete(A=!1,e=0){return this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete"),void 0===this._peerConnection?Promise.reject("Peer connection closed."):A||"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((A,t)=>{this.iceGatheringCompleteResolve=A,this.iceGatheringCompleteReject=t,e>0&&(this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout in "+e),this.iceGatheringCompleteTimeoutId=setTimeout(()=>{this.logger.debug("SessionDescriptionHandler.waitForIceGatheringToComplete - timeout"),this.iceGatheringComplete()},e))}),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 A=this._peerConnection;A.onconnectionstatechange=e=>{var t;const s=A.connectionState;this.logger.debug(`SessionDescriptionHandler.onconnectionstatechange ${s}`),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onconnectionstatechange)&&this._peerConnectionDelegate.onconnectionstatechange(e)},A.ondatachannel=A=>{var e;this.logger.debug("SessionDescriptionHandler.ondatachannel"),this._dataChannel=A.channel,this.onDataChannel&&this.onDataChannel(this._dataChannel),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.ondatachannel)&&this._peerConnectionDelegate.ondatachannel(A)},A.onicecandidate=A=>{var e;this.logger.debug("SessionDescriptionHandler.onicecandidate"),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.onicecandidate)&&this._peerConnectionDelegate.onicecandidate(A)},A.onicecandidateerror=A=>{var e;this.logger.debug("SessionDescriptionHandler.onicecandidateerror"),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.onicecandidateerror)&&this._peerConnectionDelegate.onicecandidateerror(A)},A.oniceconnectionstatechange=e=>{var t;const s=A.iceConnectionState;this.logger.debug(`SessionDescriptionHandler.oniceconnectionstatechange ${s}`),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.oniceconnectionstatechange)&&this._peerConnectionDelegate.oniceconnectionstatechange(e)},A.onicegatheringstatechange=e=>{var t;const s=A.iceGatheringState;this.logger.debug(`SessionDescriptionHandler.onicegatheringstatechange ${s}`),"complete"===s&&this.iceGatheringComplete(),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onicegatheringstatechange)&&this._peerConnectionDelegate.onicegatheringstatechange(e)},A.onnegotiationneeded=A=>{var e;this.logger.debug("SessionDescriptionHandler.onnegotiationneeded"),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.onnegotiationneeded)&&this._peerConnectionDelegate.onnegotiationneeded(A)},A.onsignalingstatechange=e=>{var t;const s=A.signalingState;this.logger.debug(`SessionDescriptionHandler.onsignalingstatechange ${s}`),(null===(t=this._peerConnectionDelegate)||void 0===t?void 0:t.onsignalingstatechange)&&this._peerConnectionDelegate.onsignalingstatechange(e)},A.ontrack=A=>{var e;const t=A.track.kind,s=A.track.enabled?"enabled":"disabled";this.logger.debug(`SessionDescriptionHandler.ontrack ${t} ${s}`),this.setRemoteTrack(A.track),(null===(e=this._peerConnectionDelegate)||void 0===e?void 0:e.ontrack)&&this._peerConnectionDelegate.ontrack(A)}}}function zA(A){return(e,t)=>{void 0===A&&(A=A=>A.audio||A.video?void 0===navigator.mediaDevices?Promise.reject(new Error("Media devices not available in insecure contexts.")):navigator.mediaDevices.getUserMedia.call(navigator.mediaDevices,A):Promise.resolve(new MediaStream));const s={iceGatheringTimeout:void 0!==(null==t?void 0:t.iceGatheringTimeout)?null==t?void 0:t.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==t?void 0:t.peerConnectionConfiguration)},i=e.userAgent.getLogger("sip.SessionDescriptionHandler");return new PA(i,A,s)}}class XA{constructor(A,e){if(this._state=AA.Disconnected,this.transitioningState=!1,this._stateEventEmitter=new l,this.logger=A,e){const A=e,t=null==A?void 0:A.wsServers,s=null==A?void 0:A.maxReconnectionAttempts;if(void 0!==t){const A='The transport option "wsServers" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(A)}if(void 0!==s){const A='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(A)}t&&!e.server&&("string"==typeof t&&(e.server=t),t instanceof Array&&(e.server=t[0]))}this.configuration=Object.assign(Object.assign({},XA.defaultOptions),e);const t=this.configuration.server,s=C.parse(t,"absoluteURI");if(-1===s)throw this.logger.error(`Invalid WebSocket Server URL "${t}"`),new Error("Invalid WebSocket Server URL");if(!["wss","ws","udp"].includes(s.scheme))throw this.logger.error(`Invalid scheme in WebSocket Server URL "${t}"`),new Error("Invalid scheme in WebSocket Server URL");this._protocol=s.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===AA.Connected}send(A){return this._send(A)}_connect(){switch(this.logger.log(`Connecting ${this.server}`),this.state){case AA.Connecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(AA.Connecting));if(!this.connectPromise)throw new Error("Connect promise must be defined.");return this.connectPromise;case AA.Connected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(AA.Connecting));if(this.connectPromise)throw new Error("Connect promise must not be defined.");return Promise.resolve();case AA.Disconnecting:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(AA.Connecting)}catch(A){if(A instanceof r)return Promise.reject(A);throw A}break;case AA.Disconnected:if(this.connectPromise)throw new Error("Connect promise must not be defined.");try{this.transitionState(AA.Connecting)}catch(A){if(A instanceof r)return Promise.reject(A);throw A}break;default:throw new Error("Unknown state")}let A;try{A=new WebSocket(this.server,"sip"),A.binaryType="arraybuffer",A.addEventListener("close",e=>this.onWebSocketClose(e,A)),A.addEventListener("error",e=>this.onWebSocketError(e,A)),A.addEventListener("open",e=>this.onWebSocketOpen(e,A)),A.addEventListener("message",e=>this.onWebSocketMessage(e,A)),this._ws=A}catch(A){return this._ws=void 0,this.logger.error("WebSocket construction failed."),this.logger.error(A.toString()),new Promise((e,t)=>{this.connectResolve=e,this.connectReject=t,this.transitionState(AA.Disconnected,A)})}return this.connectPromise=new Promise((e,t)=>{this.connectResolve=e,this.connectReject=t,this.connectTimeout=setTimeout(()=>{this.logger.warn("Connect timed out. Exceeded time set in configuration.connectionTimeout: "+this.configuration.connectionTimeout+"s."),A.close(1e3)},1e3*this.configuration.connectionTimeout)}),this.connectPromise}_disconnect(){switch(this.logger.log(`Disconnecting ${this.server}`),this.state){case AA.Connecting:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(AA.Disconnecting)}catch(A){if(A instanceof r)return Promise.reject(A);throw A}break;case AA.Connected:if(this.disconnectPromise)throw new Error("Disconnect promise must not be defined.");try{this.transitionState(AA.Disconnecting)}catch(A){if(A instanceof r)return Promise.reject(A);throw A}break;case AA.Disconnecting:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(AA.Disconnecting));if(!this.disconnectPromise)throw new Error("Disconnect promise must be defined.");return this.disconnectPromise;case AA.Disconnected:if(this.transitioningState)return Promise.reject(this.transitionLoopDetectedError(AA.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 A=this._ws;return this.disconnectPromise=new Promise((e,t)=>{this.disconnectResolve=e,this.disconnectReject=t;try{A.close(1e3)}catch(A){throw this.logger.error("WebSocket close failed."),this.logger.error(A.toString()),A}}),this.disconnectPromise}_send(A){if(!0===this.configuration.traceSip&&this.logger.log("Sending WebSocket message:\n\n"+A+"\n"),this._state!==AA.Connected)return Promise.reject(new Error("Not connected."));if(!this._ws)throw new Error("WebSocket undefined.");try{this._ws.send(A)}catch(A){return A instanceof Error?Promise.reject(A):Promise.reject(new Error("WebSocket send failed."))}return Promise.resolve()}onWebSocketClose(A,e){if(e!==this._ws)return;const t=`WebSocket closed ${this.server} (code: ${A.code})`,s=this.disconnectPromise?void 0:new Error(t);s&&this.logger.warn("WebSocket closed unexpectedly"),this.logger.log(t),this._ws=void 0,this.transitionState(AA.Disconnected,s)}onWebSocketError(A,e){e===this._ws&&this.logger.error("WebSocket error occurred.")}onWebSocketMessage(A,e){if(e!==this._ws)return;const t=A.data;let s;if(/^(\r\n)+$/.test(t))return this.clearKeepAliveTimeout(),void(!0===this.configuration.traceSip&&this.logger.log("Received WebSocket message with CRLF Keep Alive response"));if(t){if("string"!=typeof t){try{s=(new TextDecoder).decode(new Uint8Array(t))}catch(A){return this.logger.error(A.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"+s+"\n")}else s=t,!0===this.configuration.traceSip&&this.logger.log("Received WebSocket text message:\n\n"+s+"\n");if(this.state===AA.Connected){if(this.onMessage)try{this.onMessage(s)}catch(A){throw this.logger.error(A.toString()),this.logger.error("Exception thrown by onMessage callback"),A}}else this.logger.warn("Received message while not connected, discarding...")}else this.logger.warn("Received empty message, discarding...")}onWebSocketOpen(A,e){e===this._ws&&this._state===AA.Connecting&&(this.logger.log(`WebSocket opened ${this.server}`),this.transitionState(AA.Connected))}transitionLoopDetectedError(A){let e="A state transition loop has been detected.";return e+=` An attempt to transition from ${this._state} to ${A} before the prior transition completed.`,e+=" Perhaps you are synchronously calling connect() or disconnect() from a callback or state change handler?",this.logger.error(e),new r("Loop detected.")}transitionState(A,e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${A}`)};if(this.transitioningState)throw this.transitionLoopDetectedError(A);switch(this.transitioningState=!0,this._state){case AA.Connecting:A!==AA.Connected&&A!==AA.Disconnecting&&A!==AA.Disconnected&&t();break;case AA.Connected:A!==AA.Disconnecting&&A!==AA.Disconnected&&t();break;case AA.Disconnecting:A!==AA.Connecting&&A!==AA.Disconnected&&t();break;case AA.Disconnected:A!==AA.Connecting&&t();break;default:throw new Error("Unknown state.")}const s=this._state;this._state=A;const i=this.connectResolve,n=this.connectReject;s===AA.Connecting&&(this.connectPromise=void 0,this.connectResolve=void 0,this.connectReject=void 0);const o=this.disconnectResolve,r=this.disconnectReject;if(s===AA.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 ${s} to ${this._state}`),this._stateEventEmitter.emit(this._state),A===AA.Connected&&(this.startSendingKeepAlives(),this.onConnect))try{this.onConnect()}catch(A){throw this.logger.error(A.toString()),this.logger.error("Exception thrown by onConnect callback"),A}if(s===AA.Connected&&(this.stopSendingKeepAlives(),this.onDisconnect))try{e?this.onDisconnect(e):this.onDisconnect()}catch(A){throw this.logger.error(A.toString()),this.logger.error("Exception thrown by onDisconnect callback"),A}if(s===AA.Connecting){if(!i)throw new Error("Connect resolve undefined.");if(!n)throw new Error("Connect reject undefined.");A===AA.Connected?i():n(e||new Error("Connect aborted."))}if(s===AA.Disconnecting){if(!o)throw new Error("Disconnect resolve undefined.");if(!r)throw new Error("Disconnect reject undefined.");A===AA.Disconnected?o():r(e||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()},(A=>{const e=.8*A;return 1e3*(Math.random()*(A-e)+e)})(this.configuration.keepAliveInterval)))}stopSendingKeepAlives(){this.keepAliveInterval&&clearInterval(this.keepAliveInterval),this.keepAliveDebounceTimeout&&clearTimeout(this.keepAliveDebounceTimeout),this.keepAliveInterval=void 0,this.keepAliveDebounceTimeout=void 0}}XA.defaultOptions={server:"",connectionTimeout:5,keepAliveInterval:0,keepAliveDebounce:10,traceSip:!0};class _A{constructor(A={}){if(this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this._state=eA.Stopped,this._stateEventEmitter=new l,this.delegate=A.delegate,this.options=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},_A.defaultOptions()),{sipjsId:M(5)}),{uri:new d("sip","anonymous."+M(6),"anonymous.invalid")}),{viaHost:M(12)+".invalid"}),_A.stripUndefinedProperties(A)),this.options.hackIpInContact)if("boolean"==typeof this.options.hackIpInContact&&this.options.hackIpInContact){const A=1,e=254,t=Math.floor(Math.random()*(e-A+1)+A);this.options.viaHost="192.0.2."+t}else this.options.hackIpInContact&&(this.options.viaHost=this.options.hackIpInContact);switch(this.loggerFactory=new cA,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=tA.error;break;case"warn":this.loggerFactory.level=tA.warn;break;case"log":this.loggerFactory.level=tA.log;break;case"debug":this.loggerFactory.level=tA.debug}if(this.options.logConfiguration&&(this.logger.log("Configuration:"),Object.keys(this.options).forEach(A=>{const e=this.options[A];switch(A){case"uri":case"sessionDescriptionHandlerFactory":this.logger.log("· "+A+": "+e);break;case"authorizationPassword":this.logger.log("· "+A+": NOT SHOWN");break;case"transportConstructor":this.logger.log("· "+A+": "+e.name);break;default:this.logger.log("· "+A+": "+JSON.stringify(e))}})),this.options.transportOptions){const e=this.options.transportOptions,t=e.maxReconnectionAttempts,s=e.reconnectionTimeout;if(void 0!==t){const A='The transport option "maxReconnectionAttempts" as has apparently been specified and has been deprecated. It will no longer be available starting with SIP.js release 0.16.0. Please update accordingly.';this.logger.warn(A)}if(void 0!==s){const A='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(A)}void 0===A.reconnectionDelay&&void 0!==s&&(this.options.reconnectionDelay=s),void 0===A.reconnectionAttempts&&void 0!==t&&(this.options.reconnectionAttempts=t)}if(void 0!==A.reconnectionDelay){const A='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(A)}if(void 0!==A.reconnectionAttempts){const A='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(A)}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:_A.newUUID(),-1===C.parse(this._instanceId,"uuid"))throw new Error("Invalid instanceId.");this._userAgentCore=this.initCore()}static makeURI(A){return C.URIParse(A)}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:zA(),sessionDescriptionHandlerFactoryOptions:{},sipExtension100rel:j.Unsupported,sipExtensionReplaces:j.Unsupported,sipExtensionExtraSupported:[],sipjsId:"",transportConstructor:XA,transportOptions:{},uri:new d("sip","anonymous","anonymous.invalid"),userAgentString:"SIP.js/0.21.1",viaHost:""}}static newUUID(){const A="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,A=>{const e=Math.floor(16*Math.random());return("x"===A?e:e%4+8).toString(16)});return A}static stripUndefinedProperties(A){return Object.keys(A).reduce((e,t)=>(void 0!==A[t]&&(e[t]=A[t]),e),{})}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(A,e){return this.loggerFactory.getLogger(A,e)}getLoggerFactory(){return this.loggerFactory}isConnected(){return this.transport.isConnected()}reconnect(){return this.state===eA.Stopped?Promise.reject(new Error("User agent stopped.")):Promise.resolve().then(()=>this.transport.connect())}start(){return this.state===eA.Started?(this.logger.warn("User agent already started"),Promise.resolve()):(this.logger.log(`Starting ${this.configuration.uri}`),this.transitionState(eA.Started),this.transport.connect())}async stop(){if(this.state===eA.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(A=>{throw this.logger.error(A.message),A}),this.logger.log("Dispose of core"),this.userAgentCore.dispose(),this._publishers={},this._registerers={},this._sessions={},this._subscriptions={},this.transitionState(eA.Stopped),Promise.resolve();const A=Object.assign({},this._publishers),e=Object.assign({},this._registerers),t=Object.assign({},this._sessions),s=Object.assign({},this._subscriptions),i=this.transport,n=this.userAgentCore;this.logger.log("Dispose of registerers");for(const A in e)e[A]&&await e[A].dispose().catch(e=>{throw this.logger.error(e.message),delete this._registerers[A],e});this.logger.log("Dispose of sessions");for(const A in t)t[A]&&await t[A].dispose().catch(e=>{throw this.logger.error(e.message),delete this._sessions[A],e});this.logger.log("Dispose of subscriptions");for(const A in s)s[A]&&await s[A].dispose().catch(e=>{throw this.logger.error(e.message),delete this._subscriptions[A],e});this.logger.log("Dispose of publishers");for(const e in A)A[e]&&await A[e].dispose().catch(A=>{throw this.logger.error(A.message),delete this._publishers[e],A});this.logger.log("Dispose of transport"),await i.dispose().catch(A=>{throw this.logger.error(A.message),A}),this.logger.log("Dispose of core"),n.dispose(),this.transitionState(eA.Stopped)}_makeInviter(A,e){return new X(this,A,e)}attemptReconnection(A=1){const e=this.options.reconnectionAttempts,t=this.options.reconnectionDelay;A>e?this.logger.log("Maximum reconnection attempts reached"):(this.logger.log(`Reconnection attempt ${A} of ${e} - trying`),setTimeout(()=>{this.reconnect().then(()=>{this.logger.log(`Reconnection attempt ${A} of ${e} - succeeded`)}).catch(t=>{this.logger.error(t.message),this.logger.log(`Reconnection attempt ${A} of ${e} - failed`),this.attemptReconnection(++A)})},1===A?0:1e3*t))}initContact(){const A=""!==this.options.contactName?this.options.contactName:M(8),e=this.options.contactParams;return{pubGruu:void 0,tempGruu:void 0,uri:new d("sip",A,this.options.viaHost,void 0,e),toString:(A={})=>{const t=A.anonymous||!1,s=A.outbound||!1,i=A.register||!1;let n="<";return n+=t?this.contact.tempGruu||`sip:anonymous@anonymous.invalid;transport=${e.transport?e.transport:"ws"}`:i?this.contact.uri:this.contact.pubGruu||this.contact.uri,s&&(n+=";ob"),n+=">",this.options.instanceIdAlwaysAdded&&(n+=';+sip.instance="<urn:uuid:'+this._instanceId+'>"'),n}}}initCore(){let A=[];A.push("outbound"),this.options.sipExtension100rel===j.Supported&&A.push("100rel"),this.options.sipExtensionReplaces===j.Supported&&A.push("replaces"),this.options.sipExtensionExtraSupported&&A.push(...this.options.sipExtensionExtraSupported),this.options.hackAllowUnregisteredOptionTags||(A=A.filter(A=>P[A])),A=Array.from(new Set(A));const e=A.slice();(this.contact.pubGruu||this.contact.tempGruu)&&e.push("gruu");const t={aor:this.options.uri,contact:this.contact,displayName:this.options.displayName,loggerFactory:this.loggerFactory,hackViaTcp:this.options.hackViaTcp,routeSet:this.options.preloadedRouteSet,supportedOptionTags:A,supportedOptionTagsResponse:e,sipjsId:this.options.sipjsId,userAgentHeaderFieldValue:this.options.userAgentString,viaForceRport:this.options.forceRport,viaHost:this.options.viaHost,authenticationFactory:()=>{const A=this.options.authorizationUsername?this.options.authorizationUsername:this.options.uri.user,e=this.options.authorizationPassword?this.options.authorizationPassword:void 0,t=this.options.authorizationHa1?this.options.authorizationHa1:void 0;return new aA(this.getLoggerFactory(),t,A,e)},transportAccessor:()=>this.transport},s={onInvite:A=>{var e;const t=new z(this,A);if(A.delegate={onCancel:A=>{t._onCancel(A)},onTransportError:A=>{this.logger.error("A transport error has occurred while handling an incoming INVITE request.")}},A.trying(),this.options.sipExtensionReplaces!==j.Unsupported){const e=A.message.parseHeader("replaces");if(e){const A=e.call_id;if("string"!=typeof A)throw new Error("Type of call id is not string");const s=e.replaces_to_tag;if("string"!=typeof s)throw new Error("Type of to tag is not string");const i=e.replaces_from_tag;if("string"!=typeof i)throw new Error("type of from tag is not string");const n=A+s+i,o=this.userAgentCore.dialogs.get(n);if(!o)return void t.reject({statusCode:481});if(!o.early&&!0===e.early_only)return void t.reject({statusCode:486});const r=this._sessions[A+i]||this._sessions[A+s]||void 0;if(!r)throw new Error("Session does not exist.");t._replacee=r}}if(null===(e=this.delegate)||void 0===e?void 0:e.onInvite)return t.autoSendAnInitialProvisionalResponse?void t.progress().then(()=>{var A;if(void 0===(null===(A=this.delegate)||void 0===A?void 0:A.onInvite))throw new Error("onInvite undefined.");this.delegate.onInvite(t)}):void this.delegate.onInvite(t);t.reject({statusCode:486})},onMessage:A=>{if(this.delegate&&this.delegate.onMessage){const e=new b(A);this.delegate.onMessage(e)}else A.accept()},onNotify:A=>{if(this.delegate&&this.delegate.onNotify){const e=new J(A);this.delegate.onNotify(e)}else this.options.allowLegacyNotifications?A.accept():A.reject({statusCode:481})},onRefer:A=>{this.logger.warn("Received an out of dialog REFER request"),this.delegate&&this.delegate.onReferRequest?this.delegate.onReferRequest(A):A.reject({statusCode:405})},onRegister:A=>{this.logger.warn("Received an out of dialog REGISTER request"),this.delegate&&this.delegate.onRegisterRequest?this.delegate.onRegisterRequest(A):A.reject({statusCode:405})},onSubscribe:A=>{this.logger.warn("Received an out of dialog SUBSCRIBE request"),this.delegate&&this.delegate.onSubscribeRequest?this.delegate.onSubscribeRequest(A):A.reject({statusCode:405})}};return new WA(t,s)}initTransportCallbacks(){this.transport.onConnect=()=>this.onTransportConnect(),this.transport.onDisconnect=A=>this.onTransportDisconnect(A),this.transport.onMessage=A=>this.onTransportMessage(A)}onTransportConnect(){this.state!==eA.Stopped&&this.delegate&&this.delegate.onConnect&&this.delegate.onConnect()}onTransportDisconnect(A){this.state!==eA.Stopped&&(this.delegate&&this.delegate.onDisconnect&&this.delegate.onDisconnect(A),A&&this.options.reconnectionAttempts>0&&this.attemptReconnection())}onTransportMessage(A){const e=sA.parseMessage(A,this.getLogger("sip.Parser"));if(!e)return void this.logger.warn("Failed to parse incoming message. Dropping.");if(this.state===eA.Stopped&&e instanceof T)return void this.logger.warn(`Received ${e.method} request while stopped. Dropping.`);const t=()=>{const A=["from","to","call_id","cseq","via"];for(const t of A)if(!e.hasHeader(t))return this.logger.warn(`Missing mandatory header field : ${t}.`),!1;return!0};if(e instanceof T){if(!t())return void this.logger.warn("Request missing mandatory header field. Dropping.");if(!e.toTag&&e.callId.substr(0,5)===this.options.sipjsId)return void this.userAgentCore.replyStateless(e,{statusCode:482});const A=S(e.body),s=e.getHeader("content-length");if(s&&A<Number(s))return void this.userAgentCore.replyStateless(e,{statusCode:400})}if(e instanceof y){if(!t())return void this.logger.warn("Response missing mandatory header field. Dropping.");if(e.getHeaders("via").length>1)return void this.logger.warn("More than one Via header field present in the response. Dropping.");if(e.via.host!==this.options.viaHost||void 0!==e.via.port)return void this.logger.warn("Via sent-by in the response does not match UA Via host value. Dropping.");const A=S(e.body),s=e.getHeader("content-length");if(s&&A<Number(s))return void this.logger.warn("Message body length is lower than the value in Content-Length header field. Dropping.")}if(e instanceof T)this.userAgentCore.receiveIncomingRequestFromTransport(e);else{if(!(e instanceof y))throw new Error("Invalid message type.");this.userAgentCore.receiveIncomingResponseFromTransport(e)}}transitionState(A,e){const t=()=>{throw new Error(`Invalid state transition from ${this._state} to ${A}`)};switch(this._state){case eA.Started:A!==eA.Stopped&&t();break;case eA.Stopped:A!==eA.Started&&t();break;default:throw new Error("Unknown state.")}this.logger.log(`Transitioned from ${this._state} to ${A}`),this._state=A,this._stateEventEmitter.emit(this._state)}}class $A{constructor(A){this.listeners=[],this.keyListeners={},this.data={...A},this.proxy=new Proxy(this.data,{set:(A,e,t)=>(A[e]!==t&&(A[e]=t,this.notify(),this.notifyKey(e,t)),!0)})}getState(){return this.proxy}setState(A,e=!1){let t=!1;for(const s in A)if(Object.prototype.hasOwnProperty.call(A,s)){const i=this.data[s],n=A[s];(e||i!==n)&&(this.data[s]=n,t=!0,this.notifyKey(s,n))}(t||e)&&this.notify()}subscribe(A){return this.listeners.push(A),()=>{this.listeners=this.listeners.filter(e=>e!==A)}}subscribeKey(A,e){return this.keyListeners[A]||(this.keyListeners[A]=[]),this.keyListeners[A].push(e),()=>{this.keyListeners[A]=this.keyListeners[A].filter(A=>A!==e)}}notify(){const A=this.getState();for(const e of this.listeners)e(A)}notifyKey(A,e){const t=this.keyListeners[A];t&&t.forEach(A=>A(e))}}var Ae,ee,te,se,ie,ne,oe;exports.AgentStatus=void 0,(Ae=exports.AgentStatus||(exports.AgentStatus={}))[Ae.IDLE=1]="IDLE",Ae[Ae.BUSY=2]="BUSY",Ae[Ae.RINGING=3]="RINGING",Ae[Ae.OFFLINE=0]="OFFLINE",Ae[Ae.UNREGISTERED=4]="UNREGISTERED",exports.DirectionEnum=void 0,(ee=exports.DirectionEnum||(exports.DirectionEnum={})).OUTGOING="outgoing",ee.INCOMING="incoming",ee.CONSULT="consult",ee.MEETING="meeting",ee.TRANSFER="transfer",ee.PREDICT_OUT_CALL="predict_out_call",exports.WebsocketTypeEnum=void 0,(te=exports.WebsocketTypeEnum||(exports.WebsocketTypeEnum={}))[te.OUT_CALL=100]="OUT_CALL",te[te.AGENT_STATE=101]="AGENT_STATE",te[te.OUT_CALL_INCOMING_CALL=102]="OUT_CALL_INCOMING_CALL",te[te.OUT_CALL_RINGING=103]="OUT_CALL_RINGING",te[te.OUT_CALL_ANSWER=104]="OUT_CALL_ANSWER",te[te.CALL_HOLD=105]="CALL_HOLD",te[te.CALL_UNHOLD=106]="CALL_UNHOLD",te[te.OUT_CALL_END=107]="OUT_CALL_END",te[te.CONSULT_REQUEST=108]="CONSULT_REQUEST",te[te.CONSULT_RINGING=109]="CONSULT_RINGING",te[te.CONSULT_ANSWER=110]="CONSULT_ANSWER",te[te.CONSULT_FAIL=111]="CONSULT_FAIL",te[te.MUTE=112]="MUTE",te[te.UNMUTE=113]="UNMUTE",te[te.CONSULT_CALL_IN=114]="CONSULT_CALL_IN",te[te.CONSULT_CALL_IN_SUCCESS=115]="CONSULT_CALL_IN_SUCCESS",te[te.CONSULT_RETURN_CALL=125]="CONSULT_RETURN_CALL",te[te.CONSULT_RETURN_CALL_SUCCESS=126]="CONSULT_RETURN_CALL_SUCCESS",te[te.CONSULT_TRANSFER=116]="CONSULT_TRANSFER",te[te.CONSULT_TRANSFER_FAILED=118]="CONSULT_TRANSFER_FAILED",te[te.CONSULT_TRANSFER_OFF_HOOK=117]="CONSULT_TRANSFER_OFF_HOOK",te[te.INCOMING_CALL=119]="INCOMING_CALL",te[te.INCOMING_CALL_OFF_HOOK=120]="INCOMING_CALL_OFF_HOOK",te[te.INCOMING_CALL_END=121]="INCOMING_CALL_END",te[te.SATISFACTION_EVALUATION=122]="SATISFACTION_EVALUATION",te[te.CONSULT_THREE_WAY=123]="CONSULT_THREE_WAY",te[te.CONSULT_THREE_WAY_RESULT=124]="CONSULT_THREE_WAY_RESULT",te[te.TRANSFER=127]="TRANSFER",te[te.TRANSFER_FAILED=128]="TRANSFER_FAILED",te[te.TRANSFER_INCOMING_CALL=129]="TRANSFER_INCOMING_CALL",te[te.TRANSFER_OFF_HOOK=130]="TRANSFER_OFF_HOOK",te[te.AGENT_HANGUP=131]="AGENT_HANGUP",te[te.KICK_OFFLINE=132]="KICK_OFFLINE",te[te.CONTINUOUS_NOT_ANSWER=133]="CONTINUOUS_NOT_ANSWER",te[te.PREVIEW_OUT_CALL=134]="PREVIEW_OUT_CALL",te[te.SIGN_OUT=135]="SIGN_OUT",te[te.SIGN_IN_SWITCH_DEVICE=136]="SIGN_IN_SWITCH_DEVICE",te[te.LISTEN_CALL_FAILED=137]="LISTEN_CALL_FAILED",te[te.LISTEN_INCOMING_CALL=138]="LISTEN_INCOMING_CALL",te[te.LISTEN_INCOMING_CALL_OFF_HOOK=139]="LISTEN_INCOMING_CALL_OFF_HOOK",te[te.EAR_SPEECH=140]="EAR_SPEECH",te[te.STOP_EAR_SPEECH=141]="STOP_EAR_SPEECH",te[te.CALL_FORCE_INSERT=142]="CALL_FORCE_INSERT",exports.WebRtcCallSipEventEnum=void 0,(se=exports.WebRtcCallSipEventEnum||(exports.WebRtcCallSipEventEnum={})).WEB_RTC_CONNECTING="connecting",se.WEB_RTC_CONNECTED="connected",se.WEB_RTC_DISCONNECTING="disconnecting",se.WEB_RTC_DISCONNECTED="disconnected",se.WEB_RTC_REGISTERED="registered",se.WEB_RTC_UNREGISTERED="unregistered",se.WEB_RTC_TERMINATED="terminated",se.WEB_RTC_REGISTER_FAILED="register_failed",se.WEB_RTC_ANSWER_FAILED="answer_failed",se.WEB_RTC_SEND_DTMF="send_dtmf",exports.CallSipCallEventEnum=void 0,(ie=exports.CallSipCallEventEnum||(exports.CallSipCallEventEnum={})).CUSTOMER_INFO="customer_info",ie.CALL_PROGRESS="call_progress",ie.OUT_INCOMING_CALL="out_call_incoming_call",ie.PREVIEW_OUT_INCOMING_CALL="preview_out_incoming_call",ie.OUT_SUCCESS="out_call_success",ie.OUT_FAILED="out_call_failed",ie.OUT_RINGING="out_call_ringing",ie.OUT_OFF_ANSWER="out_call_answer",ie.HOLD_SUCCESS="hold_success",ie.HOLD_FAILED="hold_failed",ie.UNHOLD_SUCCESS="unhold_success",ie.UNHOLD_FAILED="unhold_failed",ie.OUT_HANGUP="out_call_hangup",ie.CONSULT_RINGING="consult_ringing",ie.CONSULT_OFF_HOOK="consult_off_hook",ie.CONSULT_FAILED="consult_failed",ie.CONSULT_INCOMING="consult_incoming",ie.CONSULT_CALL_IN_SUCCESS="consult_call_in_success",ie.CONSULT_RETURN_CALL_SUCCESS="consult_return_call_success",ie.OTHER_SIDE_CONSULT_HANGUP="other_side_consult_hangup",ie.OUR_SIDE_CONSULT_HANGUP="our_side_consult_hangup",ie.AGENT_STATE="agent_state",ie.MUTE_SUCCESS="mute_success",ie.MUTE_FAILED="mute_failed",ie.UNMUTE_SUCCESS="unmute_success",ie.UNMUTE_FAILED="unmute_failed",ie.CONSULT_TRANSFER_SUCCESS="consult_transfer_success",ie.CONSULT_TRANSFER_FAILED="consult_transfer_failed",ie.CONSULT_TRANSFER_OFF_HOOK="consult_transfer_off_hook",ie.INCOMING_CALL="incoming_call",ie.PREDICT_INCOMING_CALL="predict_incoming_call",ie.INCOMING_CALL_OFF_HOOK="incoming_call_off_hook",ie.INCOMING_CALL_END="incoming_call_end",ie.SATISFACTION_EVALUATION_SUCCESS="satisfaction_evaluation_success",ie.SATISFACTION_EVALUATION_FAILED="satisfaction_evaluation_failed",ie.CONSULT_THREE_WAY_SUCCESS="consult_three_way_success",ie.CONSULT_THREE_WAY_FAILED="consult_three_way_failed",ie.THREE_WAY_OUR_SIDE_HANGUP="three_way_our_side_hangup",ie.TRANSFER_FAILED="transfer_failed",ie.TRANSFER_PROGRESS="transfer_progress",ie.TRANSFER_INCOMING_CALL="transfer_incoming_call",ie.TRANSFER_OFF_HOOK="transfer_off_hook",ie.TRANSFER_END="transfer_end",ie.REJECT="reject",ie.LISTEN_CALL_FAILED="listen_call_failed",ie.LISTEN_INCOMING_CALL="listen_incoming_call",ie.LISTEN_INCOMING_CALL_OFF_HOOK="listen_incoming_call_off_hook",ie.LISTEN_HANGUP="listen_hangup",ie.EAR_SPEECH_SUCCESS="ear_speech_success",ie.EAR_SPEECH_BE_SUCCESS="ear_speech_be_success",ie.EAR_SPEECH_FAILED="ear_speech_failed",ie.STOP_EAR_SPEECH_SUCCESS="stop_ear_speech_success",ie.STOP_EAR_SPEECH_FAILED="stop_ear_speech_failed",ie.CALL_FORCE_INSERT_SUCCESS="call_force_insert_success",ie.CALL_FORCE_INSERT_SUCCESS_LISTENER="call_force_insert_success_listener",ie.CALL_FORCE_INSERT_FAILED="call_force_insert_failed",exports.EventName=void 0,(ne=exports.EventName||(exports.EventName={})).EVENT_ALL="event_all",ne.NOTIFICATION_CLICK="notification_click",ne.UPDATE_ANSWER_DEVICE="update_answer_device",ne.PHONE_BAR_OPERATION="phone_bar_operation",ne.AGENT_INIT_STATUS="agent_init_status",ne.WEBSITE_DELAY="website_delay",ne.SELECT_EXTERNAL_NUMBER="select_external_number",ne.FAIL_NOTIFICATION="fail_notification",ne.KICK_OFF="kick_off",ne.DESTROY="destroy",ne.NETWORK_OFFLINE="network_offline",ne.NETWORK_ONLINE="network_online",ne.SIGN_OUT="sign_out",ne.SIGN_IN_SWITCH_DEVICE="sign_in_switch_device",exports.DisplayTextEnum=void 0,(oe=exports.DisplayTextEnum||(exports.DisplayTextEnum={})).RINGING="客户振铃",oe.AGENT_RINGING="振铃中",oe.CALLING="通话中",oe.CONSULTING="正在咨询",oe.CONSULT_CALL_IN="咨询来电",oe.INCOMING_CALL="客户来电",oe.MEETING="会议中",oe.TRANSFERRING="转接中",oe.TRANSFER_INCOMING_CALL="转接来电",oe.HOLDING="保持中",oe.MUTING="静音中",oe.LISTENING="监听来电";const re=function(A){return{all:A=A||new Map,on:function(e,t){var s=A.get(e);s?s.push(t):A.set(e,[t])},off:function(e,t){var s=A.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):A.set(e,[]))},emit:function(e,t){var s=A.get(e);s&&s.slice().map(function(A){A(t)}),(s=A.get("*"))&&s.slice().map(function(A){A(e,t)})}}}(),ae={on:(A,e)=>(re.on(A,e),ae),off(A,e){re.off(A,e)},emit(A,e){re.emit(A,e),re.emit(exports.EventName.EVENT_ALL,{event:A,data:e})},clearAllListeners(){re.all.clear()}},Ve={agentInfo:{},isRtcReconnecting:!1,sessionId:"",enableBrowserAlert:!1,autoStateTimer:null,autoAnswerTimer:null,logBuiltinEnabled:!1,browserAlertTime:3e3,latency:0,monitoredAgentNo:"",earSpeakAgent:""},ce={isCalling:!1,direction:null,outCallIsAnswer:!1,incomingIsAnswer:!1,transferIsAnswer:!1,isMeeting:!1,isHold:!1,displayText:"",isMuted:!1,consultIsAnswer:!1,actionConfigs:[],answerDevice:1,selectOutNumber:"",customerObject:void 0,isNextState:!0};const le=new class extends $A{updateIsCalling(A){this.setState({isCalling:A})}updateDirection(A){this.setState({direction:A})}updateOutCallIsAnswer(A){this.setState({outCallIsAnswer:A})}updateIsHold(A){if(Ve.stateObject?.state===exports.AgentStatus.UNREGISTERED)return;const e=this.get("actionConfigs");if(A){const A=[...e.filter(A=>"hold"!==A)];A.push("unhold"),this.updateActionConfigs(A)}else{const A=[...e.filter(A=>"unhold"!==A)];A.push("hold"),this.updateActionConfigs(A)}this.getState().isHold=A}updateDisplayText(A){this.setState({displayText:A}),ae.emit(exports.CallSipCallEventEnum.CALL_PROGRESS,A)}updateActionConfigs(A){const{show_satisfaction:e}=Ve.agentInfo||{},t=this.get("answerDevice"),s=A.filter(A=>(0!==e||"satisfaction"!==A)&&(2!==t||"answer"!==A));this.setState({actionConfigs:s}),ae.emit(exports.EventName.PHONE_BAR_OPERATION,s)}updateConsultIsAnswer(A){this.setState({consultIsAnswer:A})}updateIsMuted(A){if(Ve.stateObject?.state===exports.AgentStatus.UNREGISTERED)return;const e=this.get("actionConfigs");if(A){const A=[...e.filter(A=>"mute"!==A)];A.push("unmute"),this.updateActionConfigs(A)}else{const A=[...e.filter(A=>"unmute"!==A)];A.push("mute"),this.updateActionConfigs(A)}this.setState({isMuted:A})}updateIncomingIsAnswer(A){this.setState({incomingIsAnswer:A})}updateAnswerDevice(A){this.setState({answerDevice:A}),ae.emit(exports.EventName.UPDATE_ANSWER_DEVICE,A)}updateIsMeeting(A){this.setState({isMeeting:A})}updateTransferIsAnswer(A){this.setState({transferIsAnswer:A})}updateSelectOutNumber(A){ae.emit(exports.EventName.SELECT_EXTERNAL_NUMBER,A),this.setState({selectOutNumber:A})}updateCustomerInfo(A){const e=this.get("displayText");if(A&&e){const{contact_count:e,customer_name:t,phone:s,city:i,province:n,is_vip:o,in_contact_count:r,trace_id:a,contact_count_month:V,in_contact_count_month:c}=A;ae.emit(exports.CallSipCallEventEnum.CUSTOMER_INFO,{customer_name:t||"未知客户",phone:s,city:i||"未知",province:n||"未知",contact_count:e||0,in_contact_count:r||0,is_vip:o,trace_id:a,contact_count_month:V||0,in_contact_count_month:c||0})}else ae.emit(exports.CallSipCallEventEnum.CUSTOMER_INFO,void 0);this.setState({customerObject:A})}updateIsNextState(A){this.setState({isNextState:A}),A?ae.emit(exports.EventName.NETWORK_ONLINE):(Ve.stateObject={state:exports.AgentStatus.OFFLINE,state_name:"离线"},this.updateActionConfigs([]),ae.emit(exports.CallSipCallEventEnum.AGENT_STATE,Ve.stateObject),ae.emit(exports.EventName.NETWORK_OFFLINE))}reset(){this.updateIsCalling(ce.isCalling),this.updateDirection(ce.direction),this.updateOutCallIsAnswer(ce.outCallIsAnswer),this.updateIsHold(ce.isHold),this.updateDisplayText(ce.displayText),this.updateActionConfigs(ce.actionConfigs),this.updateConsultIsAnswer(ce.consultIsAnswer),this.updateIsMuted(ce.isMuted),this.updateIncomingIsAnswer(ce.incomingIsAnswer),this.updateIsMeeting(ce.isMeeting),this.updateTransferIsAnswer(ce.transferIsAnswer),this.updateCustomerInfo(void 0)}getCallInfo(){return this.getState()}get(A){return this.getState()[A]}}(ce);const he=new class extends $A{updateRttObject(A){this.setState({rttObject:A}),ae.emit(exports.EventName.WEBSITE_DELAY,A)}}({rttObject:{rtt:null,jitter:null,packetsLost:null,packetsReceived:null,packetsSent:null,sendBitrate:null,recvBitrate:null,codec:null}});class ge{constructor(A,e){this.config=A,this.eventCallback=e,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.isManuallyStopped=!1,this.registerIntervalTimer=null,this.registerInterval=6e4,this.handleNetworkInfoChange=A=>{if(A.rttObject?.rtt){0===(A.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()},he.subscribe(this.handleNetworkInfoChange)}async start(){const A=_A.makeURI(`sip:${this.config.user}@${this.config.server}`);if(!A)throw new Error("无效的SIP配置");const e={uri:A,authorizationUsername:this.config.user,authorizationPassword:this.config.password,transportOptions:{server:this.config.webSocket,connectionTimeout:30,keepAliveInterval:20},contactName:this.config.user,contactParams:{transport:"wss"},userAgentString:"SwiftSIP/1.1.19",sessionDescriptionHandlerFactoryOptions:{alwaysAcquireMediaFirst:!0,peerConnectionConfiguration:{iceServers:[{urls:"stun:stun.qq.com:3478"},{urls:"stun:stun.agora.io:3478"}]},iceGatheringTimeout:800},logBuiltinEnabled:Ve.logBuiltinEnabled};this.userAgent=new _A(e),this.setupEventListeners(),await this.userAgent.start(),await this.register()}setupEventListeners(){this.userAgent&&(this.userAgent.transport.stateChange.addListener(A=>{let e;switch(A){case AA.Connecting:e=exports.WebRtcCallSipEventEnum.WEB_RTC_CONNECTING;break;case AA.Connected:e=exports.WebRtcCallSipEventEnum.WEB_RTC_CONNECTED,this.reconnectAttempts=0,Ve.isRtcReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);break;case AA.Disconnecting:e=exports.WebRtcCallSipEventEnum.WEB_RTC_DISCONNECTING;break;case AA.Disconnected:{if(this.isManuallyStopped)return void console.warn("[SIP] 手动断开,不触发重连");e=exports.WebRtcCallSipEventEnum.WEB_RTC_DISCONNECTED;const A=le.get("answerDevice");if(!Ve.isRtcReconnecting&&this.reconnectAttempts<this.maxReconnectAttempts&&1===A){this.reconnectAttempts++;const A=1e3*this.reconnectAttempts;console.warn(`SIP WebSocket 断开,第 ${this.reconnectAttempts} 次尝试重连,${A}ms 后重试...`),this.reconnectTimer=setTimeout(()=>{this.reconnect()},A)}else this.reconnectAttempts>=this.maxReconnectAttempts&&console.error("SIP 重连失败:已达到最大重试次数");break}default:e="unknown"}this.eventCallback?.({type:e})}),this.userAgent.delegate={onInvite:A=>{this.handleIncomingCall(A)}})}async refreshRegister(){if(this.registerer)try{await this.registerer.register(),(new Date).toLocaleTimeString()}catch(A){console.error("[SIPClient] REGISTER刷新失败",A)}}async register(){if(this.userAgent){this.registerer=new nA(this.userAgent),this.registerer?.stateChange.addListener(A=>{let e;switch(A){case _.Initial:e="initial";break;case _.Registered:e=exports.WebRtcCallSipEventEnum.WEB_RTC_REGISTERED;break;case _.Unregistered:e=exports.WebRtcCallSipEventEnum.WEB_RTC_UNREGISTERED;break;case _.Terminated:e=exports.WebRtcCallSipEventEnum.WEB_RTC_TERMINATED;break;default:e="unknown"}this.eventCallback?.({type:e})});try{await this.registerer.register(),this.registerIntervalTimer||(this.registerIntervalTimer=setInterval(()=>{this.refreshRegister()},this.registerInterval))}catch(A){this.eventCallback?.({type:exports.WebRtcCallSipEventEnum.WEB_RTC_REGISTER_FAILED,data:A})}}}attachRemoteAudio(A){const e=A.sessionDescriptionHandler;if(e){const A=e.peerConnection;if(!A)return;const t=new MediaStream;A.getReceivers().forEach(A=>{A.track&&"audio"===A.track.kind&&t.addTrack(A.track)});let s=document.getElementById("sip-remote-audio");s||(s=document.createElement("audio"),s.id="sip-remote-audio",s.autoplay=!0,s.style.display="none",document.body.appendChild(s)),s.srcObject=t,s.play().catch(A=>{console.error("音频播放失败,需要用户交互触发",A)})}}handleSessionState(A,e,t){A.stateChange.addListener(e=>{switch(e){case H.Established:clearTimeout(this.callTimeoutTimer),this.activeSession=A,this.attachRemoteAudio(A);break;case H.Terminating:break;case H.Terminated:this.activeSession=null,clearTimeout(this.callTimeoutTimer);case H.Establishing:}})}handleIncomingCall(A){this.incomingInvitation=A,this.handleSessionState(A,!1);le.get("direction")===exports.DirectionEnum.OUTGOING&&this.answerCall()}async answerCall(){if(!this.incomingInvitation)throw new Error("无来电可接听");Ve.autoAnswerTimer&&(clearTimeout(Ve.autoAnswerTimer),Ve.autoAnswerTimer=null);try{await this.incomingInvitation.accept(),this.activeSession=this.incomingInvitation,this.incomingInvitation=null}catch(A){this.eventCallback?.({type:exports.WebRtcCallSipEventEnum.WEB_RTC_ANSWER_FAILED,data:{detail:A}})}}async rejectInCall(){if(this.incomingInvitation)try{await this.incomingInvitation.reject(),this.incomingInvitation=null,le.updateDirection(null),le.updateIsCalling(!1),clearTimeout(this.callTimeoutTimer)}catch(A){this.eventCallback?.({type:"error",data:{message:"拒接失败",detail:A}})}}sendDTMF(A){if(!this.activeSession)throw new Error("当前没有活跃的通话");const e=this.activeSession.sessionDescriptionHandler;e&&"function"==typeof e.sendDtmf?(e.sendDtmf(A),this.eventCallback?.({type:exports.WebRtcCallSipEventEnum.WEB_RTC_SEND_DTMF,data:{tone:A}})):console.warn("DTMF发送不支持或未初始化")}async hangup(){if(this.activeSession,this.activeSession){clearTimeout(this.callTimeoutTimer);const A=this.activeSession;if(!A)return;const e=A.state;try{e===H.Established?await A.bye():e===H.Establishing&&(A instanceof X?await A.cancel():A instanceof z&&await A.reject()),clearTimeout(this.callTimeoutTimer)}catch(A){console.error("挂断失败",A)}finally{this.activeSession=null}}}async rejectOutCall(){this.activeSession instanceof z&&(await this.activeSession.reject(),this.activeSession=null)}async destroy(){if(this.isManuallyStopped=!0,clearTimeout(this.callTimeoutTimer),clearInterval(this.registerIntervalTimer),this.activeSession&&await this.hangup(),this.registerIntervalTimer&&(clearInterval(this.registerIntervalTimer),this.registerIntervalTimer=null),this.registerer){try{await this.registerer.unregister()}catch(A){console.warn("注销失败",A)}this.registerer=null}this.userAgent&&(await this.userAgent.stop(),this.userAgent=null)}async reconnect(){if(!Ve.isRtcReconnecting){Ve.isRtcReconnecting=!0;try{await this.destroy(),await this.start(),this.isOffline=!1}catch(A){console.error("重连失败",A)}finally{Ve.isRtcReconnecting=!1}}}async getNetworkStats(){if(this.activeSession){const A=this.activeSession.sessionDescriptionHandler?.peerConnection;if(!A)return null;const e=await A.getStats(),t={};return e.forEach(A=>{"candidate-pair"===A.type&&"succeeded"===A.state&&null!=A.currentRoundTripTime&&(t.rtt=+(1e3*A.currentRoundTripTime).toFixed(2)),"inbound-rtp"===A.type&&"audio"===A.kind&&(t.jitter=+(1e3*A.jitter).toFixed(2),t.packetsLost=A.packetsLost,t.packetsReceived=A.packetsReceived,A.bytesReceived&&A.timestamp&&(t.recvBitrate=+(A.bytesReceived/1024).toFixed(2))),"outbound-rtp"===A.type&&"audio"===A.kind&&(t.packetsSent=A.packetsSent,A.bytesSent&&A.timestamp&&(t.sendBitrate=+(A.bytesSent/1024).toFixed(2))),"codec"===A.type&&A.mimeType&&(t.codec=A.mimeType)}),{...t,rtt:t?.rtt||40}}return{rtt:Ve.latency||1}}}
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2019 Google LLC
|
|
5
5
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
6
|
-
*/const qe=globalThis,de=qe.ShadowRoot&&(void 0===qe.ShadyCSS||qe.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,pe=Symbol(),ue=new WeakMap;let me=class{constructor(A,e,t){if(this._$cssResult$=!0,t!==pe)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=A,this.t=e}get styleSheet(){let A=this.o;const e=this.t;if(de&&void 0===A){const t=void 0!==e&&1===e.length;t&&(A=ue.get(e)),void 0===A&&((this.o=A=new CSSStyleSheet).replaceSync(this.cssText),t&&ue.set(e,A))}return A}toString(){return this.cssText}};const
|
|
6
|
+
*/const qe=globalThis,de=qe.ShadowRoot&&(void 0===qe.ShadyCSS||qe.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,pe=Symbol(),ue=new WeakMap;let me=class{constructor(A,e,t){if(this._$cssResult$=!0,t!==pe)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=A,this.t=e}get styleSheet(){let A=this.o;const e=this.t;if(de&&void 0===A){const t=void 0!==e&&1===e.length;t&&(A=ue.get(e)),void 0===A&&((this.o=A=new CSSStyleSheet).replaceSync(this.cssText),t&&ue.set(e,A))}return A}toString(){return this.cssText}};const Ee=(A,...e)=>{const t=1===A.length?A[0]:e.reduce((e,t,s)=>e+(A=>{if(!0===A._$cssResult$)return A.cssText;if("number"==typeof A)return A;throw Error("Value passed to 'css' function must be a 'css' function result: "+A+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(t)+A[s+1],A[0]);return new me(t,A,pe)},Ce=de?A=>A:A=>A instanceof CSSStyleSheet?(A=>{let e="";for(const t of A.cssRules)e+=t.cssText;return(A=>new me("string"==typeof A?A:A+"",void 0,pe))(e)})(A):A,{is:Ie,defineProperty:Me,getOwnPropertyDescriptor:we,getOwnPropertyNames:fe,getOwnPropertySymbols:Be,getPrototypeOf:Se}=Object,Qe=globalThis,Te=Qe.trustedTypes,ye=Te?Te.emptyScript:"",De=Qe.reactiveElementPolyfillSupport,Re=(A,e)=>A,Ue={toAttribute(A,e){switch(e){case Boolean:A=A?ye:null;break;case Object:case Array:A=null==A?A:JSON.stringify(A)}return A},fromAttribute(A,e){let t=A;switch(e){case Boolean:t=null!==A;break;case Number:t=null===A?null:Number(A);break;case Object:case Array:try{t=JSON.parse(A)}catch(A){t=null}}return t}},ke=(A,e)=>!Ie(A,e),Ge={attribute:!0,type:String,converter:Ue,reflect:!1,useDefault:!1,hasChanged:ke};
|
|
7
7
|
/**
|
|
8
8
|
* @license
|
|
9
9
|
* Copyright 2017 Google LLC
|
|
10
10
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
11
|
-
*/Symbol.metadata??=Symbol("metadata"),Qe.litPropertyMetadata??=new WeakMap;let Fe=class extends HTMLElement{static addInitializer(A){this._$Ei(),(this.l??=[]).push(A)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(A,e=Ge){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(A)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(A,e),!e.noAccessor){const t=Symbol(),s=this.getPropertyDescriptor(A,t,e);void 0!==s&&
|
|
11
|
+
*/Symbol.metadata??=Symbol("metadata"),Qe.litPropertyMetadata??=new WeakMap;let Fe=class extends HTMLElement{static addInitializer(A){this._$Ei(),(this.l??=[]).push(A)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(A,e=Ge){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(A)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(A,e),!e.noAccessor){const t=Symbol(),s=this.getPropertyDescriptor(A,t,e);void 0!==s&&Me(this.prototype,A,s)}}static getPropertyDescriptor(A,e,t){const{get:s,set:i}=we(this.prototype,A)??{get(){return this[e]},set(A){this[e]=A}};return{get:s,set(e){const n=s?.call(this);i?.call(this,e),this.requestUpdate(A,n,t)},configurable:!0,enumerable:!0}}static getPropertyOptions(A){return this.elementProperties.get(A)??Ge}static _$Ei(){if(this.hasOwnProperty(Re("elementProperties")))return;const A=Se(this);A.finalize(),void 0!==A.l&&(this.l=[...A.l]),this.elementProperties=new Map(A.elementProperties)}static finalize(){if(this.hasOwnProperty(Re("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Re("properties"))){const A=this.properties,e=[...fe(A),...Be(A)];for(const t of e)this.createProperty(t,A[t])}const A=this[Symbol.metadata];if(null!==A){const e=litPropertyMetadata.get(A);if(void 0!==e)for(const[A,t]of e)this.elementProperties.set(A,t)}this._$Eh=new Map;for(const[A,e]of this.elementProperties){const t=this._$Eu(A,e);void 0!==t&&this._$Eh.set(t,A)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(A){const e=[];if(Array.isArray(A)){const t=new Set(A.flat(1/0).reverse());for(const A of t)e.unshift(Ce(A))}else void 0!==A&&e.push(Ce(A));return e}static _$Eu(A,e){const t=e.attribute;return!1===t?void 0:"string"==typeof t?t:"string"==typeof A?A.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(A=>this.enableUpdating=A),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(A=>A(this))}addController(A){(this._$EO??=new Set).add(A),void 0!==this.renderRoot&&this.isConnected&&A.hostConnected?.()}removeController(A){this._$EO?.delete(A)}_$E_(){const A=new Map,e=this.constructor.elementProperties;for(const t of e.keys())this.hasOwnProperty(t)&&(A.set(t,this[t]),delete this[t]);A.size>0&&(this._$Ep=A)}createRenderRoot(){const A=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((A,e)=>{if(de)A.adoptedStyleSheets=e.map(A=>A instanceof CSSStyleSheet?A:A.styleSheet);else for(const t of e){const e=document.createElement("style"),s=qe.litNonce;void 0!==s&&e.setAttribute("nonce",s),e.textContent=t.cssText,A.appendChild(e)}})(A,this.constructor.elementStyles),A}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(A=>A.hostConnected?.())}enableUpdating(A){}disconnectedCallback(){this._$EO?.forEach(A=>A.hostDisconnected?.())}attributeChangedCallback(A,e,t){this._$AK(A,t)}_$ET(A,e){const t=this.constructor.elementProperties.get(A),s=this.constructor._$Eu(A,t);if(void 0!==s&&!0===t.reflect){const i=(void 0!==t.converter?.toAttribute?t.converter:Ue).toAttribute(e,t.type);this._$Em=A,null==i?this.removeAttribute(s):this.setAttribute(s,i),this._$Em=null}}_$AK(A,e){const t=this.constructor,s=t._$Eh.get(A);if(void 0!==s&&this._$Em!==s){const A=t.getPropertyOptions(s),i="function"==typeof A.converter?{fromAttribute:A.converter}:void 0!==A.converter?.fromAttribute?A.converter:Ue;this._$Em=s;const n=i.fromAttribute(e,A.type);this[s]=n??this._$Ej?.get(s)??n,this._$Em=null}}requestUpdate(A,e,t){if(void 0!==A){const s=this.constructor,i=this[A];if(t??=s.getPropertyOptions(A),!((t.hasChanged??ke)(i,e)||t.useDefault&&t.reflect&&i===this._$Ej?.get(A)&&!this.hasAttribute(s._$Eu(A,t))))return;this.C(A,e,t)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(A,e,{useDefault:t,reflect:s,wrapped:i},n){t&&!(this._$Ej??=new Map).has(A)&&(this._$Ej.set(A,n??e??this[A]),!0!==i||void 0!==n)||(this._$AL.has(A)||(this.hasUpdated||t||(e=void 0),this._$AL.set(A,e)),!0===s&&this._$Em!==A&&(this._$Eq??=new Set).add(A))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(A){Promise.reject(A)}const A=this.scheduleUpdate();return null!=A&&await A,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[A,e]of this._$Ep)this[A]=e;this._$Ep=void 0}const A=this.constructor.elementProperties;if(A.size>0)for(const[e,t]of A){const{wrapped:A}=t,s=this[e];!0!==A||this._$AL.has(e)||void 0===s||this.C(e,void 0,t,s)}}let A=!1;const e=this._$AL;try{A=this.shouldUpdate(e),A?(this.willUpdate(e),this._$EO?.forEach(A=>A.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw A=!1,this._$EM(),e}A&&this._$AE(e)}willUpdate(A){}_$AE(A){this._$EO?.forEach(A=>A.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(A)),this.updated(A)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(A){return!0}update(A){this._$Eq&&=this._$Eq.forEach(A=>this._$ET(A,this[A])),this._$EM()}updated(A){}firstUpdated(A){}};Fe.elementStyles=[],Fe.shadowRootOptions={mode:"open"},Fe[Re("elementProperties")]=new Map,Fe[Re("finalized")]=new Map,De?.({ReactiveElement:Fe}),(Qe.reactiveElementVersions??=[]).push("2.1.1");
|
|
12
12
|
/**
|
|
13
13
|
* @license
|
|
14
14
|
* Copyright 2017 Google LLC
|
|
@@ -19,7 +19,7 @@ const Ye=globalThis,xe=Ye.trustedTypes,ve=xe?xe.createPolicy("lit-html",{createH
|
|
|
19
19
|
* @license
|
|
20
20
|
* Copyright 2017 Google LLC
|
|
21
21
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
22
|
-
*/},
|
|
22
|
+
*/},Et=globalThis;class Ct extends Fe{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const A=super.createRenderRoot();return this.renderOptions.renderBefore??=A.firstChild,A}update(A){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(A),this._$Do=mt(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return tt}}Ct._$litElement$=!0,Ct.finalized=!0,Et.litElementHydrateSupport?.({LitElement:Ct});const It=Et.litElementPolyfillSupport;It?.({LitElement:Ct}),(Et.litElementVersions??=[]).push("4.2.1");const Mt={statusColor:{[exports.AgentStatus.IDLE]:"#1D92E9",[exports.AgentStatus.BUSY]:"#F5212D",[exports.AgentStatus.OFFLINE]:"#8c8c8c",[exports.AgentStatus.RINGING]:"#e9b91d"}},wt=[],ft=["call_number"],Bt=["call_number"],St=["hangup"],Qt=["hold","hangup","mute","transfer","consult","satisfaction","dtmf"],Tt=["consult_transfer","conference","consult_retrieve"],yt=["hangup"],Dt=["hangup"],Rt=["answer","reject"],Ut=["hangup","consult","transfer","hold","mute","satisfaction","dtmf"],kt=["hangup","whisper","force_insert","force_disconnect"],Gt=["hangup"],Ft=["hangup","cancel_whisper","force_insert"],Yt=["hangup"],xt=["hangup"];function vt(A,e,t,s){var i,n=arguments.length,o=n<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,t):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(A,e,t,s);else for(var r=A.length-1;r>=0;r--)(i=A[r])&&(o=(n<3?i(o):n>3?i(e,t,o):i(e,t))||o);return n>3&&o&&Object.defineProperty(e,t,o),o}"function"==typeof SuppressedError&&SuppressedError;
|
|
23
23
|
/**
|
|
24
24
|
* @license
|
|
25
25
|
* Copyright 2017 Google LLC
|
|
@@ -45,13 +45,13 @@ const Zt=A=>(e,t)=>{void 0!==t?t.addInitializer(()=>{customElements.define(A,e)}
|
|
|
45
45
|
* @license
|
|
46
46
|
* Copyright 2017 Google LLC
|
|
47
47
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
48
|
-
*/let Lt=class extends
|
|
48
|
+
*/let Lt=class extends Ct{static{this.styles=Ee`
|
|
49
49
|
.timer-text {
|
|
50
50
|
width: 70px;
|
|
51
51
|
font-size: 14px;
|
|
52
52
|
color: #fff;
|
|
53
53
|
}
|
|
54
|
-
`}constructor(){super(),this.intervalId=null,this.elapsedSeconds=0,this.displayTime="00:00:00",this.start()}formatTime(A){const e=A=>A.toString().padStart(2,"0"),t=Math.floor(A/3600),s=Math.floor(A%3600/60),i=A%60;return`${e(t)}:${e(s)}:${e(i)}`}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 et`<div class="timer-text">${this.displayTime}</div>`}};vt([bt()],Lt.prototype,"displayTime",void 0),Lt=vt([Zt("timer-component")],Lt);let Ht=class extends
|
|
54
|
+
`}constructor(){super(),this.intervalId=null,this.elapsedSeconds=0,this.displayTime="00:00:00",this.start()}formatTime(A){const e=A=>A.toString().padStart(2,"0"),t=Math.floor(A/3600),s=Math.floor(A%3600/60),i=A%60;return`${e(t)}:${e(s)}:${e(i)}`}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 et`<div class="timer-text">${this.displayTime}</div>`}};vt([bt()],Lt.prototype,"displayTime",void 0),Lt=vt([Zt("timer-component")],Lt);let Ht=class extends Ct{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=Ee`
|
|
55
55
|
:host {
|
|
56
56
|
position: relative;
|
|
57
57
|
display: inline-block;
|
|
@@ -100,7 +100,7 @@ const Zt=A=>(e,t)=>{void 0!==t?t.addInitializer(()=>{customElements.define(A,e)}
|
|
|
100
100
|
<div class="tooltip ${this.placement} ${this.visible?"visible":""}" style="background: ${this.color}">
|
|
101
101
|
${this.content}
|
|
102
102
|
</div>
|
|
103
|
-
`}};vt([Kt({type:String})],Ht.prototype,"content",void 0),vt([Kt({type:String})],Ht.prototype,"placement",void 0),vt([Kt({type:Number})],Ht.prototype,"delay",void 0),vt([Kt({type:String})],Ht.prototype,"color",void 0),vt([Kt({type:Boolean})],Ht.prototype,"visible",void 0),vt([function(A,e){return(t,s,i)=>{const n=e=>e.renderRoot?.querySelector(A)??null;if(e){const{get:A,set:e}="object"==typeof s?t:i??(()=>{const A=Symbol();return{get(){return this[A]},set(e){this[A]=e}}})();return Jt(t,s,{get(){let t=A.call(this);return void 0===t&&(t=n(this),(null!==t||this.hasUpdated)&&e.call(this,t)),t}})}return Jt(t,s,{get(){return n(this)}})}}("slot")],Ht.prototype,"slotElement",void 0),Ht=vt([Zt("my-tooltip")],Ht);let jt=class extends
|
|
103
|
+
`}};vt([Kt({type:String})],Ht.prototype,"content",void 0),vt([Kt({type:String})],Ht.prototype,"placement",void 0),vt([Kt({type:Number})],Ht.prototype,"delay",void 0),vt([Kt({type:String})],Ht.prototype,"color",void 0),vt([Kt({type:Boolean})],Ht.prototype,"visible",void 0),vt([function(A,e){return(t,s,i)=>{const n=e=>e.renderRoot?.querySelector(A)??null;if(e){const{get:A,set:e}="object"==typeof s?t:i??(()=>{const A=Symbol();return{get(){return this[A]},set(e){this[A]=e}}})();return Jt(t,s,{get(){let t=A.call(this);return void 0===t&&(t=n(this),(null!==t||this.hasUpdated)&&e.call(this,t)),t}})}return Jt(t,s,{get(){return n(this)}})}}("slot")],Ht.prototype,"slotElement",void 0),Ht=vt([Zt("my-tooltip")],Ht);let jt=class extends Ct{constructor(){super(...arguments),this.placement="bottom",this.triggerType="click",this.visible=!1,this.hideTimer=null,this.onTogglePopover=A=>{A.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=A=>{this.contains(A.target)||(this.visible=!1)}}static{this.styles=Ee`
|
|
104
104
|
:host {
|
|
105
105
|
display: inline-block;
|
|
106
106
|
position: relative;
|
|
@@ -185,7 +185,7 @@ const Zt=A=>(e,t)=>{void 0!==t?t.addInitializer(()=>{customElements.define(A,e)}
|
|
|
185
185
|
<div class="arrow" data-placement="${this.placement}"></div>
|
|
186
186
|
<slot name="content"></slot>
|
|
187
187
|
</div>
|
|
188
|
-
`}};vt([Kt({type:String})],jt.prototype,"placement",void 0),vt([Kt({type:String})],jt.prototype,"triggerType",void 0),vt([bt()],jt.prototype,"visible",void 0),jt=vt([Zt("my-popover")],jt);let Wt=class extends
|
|
188
|
+
`}};vt([Kt({type:String})],jt.prototype,"placement",void 0),vt([Kt({type:String})],jt.prototype,"triggerType",void 0),vt([bt()],jt.prototype,"visible",void 0),jt=vt([Zt("my-popover")],jt);let Wt=class extends Ct{constructor(){super(...arguments),this.placeholder="",this.disabled=!1,this.allowClear=!1,this.value="",this.focused=!1}static{this.styles=Ee`
|
|
189
189
|
:host {
|
|
190
190
|
display: inline-block;
|
|
191
191
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, serif;
|
|
@@ -273,7 +273,7 @@ const Zt=A=>(e,t)=>{void 0!==t?t.addInitializer(()=>{customElements.define(A,e)}
|
|
|
273
273
|
</span>
|
|
274
274
|
<span class="suffix"><slot name="suffix"></slot></span>
|
|
275
275
|
</div>
|
|
276
|
-
`}};vt([Kt({type:String})],Wt.prototype,"placeholder",void 0),vt([Kt({type:Boolean})],Wt.prototype,"disabled",void 0),vt([Kt({type:Boolean})],Wt.prototype,"allowClear",void 0),vt([Kt({type:String})],Wt.prototype,"value",void 0),vt([Kt({attribute:!1})],Wt.prototype,"onPressEnter",void 0),vt([bt()],Wt.prototype,"focused",void 0),Wt=vt([Zt("my-input")],Wt);let Pt=class extends
|
|
276
|
+
`}};vt([Kt({type:String})],Wt.prototype,"placeholder",void 0),vt([Kt({type:Boolean})],Wt.prototype,"disabled",void 0),vt([Kt({type:Boolean})],Wt.prototype,"allowClear",void 0),vt([Kt({type:String})],Wt.prototype,"value",void 0),vt([Kt({attribute:!1})],Wt.prototype,"onPressEnter",void 0),vt([bt()],Wt.prototype,"focused",void 0),Wt=vt([Zt("my-input")],Wt);let Pt=class extends Ct{constructor(){super(...arguments),this.placeholder="请选择",this.value=null,this.width="200px",this.open=!1,this.animating=!1,this.selectedContent=null,this.handleOutsideClick=A=>{this.contains(A.target)||this.closeDropdown()}}static{this.styles=Ee`
|
|
277
277
|
:host {
|
|
278
278
|
position: relative;
|
|
279
279
|
display: inline-block;
|
|
@@ -348,7 +348,7 @@ const Zt=A=>(e,t)=>{void 0!==t?t.addInitializer(()=>{customElements.define(A,e)}
|
|
|
348
348
|
${this.renderSelectedLabel()}
|
|
349
349
|
</div>
|
|
350
350
|
${this.open?et`<div class="dropdown ${this.animating?"show":""}">${this.renderSelectOptions()}</div>`:st}
|
|
351
|
-
`}};vt([Kt({type:String})],Pt.prototype,"placeholder",void 0),vt([Kt({type:String})],Pt.prototype,"value",void 0),vt([Kt({type:String})],Pt.prototype,"width",void 0),vt([bt()],Pt.prototype,"open",void 0),vt([bt()],Pt.prototype,"animating",void 0),vt([bt()],Pt.prototype,"selectedContent",void 0),Pt=vt([Zt("my-select")],Pt);let zt=class extends
|
|
351
|
+
`}};vt([Kt({type:String})],Pt.prototype,"placeholder",void 0),vt([Kt({type:String})],Pt.prototype,"value",void 0),vt([Kt({type:String})],Pt.prototype,"width",void 0),vt([bt()],Pt.prototype,"open",void 0),vt([bt()],Pt.prototype,"animating",void 0),vt([bt()],Pt.prototype,"selectedContent",void 0),Pt=vt([Zt("my-select")],Pt);let zt=class extends Ct{constructor(){super(...arguments),this.isDialerVisible=!1,this.inputValue="",this.keys=["1","2","3","4","5","6","7","8","9","*","0","#"],this.handleDocumentClick=A=>{(A.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=Ee`
|
|
352
352
|
.key-body {
|
|
353
353
|
position: absolute;
|
|
354
354
|
border: 1px solid rgba(0, 0, 0, 0.2);
|
|
@@ -404,7 +404,7 @@ const Zt=A=>(e,t)=>{void 0!==t?t.addInitializer(()=>{customElements.define(A,e)}
|
|
|
404
404
|
</div>
|
|
405
405
|
</div>
|
|
406
406
|
`:st}
|
|
407
|
-
`}};vt([bt()],zt.prototype,"isDialerVisible",void 0),vt([bt()],zt.prototype,"inputValue",void 0),zt=vt([Zt("my-phone-dialer")],zt);let Xt=class extends
|
|
407
|
+
`}};vt([bt()],zt.prototype,"isDialerVisible",void 0),vt([bt()],zt.prototype,"inputValue",void 0),zt=vt([Zt("my-phone-dialer")],zt);let Xt=class extends Ct{constructor(){super(...arguments),this.visible=!1,this.showFooter=!0,this.width="520px",this.title=""}static{this.styles=Ee`
|
|
408
408
|
.mask {
|
|
409
409
|
position: fixed;
|
|
410
410
|
z-index: 9999999;
|
|
@@ -478,7 +478,7 @@ const Zt=A=>(e,t)=>{void 0!==t?t.addInitializer(()=>{customElements.define(A,e)}
|
|
|
478
478
|
`:null}
|
|
479
479
|
</div>
|
|
480
480
|
</div>
|
|
481
|
-
`:et``}_onCancel(){this.dispatchEvent(new CustomEvent("cancel")),this.visible=!1}_onOk(){this.dispatchEvent(new CustomEvent("ok"))}_onMaskClick(){this._onCancel()}};vt([Kt({type:Boolean})],Xt.prototype,"visible",void 0),vt([Kt({type:Boolean})],Xt.prototype,"showFooter",void 0),vt([Kt({type:String})],Xt.prototype,"width",void 0),vt([Kt({type:String})],Xt.prototype,"title",void 0),Xt=vt([Zt("my-modal-wrapper")],Xt);let _t=class extends
|
|
481
|
+
`:et``}_onCancel(){this.dispatchEvent(new CustomEvent("cancel")),this.visible=!1}_onOk(){this.dispatchEvent(new CustomEvent("ok"))}_onMaskClick(){this._onCancel()}};vt([Kt({type:Boolean})],Xt.prototype,"visible",void 0),vt([Kt({type:Boolean})],Xt.prototype,"showFooter",void 0),vt([Kt({type:String})],Xt.prototype,"width",void 0),vt([Kt({type:String})],Xt.prototype,"title",void 0),Xt=vt([Zt("my-modal-wrapper")],Xt);let _t=class extends Ct{constructor(){super(...arguments),this.open=!1,this.onDocumentClick=A=>{this.contains(A.target)||(this.open=!1)}}static{this.styles=Ee`
|
|
482
482
|
:host {
|
|
483
483
|
position: relative;
|
|
484
484
|
display: inline-block;
|
|
@@ -513,8 +513,8 @@ const Zt=A=>(e,t)=>{void 0!==t?t.addInitializer(()=>{customElements.define(A,e)}
|
|
|
513
513
|
<div class="popup ${this.open?"":"hidden"}">
|
|
514
514
|
<slot name="content"></slot>
|
|
515
515
|
</div>
|
|
516
|
-
`}};vt([bt()],_t.prototype,"open",void 0),_t=vt([Zt("my-icon-popup")],_t);class $t extends Error{response;request;options;constructor(A,e,t){const s=`${A.status||0===A.status?A.status:""} ${A.statusText||""}`.trim();super(`Request failed with ${s?`status code ${s}`:"an unknown error"}: ${e.method} ${e.url}`),this.name="HTTPError",this.response=A,this.request=e,this.options=t}}class As extends Error{request;constructor(A){super(`Request timed out: ${A.method} ${A.url}`),this.name="TimeoutError",this.request=A}}const es=(()=>{let A=!1,e=!1;const t="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;if(t&&s)try{e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return A=!0,"half"}}).headers.has("Content-Type")}catch(A){if(A instanceof Error&&"unsupported BodyInit type"===A.message)return!1;throw A}return A&&!e})(),ts="function"==typeof globalThis.AbortController,ss="function"==typeof globalThis.AbortSignal&&"function"==typeof globalThis.AbortSignal.any,is="function"==typeof globalThis.ReadableStream,ns="function"==typeof globalThis.FormData,os=["get","post","put","patch","head","delete"],rs={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},as=2147483647,Vs=(new TextEncoder).encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,cs=Symbol("stop"),ls={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},hs={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},gs=(A,e)=>{const t=(A=>{if(!A)return 0;if(A instanceof FormData){let e=0;for(const[t,s]of A)e+=Vs,e+=(new TextEncoder).encode(`Content-Disposition: form-data; name="${t}"`).length,e+="string"==typeof s?(new TextEncoder).encode(s).length:s.size;return e}if(A instanceof Blob)return A.size;if(A instanceof ArrayBuffer)return A.byteLength;if("string"==typeof A)return(new TextEncoder).encode(A).length;if(A instanceof URLSearchParams)return(new TextEncoder).encode(A.toString()).length;if("byteLength"in A)return A.byteLength;if("object"==typeof A&&null!==A)try{const e=JSON.stringify(A);return(new TextEncoder).encode(e).length}catch{return 0}return 0})(A.body);let s=0;return new Request(A,{duplex:"half",body:new ReadableStream({async start(i){const n=A.body instanceof ReadableStream?A.body.getReader():new Response("").body.getReader();await async function A(){const{done:o,value:r}=await n.read();if(o)return e&&e({percent:1,transferredBytes:s,totalBytes:Math.max(t,s)},new Uint8Array),void i.close();s+=r.byteLength;let a=0===t?0:s/t;(t<s||1===a)&&(a=.99),e&&e({percent:Number(a.toFixed(2)),transferredBytes:s,totalBytes:t},r),i.enqueue(r),await A()}()}})})},qs=A=>null!==A&&"object"==typeof A,ds=(...A)=>{for(const e of A)if((!qs(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return Cs({},...A)},ps=(A={},e={})=>{const t=new globalThis.Headers(A),s=e instanceof globalThis.Headers,i=new globalThis.Headers(e);for(const[A,e]of i.entries())s&&"undefined"===e||void 0===e?t.delete(A):t.set(A,e);return t};function us(A,e,t){return Object.hasOwn(e,t)&&void 0===e[t]?[]:Cs(A[t]??[],e[t]??[])}const ms=(A={},e={})=>({beforeRequest:us(A,e,"beforeRequest"),beforeRetry:us(A,e,"beforeRetry"),afterResponse:us(A,e,"afterResponse"),beforeError:us(A,e,"beforeError")}),Cs=(...A)=>{let e={},t={},s={};for(const i of A)if(Array.isArray(i))Array.isArray(e)||(e=[]),e=[...e,...i];else if(qs(i)){for(let[A,t]of Object.entries(i))qs(t)&&A in e&&(t=Cs(e[A],t)),e={...e,[A]:t};qs(i.hooks)&&(s=ms(s,i.hooks),e.hooks=s),qs(i.headers)&&(t=ps(t,i.headers),e.headers=t)}return e},Es=A=>os.includes(A)?A.toUpperCase():A,Is={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:A=>.3*2**(A-1)*1e3},ws=(A={})=>{if("number"==typeof A)return{...Is,limit:A};if(A.methods&&!Array.isArray(A.methods))throw new Error("retry.methods must be an array");if(A.statusCodes&&!Array.isArray(A.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Is,...A}};class Ms{static create(A,e){const t=new Ms(A,e),s=async()=>{if("number"==typeof t._options.timeout&&t._options.timeout>as)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let A=await t._fetch();for(const e of t._options.hooks.afterResponse){const s=await e(t.request,t._options,t._decorateResponse(A.clone()));s instanceof globalThis.Response&&(A=s)}if(t._decorateResponse(A),!A.ok&&t._options.throwHttpErrors){let e=new $t(A,t.request,t._options);for(const A of t._options.hooks.beforeError)e=await A(e);throw e}if(t._options.onDownloadProgress){if("function"!=typeof t._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!is)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return((A,e)=>{const t=Number(A.headers.get("content-length"))||0;let s=0;return 204===A.status?(e&&e({percent:1,totalBytes:t,transferredBytes:s},new Uint8Array),new Response(null,{status:A.status,statusText:A.statusText,headers:A.headers})):new Response(new ReadableStream({async start(i){const n=A.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:t},new Uint8Array),await async function A(){const{done:o,value:r}=await n.read();o?i.close():(e&&(s+=r.byteLength,e({percent:0===t?0:s/t,transferredBytes:s,totalBytes:t},r)),i.enqueue(r),await A())}()}}),{status:A.status,statusText:A.statusText,headers:A.headers})})(A.clone(),t._options.onDownloadProgress)}return A},i=(t._options.retry.methods.includes(t.request.method.toLowerCase())?t._retry(s):s()).finally(async()=>{t.request.bodyUsed||await(t.request.body?.cancel())});for(const[A,s]of Object.entries(rs))i[A]=async()=>{t.request.headers.set("accept",t.request.headers.get("accept")||s);const n=await i;if("json"===A){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(e.parseJson)return e.parseJson(await n.text())}return n[A]()};return i}request;abortController;_retryCount=0;_input;_options;constructor(A,e={}){if(this._input=A,this._options={...e,headers:ps(this._input.headers,e.headers),hooks:ms({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:Es(e.method??this._input.method??"GET"),prefixUrl:String(e.prefixUrl||""),retry:ws(e.retry),throwHttpErrors:!1!==e.throwHttpErrors,timeout:e.timeout??1e4,fetch:e.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(ts&&ss){const A=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=A?AbortSignal.any([A,this.abortController.signal]):this.abortController.signal}if(es&&(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 A="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),e=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,A);!(ns&&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(e,{...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(!es)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=gs(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(A){if(this._retryCount++,this._retryCount>this._options.retry.limit||A instanceof As)throw A;if(A instanceof $t){if(!this._options.retry.statusCodes.includes(A.response.status))throw A;const e=A.response.headers.get("Retry-After")??A.response.headers.get("RateLimit-Reset")??A.response.headers.get("X-RateLimit-Reset")??A.response.headers.get("X-Rate-Limit-Reset");if(e&&this._options.retry.afterStatusCodes.includes(A.response.status)){let A=1e3*Number(e);Number.isNaN(A)?A=Date.parse(e)-Date.now():A>=Date.parse("2024-01-01")&&(A-=Date.now());const t=this._options.retry.maxRetryAfter??A;return A<t?A:t}if(413===A.response.status)throw A}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}_decorateResponse(A){return this._options.parseJson&&(A.json=async()=>this._options.parseJson(await A.text())),A}async _retry(A){try{return await A()}catch(e){const t=Math.min(this._calculateRetryDelay(e),as);if(this._retryCount<1)throw e;await async function(A,{signal:e}){return new Promise((t,s)=>{function i(){clearTimeout(n),s(e.reason)}e&&(e.throwIfAborted(),e.addEventListener("abort",i,{once:!0}));const n=setTimeout(()=>{e?.removeEventListener("abort",i),t()},A)})}(t,{signal:this._options.signal});for(const A of this._options.hooks.beforeRetry){if(await A({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===cs)return}return this._retry(A)}}async _fetch(){for(const A of this._options.hooks.beforeRequest){const e=await A(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}const A=((A,e)=>{const t={};for(const s in e)s in hs||s in ls||s in A||(t[s]=e[s]);return t})(this.request,this._options),e=this.request;return this.request=e.clone(),!1===this._options.timeout?this._options.fetch(e,A):async function(A,e,t,s){return new Promise((i,n)=>{const o=setTimeout(()=>{t&&t.abort(),n(new As(A))},s.timeout);s.fetch(A,e).then(i).catch(n).then(()=>{clearTimeout(o)})})}(e,A,this.abortController,this._options)}}
|
|
517
|
-
/*! MIT License © Sindre Sorhus */const fs=A=>{const e=(e,t)=>
|
|
516
|
+
`}};vt([bt()],_t.prototype,"open",void 0),_t=vt([Zt("my-icon-popup")],_t);class $t extends Error{response;request;options;constructor(A,e,t){const s=`${A.status||0===A.status?A.status:""} ${A.statusText||""}`.trim();super(`Request failed with ${s?`status code ${s}`:"an unknown error"}: ${e.method} ${e.url}`),this.name="HTTPError",this.response=A,this.request=e,this.options=t}}class As extends Error{request;constructor(A){super(`Request timed out: ${A.method} ${A.url}`),this.name="TimeoutError",this.request=A}}const es=(()=>{let A=!1,e=!1;const t="function"==typeof globalThis.ReadableStream,s="function"==typeof globalThis.Request;if(t&&s)try{e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return A=!0,"half"}}).headers.has("Content-Type")}catch(A){if(A instanceof Error&&"unsupported BodyInit type"===A.message)return!1;throw A}return A&&!e})(),ts="function"==typeof globalThis.AbortController,ss="function"==typeof globalThis.AbortSignal&&"function"==typeof globalThis.AbortSignal.any,is="function"==typeof globalThis.ReadableStream,ns="function"==typeof globalThis.FormData,os=["get","post","put","patch","head","delete"],rs={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},as=2147483647,Vs=(new TextEncoder).encode("------WebKitFormBoundaryaxpyiPgbbPti10Rw").length,cs=Symbol("stop"),ls={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0},hs={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},gs=(A,e)=>{const t=(A=>{if(!A)return 0;if(A instanceof FormData){let e=0;for(const[t,s]of A)e+=Vs,e+=(new TextEncoder).encode(`Content-Disposition: form-data; name="${t}"`).length,e+="string"==typeof s?(new TextEncoder).encode(s).length:s.size;return e}if(A instanceof Blob)return A.size;if(A instanceof ArrayBuffer)return A.byteLength;if("string"==typeof A)return(new TextEncoder).encode(A).length;if(A instanceof URLSearchParams)return(new TextEncoder).encode(A.toString()).length;if("byteLength"in A)return A.byteLength;if("object"==typeof A&&null!==A)try{const e=JSON.stringify(A);return(new TextEncoder).encode(e).length}catch{return 0}return 0})(A.body);let s=0;return new Request(A,{duplex:"half",body:new ReadableStream({async start(i){const n=A.body instanceof ReadableStream?A.body.getReader():new Response("").body.getReader();await async function A(){const{done:o,value:r}=await n.read();if(o)return e&&e({percent:1,transferredBytes:s,totalBytes:Math.max(t,s)},new Uint8Array),void i.close();s+=r.byteLength;let a=0===t?0:s/t;(t<s||1===a)&&(a=.99),e&&e({percent:Number(a.toFixed(2)),transferredBytes:s,totalBytes:t},r),i.enqueue(r),await A()}()}})})},qs=A=>null!==A&&"object"==typeof A,ds=(...A)=>{for(const e of A)if((!qs(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return Es({},...A)},ps=(A={},e={})=>{const t=new globalThis.Headers(A),s=e instanceof globalThis.Headers,i=new globalThis.Headers(e);for(const[A,e]of i.entries())s&&"undefined"===e||void 0===e?t.delete(A):t.set(A,e);return t};function us(A,e,t){return Object.hasOwn(e,t)&&void 0===e[t]?[]:Es(A[t]??[],e[t]??[])}const ms=(A={},e={})=>({beforeRequest:us(A,e,"beforeRequest"),beforeRetry:us(A,e,"beforeRetry"),afterResponse:us(A,e,"afterResponse"),beforeError:us(A,e,"beforeError")}),Es=(...A)=>{let e={},t={},s={};for(const i of A)if(Array.isArray(i))Array.isArray(e)||(e=[]),e=[...e,...i];else if(qs(i)){for(let[A,t]of Object.entries(i))qs(t)&&A in e&&(t=Es(e[A],t)),e={...e,[A]:t};qs(i.hooks)&&(s=ms(s,i.hooks),e.hooks=s),qs(i.headers)&&(t=ps(t,i.headers),e.headers=t)}return e},Cs=A=>os.includes(A)?A.toUpperCase():A,Is={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:A=>.3*2**(A-1)*1e3},Ms=(A={})=>{if("number"==typeof A)return{...Is,limit:A};if(A.methods&&!Array.isArray(A.methods))throw new Error("retry.methods must be an array");if(A.statusCodes&&!Array.isArray(A.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Is,...A}};class ws{static create(A,e){const t=new ws(A,e),s=async()=>{if("number"==typeof t._options.timeout&&t._options.timeout>as)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let A=await t._fetch();for(const e of t._options.hooks.afterResponse){const s=await e(t.request,t._options,t._decorateResponse(A.clone()));s instanceof globalThis.Response&&(A=s)}if(t._decorateResponse(A),!A.ok&&t._options.throwHttpErrors){let e=new $t(A,t.request,t._options);for(const A of t._options.hooks.beforeError)e=await A(e);throw e}if(t._options.onDownloadProgress){if("function"!=typeof t._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!is)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return((A,e)=>{const t=Number(A.headers.get("content-length"))||0;let s=0;return 204===A.status?(e&&e({percent:1,totalBytes:t,transferredBytes:s},new Uint8Array),new Response(null,{status:A.status,statusText:A.statusText,headers:A.headers})):new Response(new ReadableStream({async start(i){const n=A.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:t},new Uint8Array),await async function A(){const{done:o,value:r}=await n.read();o?i.close():(e&&(s+=r.byteLength,e({percent:0===t?0:s/t,transferredBytes:s,totalBytes:t},r)),i.enqueue(r),await A())}()}}),{status:A.status,statusText:A.statusText,headers:A.headers})})(A.clone(),t._options.onDownloadProgress)}return A},i=(t._options.retry.methods.includes(t.request.method.toLowerCase())?t._retry(s):s()).finally(async()=>{t.request.bodyUsed||await(t.request.body?.cancel())});for(const[A,s]of Object.entries(rs))i[A]=async()=>{t.request.headers.set("accept",t.request.headers.get("accept")||s);const n=await i;if("json"===A){if(204===n.status)return"";if(0===(await n.clone().arrayBuffer()).byteLength)return"";if(e.parseJson)return e.parseJson(await n.text())}return n[A]()};return i}request;abortController;_retryCount=0;_input;_options;constructor(A,e={}){if(this._input=A,this._options={...e,headers:ps(this._input.headers,e.headers),hooks:ms({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:Cs(e.method??this._input.method??"GET"),prefixUrl:String(e.prefixUrl||""),retry:Ms(e.retry),throwHttpErrors:!1!==e.throwHttpErrors,timeout:e.timeout??1e4,fetch:e.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(ts&&ss){const A=this._options.signal??this._input.signal;this.abortController=new globalThis.AbortController,this._options.signal=A?AbortSignal.any([A,this.abortController.signal]):this.abortController.signal}if(es&&(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 A="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),e=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,A);!(ns&&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(e,{...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(!es)throw new Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request.body&&(this.request=gs(this.request,this._options.onUploadProgress))}}_calculateRetryDelay(A){if(this._retryCount++,this._retryCount>this._options.retry.limit||A instanceof As)throw A;if(A instanceof $t){if(!this._options.retry.statusCodes.includes(A.response.status))throw A;const e=A.response.headers.get("Retry-After")??A.response.headers.get("RateLimit-Reset")??A.response.headers.get("X-RateLimit-Reset")??A.response.headers.get("X-Rate-Limit-Reset");if(e&&this._options.retry.afterStatusCodes.includes(A.response.status)){let A=1e3*Number(e);Number.isNaN(A)?A=Date.parse(e)-Date.now():A>=Date.parse("2024-01-01")&&(A-=Date.now());const t=this._options.retry.maxRetryAfter??A;return A<t?A:t}if(413===A.response.status)throw A}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}_decorateResponse(A){return this._options.parseJson&&(A.json=async()=>this._options.parseJson(await A.text())),A}async _retry(A){try{return await A()}catch(e){const t=Math.min(this._calculateRetryDelay(e),as);if(this._retryCount<1)throw e;await async function(A,{signal:e}){return new Promise((t,s)=>{function i(){clearTimeout(n),s(e.reason)}e&&(e.throwIfAborted(),e.addEventListener("abort",i,{once:!0}));const n=setTimeout(()=>{e?.removeEventListener("abort",i),t()},A)})}(t,{signal:this._options.signal});for(const A of this._options.hooks.beforeRetry){if(await A({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===cs)return}return this._retry(A)}}async _fetch(){for(const A of this._options.hooks.beforeRequest){const e=await A(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}const A=((A,e)=>{const t={};for(const s in e)s in hs||s in ls||s in A||(t[s]=e[s]);return t})(this.request,this._options),e=this.request;return this.request=e.clone(),!1===this._options.timeout?this._options.fetch(e,A):async function(A,e,t,s){return new Promise((i,n)=>{const o=setTimeout(()=>{t&&t.abort(),n(new As(A))},s.timeout);s.fetch(A,e).then(i).catch(n).then(()=>{clearTimeout(o)})})}(e,A,this.abortController,this._options)}}
|
|
517
|
+
/*! MIT License © Sindre Sorhus */const fs=A=>{const e=(e,t)=>ws.create(e,ds(A,t));for(const t of os)e[t]=(e,s)=>ws.create(e,ds(A,s,{method:t}));return e.create=A=>fs(ds(A)),e.extend=e=>("function"==typeof e&&(e=e(A??{})),fs(ds(A,e))),e.stop=cs,e};var Bs,Ss=fs(),Qs="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Ts={exports:{}};
|
|
518
518
|
/**
|
|
519
519
|
* [js-md5]{@link https://github.com/emn178/js-md5}
|
|
520
520
|
*
|
|
@@ -524,7 +524,7 @@ const Zt=A=>(e,t)=>{void 0!==t?t.addInitializer(()=>{customElements.define(A,e)}
|
|
|
524
524
|
* @copyright Chen, Yi-Cyuan 2014-2023
|
|
525
525
|
* @license MIT
|
|
526
526
|
*/
|
|
527
|
-
Bs=Ts,function(){var t="input is invalid type",s="object"==typeof window,i=s?window:{};i.JS_MD5_NO_WINDOW&&(s=!1);var n=!s&&"object"==typeof self,o=!i.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;o?i=Qs:n&&(i=self);var r,a=!i.JS_MD5_NO_COMMON_JS&&Bs.exports,V=!i.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,c="0123456789abcdef".split(""),l=[128,32768,8388608,-2147483648],h=[0,8,16,24],g=["hex","array","digest","buffer","arrayBuffer","base64"],q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),d=[];if(V){var p=new ArrayBuffer(68);r=new Uint8Array(p),d=new Uint32Array(p)}var u=Array.isArray;!i.JS_MD5_NO_NODE_JS&&u||(u=function(A){return"[object Array]"===Object.prototype.toString.call(A)});var m=ArrayBuffer.isView;!V||!i.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&m||(m=function(A){return"object"==typeof A&&A.buffer&&A.buffer.constructor===ArrayBuffer});var C=function(A){var e=typeof A;if("string"===e)return[A,!0];if("object"!==e||null===A)throw new Error(t);if(V&&A.constructor===ArrayBuffer)return[new Uint8Array(A),!1];if(!u(A)&&!m(A))throw new Error(t);return[A,!1]},E=function(A){return function(e){return new M(!0).update(e)[A]()}},I=function(s){var n,o=A,r=e.Buffer;return n=r.from&&!i.JS_MD5_NO_BUFFER_FROM?r.from:function(A){return new r(A)},function(A){if("string"==typeof A)return o.createHash("md5").update(A,"utf8").digest("hex");if(null==A)throw new Error(t);return A.constructor===ArrayBuffer&&(A=new Uint8Array(A)),u(A)||m(A)||A.constructor===r?o.createHash("md5").update(n(A)).digest("hex"):s(A)}},w=function(A){return function(e,t){return new f(e,!0).update(t)[A]()}};function M(A){if(A)d[0]=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0,this.blocks=d,this.buffer8=r;else if(V){var e=new ArrayBuffer(68);this.buffer8=new Uint8Array(e),this.blocks=new Uint32Array(e)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function f(A,e){var t,s=C(A);if(A=s[0],s[1]){var i,n=[],o=A.length,r=0;for(t=0;t<o;++t)(i=A.charCodeAt(t))<128?n[r++]=i:i<2048?(n[r++]=192|i>>>6,n[r++]=128|63&i):i<55296||i>=57344?(n[r++]=224|i>>>12,n[r++]=128|i>>>6&63,n[r++]=128|63&i):(i=65536+((1023&i)<<10|1023&A.charCodeAt(++t)),n[r++]=240|i>>>18,n[r++]=128|i>>>12&63,n[r++]=128|i>>>6&63,n[r++]=128|63&i);A=n}A.length>64&&(A=new M(!0).update(A).array());var a=[],V=[];for(t=0;t<64;++t){var c=A[t]||0;a[t]=92^c,V[t]=54^c}M.call(this,e),this.update(V),this.oKeyPad=a,this.inner=!0,this.sharedMemory=e}M.prototype.update=function(A){if(this.finalized)throw new Error("finalize already called");var e=C(A);A=e[0];for(var t,s,i=e[1],n=0,o=A.length,r=this.blocks,a=this.buffer8;n<o;){if(this.hashed&&(this.hashed=!1,r[0]=r[16],r[16]=r[1]=r[2]=r[3]=r[4]=r[5]=r[6]=r[7]=r[8]=r[9]=r[10]=r[11]=r[12]=r[13]=r[14]=r[15]=0),i)if(V)for(s=this.start;n<o&&s<64;++n)(t=A.charCodeAt(n))<128?a[s++]=t:t<2048?(a[s++]=192|t>>>6,a[s++]=128|63&t):t<55296||t>=57344?(a[s++]=224|t>>>12,a[s++]=128|t>>>6&63,a[s++]=128|63&t):(t=65536+((1023&t)<<10|1023&A.charCodeAt(++n)),a[s++]=240|t>>>18,a[s++]=128|t>>>12&63,a[s++]=128|t>>>6&63,a[s++]=128|63&t);else for(s=this.start;n<o&&s<64;++n)(t=A.charCodeAt(n))<128?r[s>>>2]|=t<<h[3&s++]:t<2048?(r[s>>>2]|=(192|t>>>6)<<h[3&s++],r[s>>>2]|=(128|63&t)<<h[3&s++]):t<55296||t>=57344?(r[s>>>2]|=(224|t>>>12)<<h[3&s++],r[s>>>2]|=(128|t>>>6&63)<<h[3&s++],r[s>>>2]|=(128|63&t)<<h[3&s++]):(t=65536+((1023&t)<<10|1023&A.charCodeAt(++n)),r[s>>>2]|=(240|t>>>18)<<h[3&s++],r[s>>>2]|=(128|t>>>12&63)<<h[3&s++],r[s>>>2]|=(128|t>>>6&63)<<h[3&s++],r[s>>>2]|=(128|63&t)<<h[3&s++]);else if(V)for(s=this.start;n<o&&s<64;++n)a[s++]=A[n];else for(s=this.start;n<o&&s<64;++n)r[s>>>2]|=A[n]<<h[3&s++];this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},M.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var A=this.blocks,e=this.lastByteIndex;A[e>>>2]|=l[3&e],e>=56&&(this.hashed||this.hash(),A[0]=A[16],A[16]=A[1]=A[2]=A[3]=A[4]=A[5]=A[6]=A[7]=A[8]=A[9]=A[10]=A[11]=A[12]=A[13]=A[14]=A[15]=0),A[14]=this.bytes<<3,A[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},M.prototype.hash=function(){var A,e,t,s,i,n,o=this.blocks;this.first?e=((e=((A=((A=o[0]-680876937)<<7|A>>>25)-271733879|0)^(t=((t=(-271733879^(s=((s=(-1732584194^2004318071&A)+o[1]-117830708)<<12|s>>>20)+A|0)&(-271733879^A))+o[2]-1126478375)<<17|t>>>15)+s|0)&(s^A))+o[3]-1316259209)<<22|e>>>10)+t|0:(A=this.h0,e=this.h1,t=this.h2,e=((e+=((A=((A+=((s=this.h3)^e&(t^s))+o[0]-680876936)<<7|A>>>25)+e|0)^(t=((t+=(e^(s=((s+=(t^A&(e^t))+o[1]-389564586)<<12|s>>>20)+A|0)&(A^e))+o[2]+606105819)<<17|t>>>15)+s|0)&(s^A))+o[3]-1044525330)<<22|e>>>10)+t|0),e=((e+=((A=((A+=(s^e&(t^s))+o[4]-176418897)<<7|A>>>25)+e|0)^(t=((t+=(e^(s=((s+=(t^A&(e^t))+o[5]+1200080426)<<12|s>>>20)+A|0)&(A^e))+o[6]-1473231341)<<17|t>>>15)+s|0)&(s^A))+o[7]-45705983)<<22|e>>>10)+t|0,e=((e+=((A=((A+=(s^e&(t^s))+o[8]+1770035416)<<7|A>>>25)+e|0)^(t=((t+=(e^(s=((s+=(t^A&(e^t))+o[9]-1958414417)<<12|s>>>20)+A|0)&(A^e))+o[10]-42063)<<17|t>>>15)+s|0)&(s^A))+o[11]-1990404162)<<22|e>>>10)+t|0,e=((e+=((A=((A+=(s^e&(t^s))+o[12]+1804603682)<<7|A>>>25)+e|0)^(t=((t+=(e^(s=((s+=(t^A&(e^t))+o[13]-40341101)<<12|s>>>20)+A|0)&(A^e))+o[14]-1502002290)<<17|t>>>15)+s|0)&(s^A))+o[15]+1236535329)<<22|e>>>10)+t|0,e=((e+=((s=((s+=(e^t&((A=((A+=(t^s&(e^t))+o[1]-165796510)<<5|A>>>27)+e|0)^e))+o[6]-1069501632)<<9|s>>>23)+A|0)^A&((t=((t+=(A^e&(s^A))+o[11]+643717713)<<14|t>>>18)+s|0)^s))+o[0]-373897302)<<20|e>>>12)+t|0,e=((e+=((s=((s+=(e^t&((A=((A+=(t^s&(e^t))+o[5]-701558691)<<5|A>>>27)+e|0)^e))+o[10]+38016083)<<9|s>>>23)+A|0)^A&((t=((t+=(A^e&(s^A))+o[15]-660478335)<<14|t>>>18)+s|0)^s))+o[4]-405537848)<<20|e>>>12)+t|0,e=((e+=((s=((s+=(e^t&((A=((A+=(t^s&(e^t))+o[9]+568446438)<<5|A>>>27)+e|0)^e))+o[14]-1019803690)<<9|s>>>23)+A|0)^A&((t=((t+=(A^e&(s^A))+o[3]-187363961)<<14|t>>>18)+s|0)^s))+o[8]+1163531501)<<20|e>>>12)+t|0,e=((e+=((s=((s+=(e^t&((A=((A+=(t^s&(e^t))+o[13]-1444681467)<<5|A>>>27)+e|0)^e))+o[2]-51403784)<<9|s>>>23)+A|0)^A&((t=((t+=(A^e&(s^A))+o[7]+1735328473)<<14|t>>>18)+s|0)^s))+o[12]-1926607734)<<20|e>>>12)+t|0,e=((e+=((n=(s=((s+=((i=e^t)^(A=((A+=(i^s)+o[5]-378558)<<4|A>>>28)+e|0))+o[8]-2022574463)<<11|s>>>21)+A|0)^A)^(t=((t+=(n^e)+o[11]+1839030562)<<16|t>>>16)+s|0))+o[14]-35309556)<<23|e>>>9)+t|0,e=((e+=((n=(s=((s+=((i=e^t)^(A=((A+=(i^s)+o[1]-1530992060)<<4|A>>>28)+e|0))+o[4]+1272893353)<<11|s>>>21)+A|0)^A)^(t=((t+=(n^e)+o[7]-155497632)<<16|t>>>16)+s|0))+o[10]-1094730640)<<23|e>>>9)+t|0,e=((e+=((n=(s=((s+=((i=e^t)^(A=((A+=(i^s)+o[13]+681279174)<<4|A>>>28)+e|0))+o[0]-358537222)<<11|s>>>21)+A|0)^A)^(t=((t+=(n^e)+o[3]-722521979)<<16|t>>>16)+s|0))+o[6]+76029189)<<23|e>>>9)+t|0,e=((e+=((n=(s=((s+=((i=e^t)^(A=((A+=(i^s)+o[9]-640364487)<<4|A>>>28)+e|0))+o[12]-421815835)<<11|s>>>21)+A|0)^A)^(t=((t+=(n^e)+o[15]+530742520)<<16|t>>>16)+s|0))+o[2]-995338651)<<23|e>>>9)+t|0,e=((e+=((s=((s+=(e^((A=((A+=(t^(e|~s))+o[0]-198630844)<<6|A>>>26)+e|0)|~t))+o[7]+1126891415)<<10|s>>>22)+A|0)^((t=((t+=(A^(s|~e))+o[14]-1416354905)<<15|t>>>17)+s|0)|~A))+o[5]-57434055)<<21|e>>>11)+t|0,e=((e+=((s=((s+=(e^((A=((A+=(t^(e|~s))+o[12]+1700485571)<<6|A>>>26)+e|0)|~t))+o[3]-1894986606)<<10|s>>>22)+A|0)^((t=((t+=(A^(s|~e))+o[10]-1051523)<<15|t>>>17)+s|0)|~A))+o[1]-2054922799)<<21|e>>>11)+t|0,e=((e+=((s=((s+=(e^((A=((A+=(t^(e|~s))+o[8]+1873313359)<<6|A>>>26)+e|0)|~t))+o[15]-30611744)<<10|s>>>22)+A|0)^((t=((t+=(A^(s|~e))+o[6]-1560198380)<<15|t>>>17)+s|0)|~A))+o[13]+1309151649)<<21|e>>>11)+t|0,e=((e+=((s=((s+=(e^((A=((A+=(t^(e|~s))+o[4]-145523070)<<6|A>>>26)+e|0)|~t))+o[11]-1120210379)<<10|s>>>22)+A|0)^((t=((t+=(A^(s|~e))+o[2]+718787259)<<15|t>>>17)+s|0)|~A))+o[9]-343485551)<<21|e>>>11)+t|0,this.first?(this.h0=A+1732584193|0,this.h1=e-271733879|0,this.h2=t-1732584194|0,this.h3=s+271733878|0,this.first=!1):(this.h0=this.h0+A|0,this.h1=this.h1+e|0,this.h2=this.h2+t|0,this.h3=this.h3+s|0)},M.prototype.hex=function(){this.finalize();var A=this.h0,e=this.h1,t=this.h2,s=this.h3;return c[A>>>4&15]+c[15&A]+c[A>>>12&15]+c[A>>>8&15]+c[A>>>20&15]+c[A>>>16&15]+c[A>>>28&15]+c[A>>>24&15]+c[e>>>4&15]+c[15&e]+c[e>>>12&15]+c[e>>>8&15]+c[e>>>20&15]+c[e>>>16&15]+c[e>>>28&15]+c[e>>>24&15]+c[t>>>4&15]+c[15&t]+c[t>>>12&15]+c[t>>>8&15]+c[t>>>20&15]+c[t>>>16&15]+c[t>>>28&15]+c[t>>>24&15]+c[s>>>4&15]+c[15&s]+c[s>>>12&15]+c[s>>>8&15]+c[s>>>20&15]+c[s>>>16&15]+c[s>>>28&15]+c[s>>>24&15]},M.prototype.toString=M.prototype.hex,M.prototype.digest=function(){this.finalize();var A=this.h0,e=this.h1,t=this.h2,s=this.h3;return[255&A,A>>>8&255,A>>>16&255,A>>>24&255,255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&s,s>>>8&255,s>>>16&255,s>>>24&255]},M.prototype.array=M.prototype.digest,M.prototype.arrayBuffer=function(){this.finalize();var A=new ArrayBuffer(16),e=new Uint32Array(A);return e[0]=this.h0,e[1]=this.h1,e[2]=this.h2,e[3]=this.h3,A},M.prototype.buffer=M.prototype.arrayBuffer,M.prototype.base64=function(){for(var A,e,t,s="",i=this.array(),n=0;n<15;)A=i[n++],e=i[n++],t=i[n++],s+=q[A>>>2]+q[63&(A<<4|e>>>4)]+q[63&(e<<2|t>>>6)]+q[63&t];return A=i[n],s+=q[A>>>2]+q[A<<4&63]+"=="},f.prototype=new M,f.prototype.finalize=function(){if(M.prototype.finalize.call(this),this.inner){this.inner=!1;var A=this.array();M.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(A),M.prototype.finalize.call(this)}};var B=function(){var A=E("hex");o&&(A=I(A)),A.create=function(){return new M},A.update=function(e){return A.create().update(e)};for(var e=0;e<g.length;++e){var t=g[e];A[t]=E(t)}return A}();B.md5=B,B.md5.hmac=function(){var A=w("hex");A.create=function(A){return new f(A)},A.update=function(e,t){return A.create(e).update(t)};for(var e=0;e<g.length;++e){var t=g[e];A[t]=w(t)}return A}(),a?Bs.exports=B:i.md5=B}();var ys=Ts.exports;const Ds=(A,e)=>{const t=Date.now(),s=`${A}:${t}:${ys.md5(`${e}${t}`)}`,i=(new TextEncoder).encode(s);return btoa(String.fromCharCode(...i))},Rs=A=>/^\d+$/.test(A),Us="/v1/aicc/bmserver",ks="/v1/aicc/ccs";let Gs="",Fs="",Ys="",xs="";function vs(){const A=Ds(Fs,Ys);return Ss.create({prefixUrl:`${Gs}`,timeout:!1,headers:{Authorization:A},hooks:{afterResponse:[async(A,e,t)=>{if(-1!==t.url.indexOf("heartbeat"))return t;const s=await t.clone().json();if(0!==s.code)throw new Error(JSON.stringify(s)||"请求失败");return t.json=async()=>s,t}]}})}async function Zs(A,e){const t=vs(),s="api/"+A.replace(/^\/+/,"");return t.post(s,{json:e}).json()}const Os=A=>Zs(`${ks}/state/change`,A),Ns=()=>async function(A,e){const t=vs(),s=A.replace(/^\/+/,"");return t.post(s,{json:e}).json()}("/heartbeat",{});class Ks{constructor(){this.roleData={agentInfo:()=>{if(!Ve.agentInfo?.agent_no)throw new Error(JSON.stringify({code:1,msg:"请先登录"}))},requestInfo:A=>{if(!A.data)throw new Error(JSON.stringify({code:1,msg:'Parameter "data" is required'}))},changeDevice:A=>{if(!A)throw new Error(JSON.stringify({code:1,msg:'Parameter "device" is required'}));const{answer_devices:e}=Ve.agentInfo;if(!e.split(",").map(A=>Number(A)).includes(A))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(A,e)=>{if(!A)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(2===A&&("通话中"===e||"整理"===e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}));if(![1,2].includes(A))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},setAgentExplicit:A=>{const{out_display_select_switch:e,out_display_data:t}=Ve.agentInfo;if(1!==e)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!A)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(t||"").split("#").includes(A))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}}}formatDate(A){return`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")} ${String(A.getHours()).padStart(2,"0")}:${String(A.getMinutes()).padStart(2,"0")}:${String(A.getSeconds()).padStart(2,"0")}`}async _agentLogin(A){try{const t=await(e={agent_no:A},Zs(`${ks}/agent/login`,e));Ve.agentInfo=t.data}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}var e}async _changeState(A){try{Ve.autoStateTimer&&(clearTimeout(Ve.autoStateTimer),Ve.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(A);const{data:e,success:t}=A,{state:s,state_name:i}=e,{agent_no:n}=Ve.agentInfo;await Os({agent_no:n,state_name:i,state:s}),s===exports.AgentStatus.IDLE?le.updateActionConfigs(ft):s===exports.AgentStatus.BUSY&&le.updateActionConfigs(Bt),Ve.stateObject={state:s,state_name:i},t?.({code:0,msg:"请求成功"})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async _getInCallCrmDetail(A){try{const{phone:e}=A.data,t={};Rs(e)?t.phone=e:t.trace_id=e;const s=await(A=>Zs(`${Us}/crm/popups`,A))({...t});A.success?.(s)}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async changeDevice(A){try{if(le.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(A);const{data:e,success:t}=A,{device:s}=e;1===s&&le.updateAnswerDevice(s),this.roleData.changeDevice(s);const{agent_no:i}=Ve.agentInfo;await(A=>Zs(`${ks}/device/change`,A))({agent_no:i,answer_device:s}),le.updateAnswerDevice(s);const n=le.get("actionConfigs");le.updateActionConfigs(n),2===s&&Ve.stateObject.state===exports.AgentStatus.UNREGISTERED&&await this._changeState({data:{...Ve.stateBeforeChange,state_name:Ve.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}}),t?.({code:0,msg:"请求成功"})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async changeState(A){try{if(le.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));Ve.autoStateTimer&&(clearTimeout(Ve.autoStateTimer),Ve.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(A);const{data:e,success:t}=A,{state:s,state_name:i}=e;this.roleData.changeState(s,i);const{agent_no:n}=Ve.agentInfo;await Os({agent_no:n,state_name:i,state:s}),(Ve.stateObject.state===exports.AgentStatus.IDLE||Ve.stateObject.state===exports.AgentStatus.BUSY&&"整理"!==i)&&(Ve.stateBeforeChange=Ve.stateObject),s===exports.AgentStatus.IDLE?le.updateActionConfigs(ft):s===exports.AgentStatus.BUSY&&le.updateActionConfigs(Bt),Ve.stateObject={state:s,state_name:i},t?.({code:0,msg:"请求成功"})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async getIdleAgentList(A){const{agent_no:e}=Ve.agentInfo;try{this.roleData.agentInfo();const t=await(A=>Zs(`${ks}/agent/free`,A))({agent_no:e});A.success?.(t)}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async getAgentState(A){try{const e=await Zs(`${Us}/agent/statecfg/list`,{}),t=(e.data||[]).filter(A=>0===A.enable).filter(A=>0!==A.state&&3!==A.state).filter(A=>"通话中"!==A.state_name&&"整理"!==A.state_name&&"未注册"!==A.state_name&&"离线接听"!==A.state_name).map(A=>({state:A.state,state_name:A.state_name})).reverse();A.success?.({...e,data:t})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async setAgentExplicit(A){try{this.roleData.agentInfo(),this.roleData.requestInfo(A),this.roleData.setAgentExplicit(A.data.number);const{agent_id:e}=Ve.agentInfo;await(A=>Zs(`${Us}/agent/update`,A))({agent_id:e,out_display_number:A.data.number}),le.updateSelectOutNumber(A.data.number),A.success?.({code:0,msg:"请求成功"})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async checkAgentLogin(A){try{this.roleData.requestInfo(A);const{agent_no:e}=A.data;if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const t=await(A=>Zs(`${ks}/agent/islogin`,A))({agent_no:e});A.success?.(t)}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async getCallRecord(A){try{this.roleData.agentInfo();const{success:e}=A,t=new Date,s=new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,0),i=new Date(t.getFullYear(),t.getMonth(),t.getDate(),23,59,59),n=[this.formatDate(s),this.formatDate(i)],{agent_no:o}=Ve.agentInfo,r=await(A=>Zs(`${Us}/agent/recordpage`,A))({start_time:n[0],end_time:n[1],page_no:1,page_size:10,agent_no:o}),{code:a,msg:V,data:c}=r;e?.({code:a,msg:V,data:c})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async logout(A){this.roleData.agentInfo();try{const{agent_no:e}=Ve.agentInfo,{data:t,success:s}=A;await(A=>Zs(`${ks}/agent/logout`,A))({...t,agent_no:e}),s?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async listenCall(A){try{const{agent_no:e}=Ve.agentInfo,{data:t,success:s}=A;if(this.roleData.agentInfo(),this.roleData.requestInfo(A),!t.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(A=>Zs(`${ks}/call/monitor`,A))({...t,monitor_agent_no:e}),Ve.monitoredAgentNo=t.monitored_agent_no,s?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async earCall(A){try{const{agentInfo:e,monitoredAgentNo:t}=Ve,{agent_no:s}=e;this.roleData.agentInfo();const{success:i}=A;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(A=>Zs(`${ks}/call/whisper`,A))({monitored_agent_no:t,monitor_agent_no:s}),i?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async stopEarCall(A){try{const{agentInfo:e,earSpeakAgent:t}=Ve;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:s}=e;this.roleData.agentInfo();const{success:i}=A;await(A=>Zs(`${ks}/call/stopwhisper`,A))({monitor_agent_no:s,monitored_agent_no:t}),i?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async forceInsert(A){try{const{agentInfo:e,monitoredAgentNo:t}=Ve,{agent_no:s}=e;this.roleData.agentInfo();const{success:i}=A;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(A=>Zs(`${ks}/call/bargein`,A))({monitored_agent_no:t,monitor_agent_no:s}),i?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async forceDisconnect(A){try{const{agentInfo:e,monitoredAgentNo:t}=Ve,{agent_no:s}=e;this.roleData.agentInfo();const{success:i}=A;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(A=>Zs(`${ks}/call/intercept`,A))({monitored_agent_no:t,monitor_agent_no:s}),i?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}}let bs=class extends Et{constructor(){super(...arguments),this.type="info",this.content="",this.duration=3e3}static{this.styles=Ce`
|
|
527
|
+
Bs=Ts,function(){var t="input is invalid type",s="object"==typeof window,i=s?window:{};i.JS_MD5_NO_WINDOW&&(s=!1);var n=!s&&"object"==typeof self,o=!i.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;o?i=Qs:n&&(i=self);var r,a=!i.JS_MD5_NO_COMMON_JS&&Bs.exports,V=!i.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,c="0123456789abcdef".split(""),l=[128,32768,8388608,-2147483648],h=[0,8,16,24],g=["hex","array","digest","buffer","arrayBuffer","base64"],q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),d=[];if(V){var p=new ArrayBuffer(68);r=new Uint8Array(p),d=new Uint32Array(p)}var u=Array.isArray;!i.JS_MD5_NO_NODE_JS&&u||(u=function(A){return"[object Array]"===Object.prototype.toString.call(A)});var m=ArrayBuffer.isView;!V||!i.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&m||(m=function(A){return"object"==typeof A&&A.buffer&&A.buffer.constructor===ArrayBuffer});var E=function(A){var e=typeof A;if("string"===e)return[A,!0];if("object"!==e||null===A)throw new Error(t);if(V&&A.constructor===ArrayBuffer)return[new Uint8Array(A),!1];if(!u(A)&&!m(A))throw new Error(t);return[A,!1]},C=function(A){return function(e){return new w(!0).update(e)[A]()}},I=function(s){var n,o=A,r=e.Buffer;return n=r.from&&!i.JS_MD5_NO_BUFFER_FROM?r.from:function(A){return new r(A)},function(A){if("string"==typeof A)return o.createHash("md5").update(A,"utf8").digest("hex");if(null==A)throw new Error(t);return A.constructor===ArrayBuffer&&(A=new Uint8Array(A)),u(A)||m(A)||A.constructor===r?o.createHash("md5").update(n(A)).digest("hex"):s(A)}},M=function(A){return function(e,t){return new f(e,!0).update(t)[A]()}};function w(A){if(A)d[0]=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0,this.blocks=d,this.buffer8=r;else if(V){var e=new ArrayBuffer(68);this.buffer8=new Uint8Array(e),this.blocks=new Uint32Array(e)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}function f(A,e){var t,s=E(A);if(A=s[0],s[1]){var i,n=[],o=A.length,r=0;for(t=0;t<o;++t)(i=A.charCodeAt(t))<128?n[r++]=i:i<2048?(n[r++]=192|i>>>6,n[r++]=128|63&i):i<55296||i>=57344?(n[r++]=224|i>>>12,n[r++]=128|i>>>6&63,n[r++]=128|63&i):(i=65536+((1023&i)<<10|1023&A.charCodeAt(++t)),n[r++]=240|i>>>18,n[r++]=128|i>>>12&63,n[r++]=128|i>>>6&63,n[r++]=128|63&i);A=n}A.length>64&&(A=new w(!0).update(A).array());var a=[],V=[];for(t=0;t<64;++t){var c=A[t]||0;a[t]=92^c,V[t]=54^c}w.call(this,e),this.update(V),this.oKeyPad=a,this.inner=!0,this.sharedMemory=e}w.prototype.update=function(A){if(this.finalized)throw new Error("finalize already called");var e=E(A);A=e[0];for(var t,s,i=e[1],n=0,o=A.length,r=this.blocks,a=this.buffer8;n<o;){if(this.hashed&&(this.hashed=!1,r[0]=r[16],r[16]=r[1]=r[2]=r[3]=r[4]=r[5]=r[6]=r[7]=r[8]=r[9]=r[10]=r[11]=r[12]=r[13]=r[14]=r[15]=0),i)if(V)for(s=this.start;n<o&&s<64;++n)(t=A.charCodeAt(n))<128?a[s++]=t:t<2048?(a[s++]=192|t>>>6,a[s++]=128|63&t):t<55296||t>=57344?(a[s++]=224|t>>>12,a[s++]=128|t>>>6&63,a[s++]=128|63&t):(t=65536+((1023&t)<<10|1023&A.charCodeAt(++n)),a[s++]=240|t>>>18,a[s++]=128|t>>>12&63,a[s++]=128|t>>>6&63,a[s++]=128|63&t);else for(s=this.start;n<o&&s<64;++n)(t=A.charCodeAt(n))<128?r[s>>>2]|=t<<h[3&s++]:t<2048?(r[s>>>2]|=(192|t>>>6)<<h[3&s++],r[s>>>2]|=(128|63&t)<<h[3&s++]):t<55296||t>=57344?(r[s>>>2]|=(224|t>>>12)<<h[3&s++],r[s>>>2]|=(128|t>>>6&63)<<h[3&s++],r[s>>>2]|=(128|63&t)<<h[3&s++]):(t=65536+((1023&t)<<10|1023&A.charCodeAt(++n)),r[s>>>2]|=(240|t>>>18)<<h[3&s++],r[s>>>2]|=(128|t>>>12&63)<<h[3&s++],r[s>>>2]|=(128|t>>>6&63)<<h[3&s++],r[s>>>2]|=(128|63&t)<<h[3&s++]);else if(V)for(s=this.start;n<o&&s<64;++n)a[s++]=A[n];else for(s=this.start;n<o&&s<64;++n)r[s>>>2]|=A[n]<<h[3&s++];this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296|0,this.bytes=this.bytes%4294967296),this},w.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var A=this.blocks,e=this.lastByteIndex;A[e>>>2]|=l[3&e],e>=56&&(this.hashed||this.hash(),A[0]=A[16],A[16]=A[1]=A[2]=A[3]=A[4]=A[5]=A[6]=A[7]=A[8]=A[9]=A[10]=A[11]=A[12]=A[13]=A[14]=A[15]=0),A[14]=this.bytes<<3,A[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},w.prototype.hash=function(){var A,e,t,s,i,n,o=this.blocks;this.first?e=((e=((A=((A=o[0]-680876937)<<7|A>>>25)-271733879|0)^(t=((t=(-271733879^(s=((s=(-1732584194^2004318071&A)+o[1]-117830708)<<12|s>>>20)+A|0)&(-271733879^A))+o[2]-1126478375)<<17|t>>>15)+s|0)&(s^A))+o[3]-1316259209)<<22|e>>>10)+t|0:(A=this.h0,e=this.h1,t=this.h2,e=((e+=((A=((A+=((s=this.h3)^e&(t^s))+o[0]-680876936)<<7|A>>>25)+e|0)^(t=((t+=(e^(s=((s+=(t^A&(e^t))+o[1]-389564586)<<12|s>>>20)+A|0)&(A^e))+o[2]+606105819)<<17|t>>>15)+s|0)&(s^A))+o[3]-1044525330)<<22|e>>>10)+t|0),e=((e+=((A=((A+=(s^e&(t^s))+o[4]-176418897)<<7|A>>>25)+e|0)^(t=((t+=(e^(s=((s+=(t^A&(e^t))+o[5]+1200080426)<<12|s>>>20)+A|0)&(A^e))+o[6]-1473231341)<<17|t>>>15)+s|0)&(s^A))+o[7]-45705983)<<22|e>>>10)+t|0,e=((e+=((A=((A+=(s^e&(t^s))+o[8]+1770035416)<<7|A>>>25)+e|0)^(t=((t+=(e^(s=((s+=(t^A&(e^t))+o[9]-1958414417)<<12|s>>>20)+A|0)&(A^e))+o[10]-42063)<<17|t>>>15)+s|0)&(s^A))+o[11]-1990404162)<<22|e>>>10)+t|0,e=((e+=((A=((A+=(s^e&(t^s))+o[12]+1804603682)<<7|A>>>25)+e|0)^(t=((t+=(e^(s=((s+=(t^A&(e^t))+o[13]-40341101)<<12|s>>>20)+A|0)&(A^e))+o[14]-1502002290)<<17|t>>>15)+s|0)&(s^A))+o[15]+1236535329)<<22|e>>>10)+t|0,e=((e+=((s=((s+=(e^t&((A=((A+=(t^s&(e^t))+o[1]-165796510)<<5|A>>>27)+e|0)^e))+o[6]-1069501632)<<9|s>>>23)+A|0)^A&((t=((t+=(A^e&(s^A))+o[11]+643717713)<<14|t>>>18)+s|0)^s))+o[0]-373897302)<<20|e>>>12)+t|0,e=((e+=((s=((s+=(e^t&((A=((A+=(t^s&(e^t))+o[5]-701558691)<<5|A>>>27)+e|0)^e))+o[10]+38016083)<<9|s>>>23)+A|0)^A&((t=((t+=(A^e&(s^A))+o[15]-660478335)<<14|t>>>18)+s|0)^s))+o[4]-405537848)<<20|e>>>12)+t|0,e=((e+=((s=((s+=(e^t&((A=((A+=(t^s&(e^t))+o[9]+568446438)<<5|A>>>27)+e|0)^e))+o[14]-1019803690)<<9|s>>>23)+A|0)^A&((t=((t+=(A^e&(s^A))+o[3]-187363961)<<14|t>>>18)+s|0)^s))+o[8]+1163531501)<<20|e>>>12)+t|0,e=((e+=((s=((s+=(e^t&((A=((A+=(t^s&(e^t))+o[13]-1444681467)<<5|A>>>27)+e|0)^e))+o[2]-51403784)<<9|s>>>23)+A|0)^A&((t=((t+=(A^e&(s^A))+o[7]+1735328473)<<14|t>>>18)+s|0)^s))+o[12]-1926607734)<<20|e>>>12)+t|0,e=((e+=((n=(s=((s+=((i=e^t)^(A=((A+=(i^s)+o[5]-378558)<<4|A>>>28)+e|0))+o[8]-2022574463)<<11|s>>>21)+A|0)^A)^(t=((t+=(n^e)+o[11]+1839030562)<<16|t>>>16)+s|0))+o[14]-35309556)<<23|e>>>9)+t|0,e=((e+=((n=(s=((s+=((i=e^t)^(A=((A+=(i^s)+o[1]-1530992060)<<4|A>>>28)+e|0))+o[4]+1272893353)<<11|s>>>21)+A|0)^A)^(t=((t+=(n^e)+o[7]-155497632)<<16|t>>>16)+s|0))+o[10]-1094730640)<<23|e>>>9)+t|0,e=((e+=((n=(s=((s+=((i=e^t)^(A=((A+=(i^s)+o[13]+681279174)<<4|A>>>28)+e|0))+o[0]-358537222)<<11|s>>>21)+A|0)^A)^(t=((t+=(n^e)+o[3]-722521979)<<16|t>>>16)+s|0))+o[6]+76029189)<<23|e>>>9)+t|0,e=((e+=((n=(s=((s+=((i=e^t)^(A=((A+=(i^s)+o[9]-640364487)<<4|A>>>28)+e|0))+o[12]-421815835)<<11|s>>>21)+A|0)^A)^(t=((t+=(n^e)+o[15]+530742520)<<16|t>>>16)+s|0))+o[2]-995338651)<<23|e>>>9)+t|0,e=((e+=((s=((s+=(e^((A=((A+=(t^(e|~s))+o[0]-198630844)<<6|A>>>26)+e|0)|~t))+o[7]+1126891415)<<10|s>>>22)+A|0)^((t=((t+=(A^(s|~e))+o[14]-1416354905)<<15|t>>>17)+s|0)|~A))+o[5]-57434055)<<21|e>>>11)+t|0,e=((e+=((s=((s+=(e^((A=((A+=(t^(e|~s))+o[12]+1700485571)<<6|A>>>26)+e|0)|~t))+o[3]-1894986606)<<10|s>>>22)+A|0)^((t=((t+=(A^(s|~e))+o[10]-1051523)<<15|t>>>17)+s|0)|~A))+o[1]-2054922799)<<21|e>>>11)+t|0,e=((e+=((s=((s+=(e^((A=((A+=(t^(e|~s))+o[8]+1873313359)<<6|A>>>26)+e|0)|~t))+o[15]-30611744)<<10|s>>>22)+A|0)^((t=((t+=(A^(s|~e))+o[6]-1560198380)<<15|t>>>17)+s|0)|~A))+o[13]+1309151649)<<21|e>>>11)+t|0,e=((e+=((s=((s+=(e^((A=((A+=(t^(e|~s))+o[4]-145523070)<<6|A>>>26)+e|0)|~t))+o[11]-1120210379)<<10|s>>>22)+A|0)^((t=((t+=(A^(s|~e))+o[2]+718787259)<<15|t>>>17)+s|0)|~A))+o[9]-343485551)<<21|e>>>11)+t|0,this.first?(this.h0=A+1732584193|0,this.h1=e-271733879|0,this.h2=t-1732584194|0,this.h3=s+271733878|0,this.first=!1):(this.h0=this.h0+A|0,this.h1=this.h1+e|0,this.h2=this.h2+t|0,this.h3=this.h3+s|0)},w.prototype.hex=function(){this.finalize();var A=this.h0,e=this.h1,t=this.h2,s=this.h3;return c[A>>>4&15]+c[15&A]+c[A>>>12&15]+c[A>>>8&15]+c[A>>>20&15]+c[A>>>16&15]+c[A>>>28&15]+c[A>>>24&15]+c[e>>>4&15]+c[15&e]+c[e>>>12&15]+c[e>>>8&15]+c[e>>>20&15]+c[e>>>16&15]+c[e>>>28&15]+c[e>>>24&15]+c[t>>>4&15]+c[15&t]+c[t>>>12&15]+c[t>>>8&15]+c[t>>>20&15]+c[t>>>16&15]+c[t>>>28&15]+c[t>>>24&15]+c[s>>>4&15]+c[15&s]+c[s>>>12&15]+c[s>>>8&15]+c[s>>>20&15]+c[s>>>16&15]+c[s>>>28&15]+c[s>>>24&15]},w.prototype.toString=w.prototype.hex,w.prototype.digest=function(){this.finalize();var A=this.h0,e=this.h1,t=this.h2,s=this.h3;return[255&A,A>>>8&255,A>>>16&255,A>>>24&255,255&e,e>>>8&255,e>>>16&255,e>>>24&255,255&t,t>>>8&255,t>>>16&255,t>>>24&255,255&s,s>>>8&255,s>>>16&255,s>>>24&255]},w.prototype.array=w.prototype.digest,w.prototype.arrayBuffer=function(){this.finalize();var A=new ArrayBuffer(16),e=new Uint32Array(A);return e[0]=this.h0,e[1]=this.h1,e[2]=this.h2,e[3]=this.h3,A},w.prototype.buffer=w.prototype.arrayBuffer,w.prototype.base64=function(){for(var A,e,t,s="",i=this.array(),n=0;n<15;)A=i[n++],e=i[n++],t=i[n++],s+=q[A>>>2]+q[63&(A<<4|e>>>4)]+q[63&(e<<2|t>>>6)]+q[63&t];return A=i[n],s+=q[A>>>2]+q[A<<4&63]+"=="},f.prototype=new w,f.prototype.finalize=function(){if(w.prototype.finalize.call(this),this.inner){this.inner=!1;var A=this.array();w.call(this,this.sharedMemory),this.update(this.oKeyPad),this.update(A),w.prototype.finalize.call(this)}};var B=function(){var A=C("hex");o&&(A=I(A)),A.create=function(){return new w},A.update=function(e){return A.create().update(e)};for(var e=0;e<g.length;++e){var t=g[e];A[t]=C(t)}return A}();B.md5=B,B.md5.hmac=function(){var A=M("hex");A.create=function(A){return new f(A)},A.update=function(e,t){return A.create(e).update(t)};for(var e=0;e<g.length;++e){var t=g[e];A[t]=M(t)}return A}(),a?Bs.exports=B:i.md5=B}();var ys=Ts.exports;const Ds=(A,e)=>{const t=Date.now(),s=`${A}:${t}:${ys.md5(`${e}${t}`)}`,i=(new TextEncoder).encode(s);return btoa(String.fromCharCode(...i))},Rs=A=>/^\d+$/.test(A),Us="/v1/aicc/bmserver",ks="/v1/aicc/ccs";let Gs="",Fs="",Ys="",xs="";function vs(){const A=Ds(Fs,Ys);return Ss.create({prefixUrl:`${Gs}`,timeout:!1,headers:{Authorization:A},hooks:{afterResponse:[async(A,e,t)=>{if(-1!==t.url.indexOf("heartbeat"))return t;const s=await t.clone().json();if(0!==s.code)throw new Error(JSON.stringify(s)||"请求失败");return t.json=async()=>s,t}]}})}async function Zs(A,e){const t=vs(),s="api/"+A.replace(/^\/+/,"");return t.post(s,{json:e}).json()}const Os=A=>Zs(`${ks}/state/change`,A),Ns=()=>async function(A,e){const t=vs(),s=A.replace(/^\/+/,"");return t.post(s,{json:e}).json()}("/heartbeat",{});class Ks{constructor(){this.roleData={agentInfo:()=>{if(!Ve.agentInfo?.agent_no)throw new Error(JSON.stringify({code:1,msg:"请先登录"}))},requestInfo:A=>{if(!A.data)throw new Error(JSON.stringify({code:1,msg:'Parameter "data" is required'}))},changeDevice:A=>{if(!A)throw new Error(JSON.stringify({code:1,msg:'Parameter "device" is required'}));const{answer_devices:e}=Ve.agentInfo;if(!e.split(",").map(A=>Number(A)).includes(A))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},changeState:(A,e)=>{if(!A)throw new Error(JSON.stringify({code:1,msg:'Parameter "state" is required'}));if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "state_name" is required'}));if(2===A&&("通话中"===e||"整理"===e))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}));if(![1,2].includes(A))throw new Error(JSON.stringify({code:1,msg:"当前状态不支持"}))},setAgentExplicit:A=>{const{out_display_select_switch:e,out_display_data:t}=Ve.agentInfo;if(1!==e)throw new Error(JSON.stringify({code:1,msg:"当前坐席设置未开启允许指定外显"}));if(!A)throw new Error(JSON.stringify({code:1,msg:'Parameter "number" is required'}));if(!(t||"").split("#").includes(A))throw new Error(JSON.stringify({code:1,msg:"当前外显号码不存在"}))}}}formatDate(A){return`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")} ${String(A.getHours()).padStart(2,"0")}:${String(A.getMinutes()).padStart(2,"0")}:${String(A.getSeconds()).padStart(2,"0")}`}async _agentLogin(A){try{const t=await(e={agent_no:A},Zs(`${ks}/agent/login`,e));Ve.agentInfo=t.data}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}var e}async _changeState(A){try{Ve.autoStateTimer&&(clearTimeout(Ve.autoStateTimer),Ve.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(A);const{data:e,success:t}=A,{state:s,state_name:i}=e,{agent_no:n}=Ve.agentInfo;await Os({agent_no:n,state_name:i,state:s}),s===exports.AgentStatus.IDLE?le.updateActionConfigs(ft):s===exports.AgentStatus.BUSY&&le.updateActionConfigs(Bt),Ve.stateObject={state:s,state_name:i},t?.({code:0,msg:"请求成功"})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async _getInCallCrmDetail(A){try{const{phone:e}=A.data,t={};Rs(e)?t.phone=e:t.trace_id=e;const s=await(A=>Zs(`${Us}/crm/popups`,A))({...t});A.success?.(s)}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async changeDevice(A){try{if(le.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));this.roleData.agentInfo(),this.roleData.requestInfo(A);const{data:e,success:t}=A,{device:s}=e;1===s&&le.updateAnswerDevice(s),this.roleData.changeDevice(s);const{agent_no:i}=Ve.agentInfo;await(A=>Zs(`${ks}/device/change`,A))({agent_no:i,answer_device:s}),le.updateAnswerDevice(s);const n=le.get("actionConfigs");le.updateActionConfigs(n),2===s&&Ve.stateObject.state===exports.AgentStatus.UNREGISTERED&&await this._changeState({data:{...Ve.stateBeforeChange,state_name:Ve.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}}),t?.({code:0,msg:"请求成功"})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async changeState(A){try{if(le.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前正在通话中,请勿切换设备"}));Ve.autoStateTimer&&(clearTimeout(Ve.autoStateTimer),Ve.autoStateTimer=null),this.roleData.agentInfo(),this.roleData.requestInfo(A);const{data:e,success:t}=A,{state:s,state_name:i}=e;this.roleData.changeState(s,i);const{agent_no:n}=Ve.agentInfo;await Os({agent_no:n,state_name:i,state:s}),(Ve.stateObject.state===exports.AgentStatus.IDLE||Ve.stateObject.state===exports.AgentStatus.BUSY&&"整理"!==i)&&(Ve.stateBeforeChange=Ve.stateObject),s===exports.AgentStatus.IDLE?le.updateActionConfigs(ft):s===exports.AgentStatus.BUSY&&le.updateActionConfigs(Bt),Ve.stateObject={state:s,state_name:i},t?.({code:0,msg:"请求成功"})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async getIdleAgentList(A){const{agent_no:e}=Ve.agentInfo;try{this.roleData.agentInfo();const t=await(A=>Zs(`${ks}/agent/free`,A))({agent_no:e});A.success?.(t)}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async getAgentState(A){try{const e=await Zs(`${Us}/agent/statecfg/list`,{}),t=(e.data||[]).filter(A=>0===A.enable).filter(A=>0!==A.state&&3!==A.state).filter(A=>"通话中"!==A.state_name&&"整理"!==A.state_name&&"未注册"!==A.state_name&&"离线接听"!==A.state_name).map(A=>({state:A.state,state_name:A.state_name})).reverse();A.success?.({...e,data:t})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async setAgentExplicit(A){try{this.roleData.agentInfo(),this.roleData.requestInfo(A),this.roleData.setAgentExplicit(A.data.number);const{agent_id:e}=Ve.agentInfo;await(A=>Zs(`${Us}/agent/update`,A))({agent_id:e,out_display_number:A.data.number}),le.updateSelectOutNumber(A.data.number),A.success?.({code:0,msg:"请求成功"})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async checkAgentLogin(A){try{this.roleData.requestInfo(A);const{agent_no:e}=A.data;if(!e)throw new Error(JSON.stringify({code:1,msg:'Parameter "agent_no" is required'}));const t=await(A=>Zs(`${ks}/agent/islogin`,A))({agent_no:e});A.success?.(t)}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async getCallRecord(A){try{this.roleData.agentInfo();const{success:e}=A,t=new Date,s=new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,0),i=new Date(t.getFullYear(),t.getMonth(),t.getDate(),23,59,59),n=[this.formatDate(s),this.formatDate(i)],{agent_no:o}=Ve.agentInfo,r=await(A=>Zs(`${Us}/agent/recordpage`,A))({start_time:n[0],end_time:n[1],page_no:1,page_size:10,agent_no:o}),{code:a,msg:V,data:c}=r;e?.({code:a,msg:V,data:c})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async logout(A){this.roleData.agentInfo();try{const{agent_no:e}=Ve.agentInfo,{data:t,success:s}=A;await(A=>Zs(`${ks}/agent/logout`,A))({...t,agent_no:e}),s?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async listenCall(A){try{const{agent_no:e}=Ve.agentInfo,{data:t,success:s}=A;if(this.roleData.agentInfo(),this.roleData.requestInfo(A),!t.monitored_agent_no)throw new Error(JSON.stringify({code:1,msg:'Parameter "monitored_agent_no" is required'}));await(A=>Zs(`${ks}/call/monitor`,A))({...t,monitor_agent_no:e}),Ve.monitoredAgentNo=t.monitored_agent_no,s?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async earCall(A){try{const{agentInfo:e,monitoredAgentNo:t}=Ve,{agent_no:s}=e;this.roleData.agentInfo();const{success:i}=A;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(A=>Zs(`${ks}/call/whisper`,A))({monitored_agent_no:t,monitor_agent_no:s}),i?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async stopEarCall(A){try{const{agentInfo:e,earSpeakAgent:t}=Ve;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前没有正在耳语的坐席"}));const{agent_no:s}=e;this.roleData.agentInfo();const{success:i}=A;await(A=>Zs(`${ks}/call/stopwhisper`,A))({monitor_agent_no:s,monitored_agent_no:t}),i?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async forceInsert(A){try{const{agentInfo:e,monitoredAgentNo:t}=Ve,{agent_no:s}=e;this.roleData.agentInfo();const{success:i}=A;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(A=>Zs(`${ks}/call/bargein`,A))({monitored_agent_no:t,monitor_agent_no:s}),i?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}async forceDisconnect(A){try{const{agentInfo:e,monitoredAgentNo:t}=Ve,{agent_no:s}=e;this.roleData.agentInfo();const{success:i}=A;if(!t)throw new Error(JSON.stringify({code:1,msg:"当前未有监听坐席"}));await(A=>Zs(`${ks}/call/intercept`,A))({monitored_agent_no:t,monitor_agent_no:s}),i?.({code:0,msg:""})}catch(A){throw ae.emit(exports.EventName.FAIL_NOTIFICATION,JSON.parse(A.message).msg),A}}}let bs=class extends Ct{constructor(){super(...arguments),this.type="info",this.content="",this.duration=3e3}static{this.styles=Ee`
|
|
528
528
|
:host {
|
|
529
529
|
display: block;
|
|
530
530
|
margin-top: 10px;
|
|
@@ -763,7 +763,7 @@ Bs=Ts,function(){var t="input is invalid type",s="object"==typeof window,i=s?win
|
|
|
763
763
|
`}
|
|
764
764
|
</div>
|
|
765
765
|
</my-modal-wrapper>
|
|
766
|
-
`;mt(s,this.modalRoot)}})}catch(A){Hs(A)}}getActionConfigs(){const A=le.get("actionConfigs");return[{render:this.renderCallPopover,type:"call_number"},{render:this.renderAnswer,type:"answer"},{render:this.renderReject,type:"reject"},{render:this.renderHangup,type:"hangup"},{render:this.renderDialer,type:"dtmf"},{render:this.renderUnhold,type:"unhold"},{render:this.renderHold,type:"hold"},{render:this.renderMute,type:"mute"},{render:this.renderUnmute,type:"unmute"},{render:this.renderSatisfaction,type:"satisfaction"},{render:this.renderConsult,type:"consult"},{render:this.renderTransfer,type:"transfer"},{render:this.renderConsultTransfer,type:"consult_transfer"},{render:this.renderConsultRetrieve,type:"consult_retrieve"},{render:this.renderConference,type:"conference"}].filter(({type:e})=>A.includes(e))}async render(){if(!this.isLoad)return void mt(et`<span></span>`,this.container);const{displayText:A}=le.getState(),{answer_devices:e,out_display_data:t,out_display_select_switch:s}=Ve.agentInfo,i=(e||"").split(","),n=this.getActionConfigs(),o={...
|
|
766
|
+
`;mt(s,this.modalRoot)}})}catch(A){Hs(A)}}getActionConfigs(){const A=le.get("actionConfigs");return[{render:this.renderCallPopover,type:"call_number"},{render:this.renderAnswer,type:"answer"},{render:this.renderReject,type:"reject"},{render:this.renderHangup,type:"hangup"},{render:this.renderDialer,type:"dtmf"},{render:this.renderUnhold,type:"unhold"},{render:this.renderHold,type:"hold"},{render:this.renderMute,type:"mute"},{render:this.renderUnmute,type:"unmute"},{render:this.renderSatisfaction,type:"satisfaction"},{render:this.renderConsult,type:"consult"},{render:this.renderTransfer,type:"transfer"},{render:this.renderConsultTransfer,type:"consult_transfer"},{render:this.renderConsultRetrieve,type:"consult_retrieve"},{render:this.renderConference,type:"conference"}].filter(({type:e})=>A.includes(e))}async render(){if(!this.isLoad)return void mt(et`<span></span>`,this.container);const{displayText:A}=le.getState(),{answer_devices:e,out_display_data:t,out_display_select_switch:s}=Ve.agentInfo,i=(e||"").split(","),n=this.getActionConfigs(),o={...Mt},{statusColor:r}=o,a=document.querySelector("head"),{city:V,contact_count:c,customer_name:l,phone:h,province:g}=this.customerInfo||{};if(a){const A=et`
|
|
767
767
|
<style>
|
|
768
768
|
.ysyt-phone-body {
|
|
769
769
|
background: ${r[this.statusParams.state]};
|
|
@@ -911,4 +911,4 @@ Bs=Ts,function(){var t="input is invalid type",s="object"==typeof window,i=s?win
|
|
|
911
911
|
`:""}
|
|
912
912
|
</div>
|
|
913
913
|
</my-popover>
|
|
914
|
-
`;mt(s,this.rttHTML)}}class Ps{static requestPermission(){"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission()}static async requestMediaPermissions(){try{const A=await navigator.mediaDevices.enumerateDevices();if(A.some(A=>"audioinput"===A.kind&&""!==A.label))return null;return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(A){return console.warn("获取音频权限失败:",A),null}}static show(A,e,t,s){if("Notification"in window&&"granted"===Notification.permission){const i=new Notification(A,{body:e,tag:`xy-global-notification${(new Date).getTime()}`,renotify:!0});i.onclick=()=>{window.focus(),i.close(),t?.()},setTimeout(()=>i.close(),1e3*(s||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(A=>"audioinput"===A.kind&&""!==A.label)}catch(A){return console.warn("无法检查设备权限:",A),!1}}}const zs=console.log,Xs=(...A)=>{Ve.logBuiltinEnabled&&zs(...A)};let _s=null;class $s{constructor(A){this.url=A,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new Ks,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:A,sipClient:e}){if(!_s){if(!A)throw new Error("WebSocket 尚未初始化");_s=new $s(A),_s.sipClient=e}return _s}stateIdleChange(){const{state:A}=Ve.stateObject;A!==exports.AgentStatus.IDLE&&(Ve.stateBeforeChange,this.apiClient._changeState({data:{...Ve.stateBeforeChange,state_name:Ve.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}}))}inCallAutoAnswer(){const{soft_device_auto_answer:A,auto_answer_time:e}=Ve.agentInfo,t=1===A,s=le.get("direction");if(t&&s===exports.DirectionEnum.INCOMING){const A=Number(e)||0;A>0&&(Ve.autoAnswerTimer=setTimeout(()=>{this.sipClient?.answerCall(),Ve.autoAnswerTimer=null},1e3*A))}}async getCustomerInfo(A){try{await this.apiClient._getInCallCrmDetail({data:{phone:A},success:A=>{le.updateCustomerInfo(A.data||{phone:A.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:A.data.trace_id,contact_count_month:0,in_contact_count_month:0})}})}catch(A){}}putAgentState(A,e){if(!A)return;if(5===e)return void this.stateIdleChange();Ve.sessionId="";const{post_call_process_time:t}=Ve.agentInfo,s=t||0;if(Ve.autoStateTimer&&(clearTimeout(Ve.autoStateTimer),Ve.autoStateTimer=null),le.updateCustomerInfo(void 0),s>0){const{state:A}=Ve.stateObject;if(A===exports.AgentStatus.IDLE)return;this.apiClient._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"整理"}}),Ve.autoStateTimer=setTimeout(()=>{Ve.autoStateTimer=null,this.stateIdleChange()},1e3*s)}else this.stateIdleChange()}stateBusyChange(){Ve.sessionId="",clearTimeout(Ve.autoStateTimer),le.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"忙碌"}})}initWebSocket(){if(1===this.ws?.readyState)return;const A=Ds(Fs,Ys);this.ws=new WebSocket(this.url+A),this.ws.onopen=()=>{const A=(new Date).getTime();this.sendMessage({type:0,msg_id:A}),this.pendingMessages.set(A,performance.now()),this.startHeartbeat(),this.manualClose=!1},this.ws.onmessage=async A=>{const e=JSON.parse(A.data),{type:t,data:s,code:i,msg:n,msg_id:o}=e;if(0===t&&o){const A=this.pendingMessages.get(o),e=performance.now()-A;Ve.latency=parseFloat(e.toFixed(2)),this.pendingMessages.delete(o)}if(0!==t&&Xs("%cWebSocket 收到消息:","color: blue; font-weight: bold;",e),t!==exports.WebsocketTypeEnum.OUT_CALL&&t!==exports.WebsocketTypeEnum.PREVIEW_OUT_CALL||(0!==i?(le.reset(),ae.emit(exports.CallSipCallEventEnum.OUT_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n),le.updateActionConfigs(ft),setTimeout(()=>{le.updateCustomerInfo(void 0)},500),this.stateIdleChange()):0===i&&(ae.emit(exports.CallSipCallEventEnum.OUT_SUCCESS),clearTimeout(Ve.autoStateTimer))),t===exports.WebsocketTypeEnum.AGENT_STATE){const{state:A,state_name:e}=s;Ve.stateObject={state:A,state_name:e},"振铃中"===e&&le.updateDisplayText(exports.DisplayTextEnum.AGENT_RINGING),A===exports.AgentStatus.UNREGISTERED&&le.updateActionConfigs(Mt),A===exports.AgentStatus.IDLE&&Ve.stateObject.state===exports.AgentStatus.UNREGISTERED&&le.updateActionConfigs(ft),ae.emit(exports.CallSipCallEventEnum.AGENT_STATE,{state:A,state_name:e})}if(t===exports.WebsocketTypeEnum.OUT_CALL_INCOMING_CALL){try{await this.getCustomerInfo(s.trace_id||s.customer_phone)}catch(A){console.error(A)}s.preview_task_id?ae.emit(exports.CallSipCallEventEnum.PREVIEW_OUT_INCOMING_CALL,{customer_phone:s.customer_phone,session_id:s.session_id,preview_task_id:s.preview_task_id,trace_id:s.trace_id}):ae.emit(exports.CallSipCallEventEnum.OUT_INCOMING_CALL,{customer_phone:s.customer_phone,session_id:s.session_id,trace_id:s.trace_id}),Ve.sessionId=s.session_id,le.updateActionConfigs(St)}if(t===exports.WebsocketTypeEnum.OUT_CALL_END)if(le.updateDisplayText(""),1===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.OUT_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft);else if(2===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)le.reset(),ae.emit(exports.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:s.session_id}),this.putAgentState(!0),le.updateActionConfigs(ft);else if(2===s.device_type&&s.agent_no!==Ve.agentInfo.agent_no){le.get("isCalling")&&(le.updateDisplayText(exports.DisplayTextEnum.CALLING),ae.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(Qt))}else 3===s.device_type&&s.agent_no===Ve.agentInfo.agent_no?(this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft)):4===s.device_type&&s.agent_no===Ve.agentInfo.agent_no?(this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.TRANSFER_END,{session_id:s.session_id}),le.updateActionConfigs(ft)):5===s.device_type&&s.agent_no===Ve.agentInfo.agent_no&&(this.putAgentState(!0,5),Ve.monitoredAgentNo="",Ve.earSpeakAgent="",le.reset(),ae.emit(exports.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft));if(t===exports.WebsocketTypeEnum.OUT_CALL_RINGING&&1===s.type&&(ae.emit(exports.CallSipCallEventEnum.OUT_RINGING,{session_id:Ve.sessionId,type:s.type}),le.updateDisplayText(exports.DisplayTextEnum.RINGING)),t===exports.WebsocketTypeEnum.OUT_CALL_ANSWER&&(clearTimeout(Ve.autoStateTimer),le.updateIsCalling(!0),ae.emit(exports.CallSipCallEventEnum.OUT_OFF_ANSWER,{session_id:Ve.sessionId}),le.updateOutCallIsAnswer(!0),le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateActionConfigs(Qt)),t===exports.WebsocketTypeEnum.CONSULT_RINGING&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_RINGING,{session_id:s.session_id}),le.updateDisplayText(exports.DisplayTextEnum.AGENT_RINGING),le.updateActionConfigs([]),clearTimeout(Ve.autoStateTimer)),t===exports.WebsocketTypeEnum.CONSULT_ANSWER&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_OFF_HOOK,{session_id:s.session_id}),le.updateConsultIsAnswer(!0),le.updateDisplayText(exports.DisplayTextEnum.CONSULTING),le.updateActionConfigs(Tt)),t===exports.WebsocketTypeEnum.CONSULT_FAIL&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_FAILED,{custom_reason:s.custom_reason}),le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateActionConfigs(Qt)),t===exports.WebsocketTypeEnum.CONSULT_CALL_IN&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_INCOMING,{agent_no:s.agent_no,agent_mane:s.agent_name,session_id:s.session_id}),Ve.sessionId=s.session_id,le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.CONSULT),le.updateDisplayText(exports.DisplayTextEnum.CONSULT_CALL_IN),le.updateActionConfigs(Rt),Ve.enableBrowserAlert&&Ps.show("📞 咨询来电",`坐席 [${s.agent_name}] 正在咨询...`,()=>{ae.emit(exports.EventName.NOTIFICATION_CLICK,{agent_mane:s.agent_name,agent_no:s.agent_no})},Ve.browserAlertTime)),t===exports.WebsocketTypeEnum.CONSULT_CALL_IN_SUCCESS&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_CALL_IN_SUCCESS,{session_id:s.session_id}),le.updateConsultIsAnswer(!0),le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateActionConfigs(yt)),t===exports.WebsocketTypeEnum.CONSULT_RETURN_CALL_SUCCESS&&("success"===s.status?(le.updateConsultIsAnswer(!1),ae.emit(exports.CallSipCallEventEnum.CONSULT_RETURN_CALL_SUCCESS),le.updateDisplayText(exports.DisplayTextEnum.CALLING),ae.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP),le.updateActionConfigs(Qt)):ae.emit(exports.EventName.FAIL_NOTIFICATION,"媒体失败")),t===exports.WebsocketTypeEnum.MUTE&&(0===i?(le.updateIsMuted(!0),ae.emit(exports.CallSipCallEventEnum.MUTE_SUCCESS),le.updateDisplayText(exports.DisplayTextEnum.MUTING)):(ae.emit(exports.CallSipCallEventEnum.MUTE_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.UNMUTE&&(0===i?(le.updateIsMuted(!1),ae.emit(exports.CallSipCallEventEnum.UNMUTE_SUCCESS),le.updateDisplayText(exports.DisplayTextEnum.CALLING)):(ae.emit(exports.CallSipCallEventEnum.UNMUTE_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CALL_HOLD&&(0===i?(le.updateIsHold(!0),le.updateDisplayText(exports.DisplayTextEnum.HOLDING),ae.emit(exports.CallSipCallEventEnum.HOLD_SUCCESS)):(ae.emit(exports.CallSipCallEventEnum.HOLD_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CALL_UNHOLD&&(0===i?(le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateIsHold(!1),ae.emit(exports.CallSipCallEventEnum.UNHOLD_SUCCESS)):(ae.emit(exports.CallSipCallEventEnum.UNHOLD_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CONSULT_TRANSFER&&(0===i?ae.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_SUCCESS):(ae.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CONSULT_TRANSFER_FAILED&&ae.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,s.status),t===exports.WebsocketTypeEnum.CONSULT_TRANSFER_OFF_HOOK&&(le.updateDirection(exports.DirectionEnum.INCOMING),le.updateDisplayText(exports.DisplayTextEnum.CALLING),ae.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_OFF_HOOK),le.updateActionConfigs(Ut),le.updateIncomingIsAnswer(!0),le.updateConsultIsAnswer(!1)),t===exports.WebsocketTypeEnum.INCOMING_CALL){clearTimeout(Ve.autoStateTimer),Ve.sessionId=s.session_id;try{await this.getCustomerInfo(s.trace_id||s.customer_phone)}catch(A){console.error(A)}le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.INCOMING),this.inCallAutoAnswer(),le.updateDisplayText(exports.DisplayTextEnum.INCOMING_CALL),1===s.direction&&ae.emit(exports.CallSipCallEventEnum.INCOMING_CALL,{customer_phone:s.customer_phone,trace_id:s.trace_id,session_id:s.session_id}),3===s.direction&&(ae.emit(exports.CallSipCallEventEnum.PREDICT_INCOMING_CALL,{customer_phone:s.customer_phone,trace_id:s.trace_id,session_id:s.session_id}),this.sipClient?.answerCall()),le.updateActionConfigs(Rt),Ve.enableBrowserAlert&&Ps.show("📞 客户来电",`客户 [${s.customer_phone}] 正在呼入...`,()=>{ae.emit(exports.EventName.NOTIFICATION_CLICK,{customer_phone:s.customer_phone})},Ve.browserAlertTime)}if(t===exports.WebsocketTypeEnum.INCOMING_CALL_OFF_HOOK&&(le.updateIncomingIsAnswer(!0),ae.emit(exports.CallSipCallEventEnum.INCOMING_CALL_OFF_HOOK,{session_id:Ve.sessionId}),le.updateActionConfigs(Ut),le.updateDisplayText(exports.DisplayTextEnum.CALLING)),t===exports.WebsocketTypeEnum.INCOMING_CALL_END&&(le.updateDisplayText(""),1===s.device_type&&s.agent_no===Ve.agentInfo.agent_no?(this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.INCOMING_CALL_END,{session_id:s.session_id}),le.updateActionConfigs(ft)):2===s.device_type&&s.agent_no===Ve.agentInfo.agent_no?(le.reset(),ae.emit(exports.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:s.session_id}),this.putAgentState(!0),le.updateActionConfigs(ft)):2===s.device_type&&s.agent_no!==Ve.agentInfo.agent_no?(le.updateDisplayText(exports.DisplayTextEnum.CALLING),ae.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(Qt)):3===s.device_type&&s.agent_no===Ve.agentInfo.agent_no?(this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft)):4===s.device_type&&s.agent_no===Ve.agentInfo.agent_no?(this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.TRANSFER_END,{session_id:s.session_id}),le.updateActionConfigs(ft)):5===s.device_type&&s.agent_no===Ve.agentInfo.agent_no&&(this.putAgentState(!0,5),Ve.monitoredAgentNo="",Ve.earSpeakAgent="",le.reset(),ae.emit(exports.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft))),t===exports.WebsocketTypeEnum.SATISFACTION_EVALUATION&&(0===i?ae.emit(exports.CallSipCallEventEnum.SATISFACTION_EVALUATION_SUCCESS):(ae.emit(exports.CallSipCallEventEnum.SATISFACTION_EVALUATION_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CONSULT_THREE_WAY&&(0!==i?(ae.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n)):0===i&&le.updateIsMeeting(!0)),t===exports.WebsocketTypeEnum.CONSULT_THREE_WAY_RESULT&&("success"===s.status?(le.updateDirection(exports.DirectionEnum.MEETING),le.updateDisplayText(exports.DisplayTextEnum.MEETING),le.updateActionConfigs(Dt),ae.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_SUCCESS)):(ae.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,{conf_name:s.conf_name}),le.updateIsMeeting(!1))),t===exports.WebsocketTypeEnum.TRANSFER_INCOMING_CALL&&(clearTimeout(Ve.autoStateTimer),s.agent_no===Ve.agentInfo.agent_no?(le.updateDisplayText(exports.DisplayTextEnum.TRANSFERRING),ae.emit(exports.CallSipCallEventEnum.TRANSFER_PROGRESS),le.updateActionConfigs([]),le.updateTransferIsAnswer(!0)):(Ve.sessionId=s.session_id,ae.emit(exports.CallSipCallEventEnum.TRANSFER_INCOMING_CALL,{agent_no:s.agent_no,agent_name:s.agent_name,session_id:s.session_id}),le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.TRANSFER),le.updateDisplayText(exports.DisplayTextEnum.TRANSFER_INCOMING_CALL),le.updateActionConfigs(Rt),Ve.enableBrowserAlert&&Ps.show("📞 转接来电",`坐席 [${s.agent_no}] 正在转接...`,()=>{ae.emit(exports.EventName.NOTIFICATION_CLICK,{agent_no:s.agent_no})},Ve.browserAlertTime))),t===exports.WebsocketTypeEnum.TRANSFER_OFF_HOOK&&(ae.emit(exports.CallSipCallEventEnum.TRANSFER_OFF_HOOK,{session_id:Ve.sessionId}),le.updateTransferIsAnswer(!1),le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateActionConfigs(Ut)),t===exports.WebsocketTypeEnum.TRANSFER_FAILED&&"failed"===s.status){ae.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ae.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const A=le.get("direction");A===exports.DirectionEnum.OUTGOING?le.updateActionConfigs(Qt):A===exports.DirectionEnum.INCOMING&&le.updateActionConfigs(Ut)}t===exports.WebsocketTypeEnum.KICK_OFFLINE&&ae.emit(exports.EventName.KICK_OFF),t===exports.WebsocketTypeEnum.CONTINUOUS_NOT_ANSWER&&(ae.emit(exports.EventName.FAIL_NOTIFICATION,`已连续 ${s.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()),t===exports.WebsocketTypeEnum.SIGN_OUT&&ae.emit(exports.EventName.SIGN_OUT),t===exports.WebsocketTypeEnum.SIGN_IN_SWITCH_DEVICE&&ae.emit(exports.EventName.SIGN_IN_SWITCH_DEVICE,s),t===exports.WebsocketTypeEnum.LISTEN_INCOMING_CALL&&(clearTimeout(Ve.autoStateTimer),Ve.sessionId=s.session_id,le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.INCOMING),this.inCallAutoAnswer(),le.updateDisplayText(exports.DisplayTextEnum.LISTENING),le.updateActionConfigs(Rt),ae.emit(exports.CallSipCallEventEnum.LISTEN_INCOMING_CALL,{session_id:s.session_id}),Ve.enableBrowserAlert&&Ps.show("📞 监听来电","正在来电...",()=>{ae.emit(exports.EventName.NOTIFICATION_CLICK,{customer_phone:s.customer_phone})},Ve.browserAlertTime)),t===exports.WebsocketTypeEnum.LISTEN_INCOMING_CALL_OFF_HOOK&&(Ve.monitoredAgentNo=s.monitored_agent_no,Ve.earSpeakAgent="",le.updateIncomingIsAnswer(!0),ae.emit(exports.CallSipCallEventEnum.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:Ve.sessionId,monitored_agent_no:s.monitored_agent_no}),le.updateActionConfigs(kt),le.updateDisplayText(exports.DisplayTextEnum.CALLING)),t===exports.WebsocketTypeEnum.LISTEN_CALL_FAILED&&"failed"===s.status&&(ae.emit(exports.CallSipCallEventEnum.LISTEN_CALL_FAILED),Ve.monitoredAgentNo=""),t===exports.WebsocketTypeEnum.EAR_SPEECH&&("success"===s.status?(s.monitored_agent_no===Ve.agentInfo.agent_no&&(le.updateActionConfigs(Gt),ae.emit(exports.CallSipCallEventEnum.EAR_SPEECH_BE_SUCCESS)),s.monitor_agent_no===Ve.agentInfo.agent_no&&(le.updateActionConfigs(Ft),ae.emit(exports.CallSipCallEventEnum.EAR_SPEECH_SUCCESS,{monitored_agent_no:s.monitored_agent_no,monitor_agent_no:s.monitor_agent_no}),Ve.earSpeakAgent=s.monitored_agent_no)):ae.emit(exports.CallSipCallEventEnum.EAR_SPEECH_FAILED)),t===exports.WebsocketTypeEnum.STOP_EAR_SPEECH&&("success"===s.status?(s.monitored_agent_no===Ve.agentInfo.agent_no&&le.updateActionConfigs(Ut),s.monitor_agent_no===Ve.agentInfo.agent_no&&le.updateActionConfigs(kt),Ve.earSpeakAgent="",ae.emit(exports.CallSipCallEventEnum.STOP_EAR_SPEECH_SUCCESS)):ae.emit(exports.CallSipCallEventEnum.STOP_EAR_SPEECH_FAILED)),t===exports.WebsocketTypeEnum.CALL_FORCE_INSERT&&("success"===s.status?(s.monitored_agent_no===Ve.agentInfo.agent_no&&(le.updateActionConfigs(xt),ae.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:s.monitored_agent_no,monitor_agent_no:s.monitor_agent_no})),s.monitor_agent_no===Ve.agentInfo.agent_no&&(le.updateActionConfigs(Yt),ae.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:s.monitored_agent_no,monitor_agent_no:s.monitor_agent_no}))):ae.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_FAILED))},this.ws.onclose=()=>{this.stopHeartbeat(),this.manualClose||setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=()=>{this.ws?.close()}}startHeartbeat(){const A=new Blob(["\n let timer;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timer = setInterval(() => {\n self.postMessage('heartbeat');\n }, 5000);\n } else if (e.data === 'stop') {\n clearInterval(timer);\n }\n };\n "],{type:"application/javascript"}),e=URL.createObjectURL(A);this.heartbeatWorker=new Worker(e),this.heartbeatWorker.onmessage=()=>{const A=(new Date).getTime();this.sendMessage({type:0,msg_id:A}),this.pendingMessages.set(A,performance.now())},this.heartbeatWorker.postMessage("start")}stopHeartbeat(){this.heartbeatWorker&&(this.heartbeatWorker.postMessage("stop"),this.heartbeatWorker.terminate(),this.heartbeatWorker=null)}sendMessage(A){this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(A)),0!==A.type&&Xs("%cWebSocket 发送消息:","color: green; font-weight: bold;",A)):console.warn("WebSocket 未连接,消息未发送")}close(){this.manualClose=!0,this.stopHeartbeat(),this.ws?.close()}reconnect(){this.initWebSocket()}static __internalClose(){_s&&(_s.close(),_s=null)}static __internalSend(A){if(!_s)throw new Error("WebSocket 尚未初始化");_s.sendMessage(A)}}class Ai{constructor(A){this.sipClient=null,this.sipClient=A}roleMute(){const A=le.get("isCalling"),e=Ve.sessionId;if(!A)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}))}holdCall(){this.roleMute();const A=le.get("isHold"),{sessionId:e}=Ve;if(!e)return;if(!le.get("actionConfigs").includes("hold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿保持"}));if(A)throw new Error(JSON.stringify({code:1,msg:"当前已处于保持状态"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CALL_HOLD,data:{session_id:e}})}unholdCall(){this.roleMute();const{isHold:A}=le.getState(),{sessionId:e}=Ve;if(!le.get("actionConfigs").includes("unhold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取消保持"}));if(e){if(!A)throw new Error(JSON.stringify({code:1,msg:"当前未处于保持状态"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CALL_UNHOLD,data:{session_id:e}})}}sendDTMF(A){if(1!==le.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));if(!le.get("actionConfigs").includes("dtmf"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿发送按键"}));const{isCalling:e}=le.getState();if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));this.sipClient.sendDTMF(A)}cancelCall(){if(!le.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const A=Ve.sessionId;ae.emit(exports.CallSipCallEventEnum.REJECT,{session_id:A}),$s.__internalSend({type:exports.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:A}})}async consultCall(A){this.roleMute();const{isCalling:e,outCallIsAnswer:t,consultIsAnswer:s,incomingIsAnswer:i}=le.getState(),n=Ve.sessionId;if(!le.get("actionConfigs").includes("consult"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询"}));if(s)throw new Error(JSON.stringify({code:1,msg:"当前正在咨询"}));if(!(e||t||i))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!n)throw new Error(JSON.stringify({code:1,msg:"sessionId不存在"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_REQUEST,data:{session_id:n,consultation_agent_no:A}})}async answerCall(){if(1!==le.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));await this.sipClient.answerCall()}makeCall(A){const e={};Rs(A)?e.customer_phone=A:e.trace_id=A;const t=le.get("isCalling"),s=le.get("selectOutNumber")||"";if(t)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof A||""===A.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.OUTGOING),$s.__internalSend({type:exports.WebsocketTypeEnum.OUT_CALL,data:{...e,caller:s}})}previewCall(A,e){const t={};Rs(A)?t.customer_phone=A:t.trace_id=A;const s=le.get("isCalling"),i=le.get("selectOutNumber")||"";if(s)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof A||""===A.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.OUTGOING),$s.__internalSend({type:exports.WebsocketTypeEnum.PREVIEW_OUT_CALL,data:{...t,caller:i,preview_task_id:e}})}async hangup(){if(!le.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const A=Ve.sessionId;$s.__internalSend({type:exports.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:A}})}mute(){this.roleMute();const A=le.get("actionConfigs"),e=le.get("isMuted"),t=Ve.sessionId;if(e)throw new Error(JSON.stringify({code:1,msg:"当前未处于静音状态"}));if(!A.includes("mute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));$s.__internalSend({type:exports.WebsocketTypeEnum.MUTE,data:{session_id:t}})}unmute(){this.roleMute();const A=le.get("actionConfigs"),e=le.get("isMuted"),t=Ve.sessionId;if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于未静音状态"}));if(!A.includes("unmute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));$s.__internalSend({type:exports.WebsocketTypeEnum.UNMUTE,data:{session_id:t}})}consultTransfer(){this.roleMute();const A=le.get("consultIsAnswer"),e=Ve.sessionId;if(!le.get("actionConfigs").includes("consult_transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询转移"}));if(!A)throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_TRANSFER,data:{session_id:e}})}satisfactionEvaluation(){this.roleMute();const A=Ve.sessionId;if(!le.get("actionConfigs").includes("satisfaction"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用满意度评价"}));$s.__internalSend({type:exports.WebsocketTypeEnum.SATISFACTION_EVALUATION,data:{session_id:A}})}startConference(){this.roleMute();if(!le.get("actionConfigs").includes("conference"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用三方会议"}));const A=Ve.sessionId;if(!le.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_THREE_WAY,data:{session_id:A}})}consultRetrieve(){this.roleMute();if(!le.get("actionConfigs").includes("consult_retrieve"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取回通话"}));const A=Ve.sessionId;if(!le.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_RETURN_CALL,data:{session_id:A}})}async transferAgent(A){this.roleMute();if(!le.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));const{transferIsAnswer:e}=le.getState(),t=Ve.sessionId;if(e)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));$s.__internalSend({type:exports.WebsocketTypeEnum.TRANSFER,data:{session_id:t,transfer_type:0,transfer_dest:A}})}async transferOutline(A){this.roleMute();if(!le.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));if(!A)throw new Error(JSON.stringify({code:1,msg:"号码不能为空"}));if(!/^\d+$/.test(A))throw new Error(JSON.stringify({code:1,msg:"号码格式错误"}));const{transferIsAnswer:e}=le.getState(),t=Ve.sessionId;if(e)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));if(e)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));$s.__internalSend({type:exports.WebsocketTypeEnum.TRANSFER,data:{session_id:t,transfer_type:2,transfer_dest:A}})}}var ei;class ti{static{this._instance=null}#A=null;#e=new Ks;#t;#s=null;#i=!1;#n;#o;#r=!1;static{this._timer=null}#a=null;constructor(){if(!ei._creatingInstance)throw new Error("请使用 YSYTAgentSdk.getInstance() 获取实例");clearInterval(this.#s),this.#s=setInterval(async()=>{const A=await this.#V();he.updateRttObject(A)},2e3),Ps.requestMediaPermissions(),this.#n=le.subscribeKey("answerDevice",async A=>{1===A?(await this.initWebRtc(),Ve.stateObject.state===exports.AgentStatus.UNREGISTERED&&await this.#e._changeState({data:{...Ve.stateBeforeChange,state_name:Ve.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}})):await this.destroyRtc()}),this.#o=le.subscribeKey("isNextState",async A=>{if(A){await this.#e._agentLogin(xs);1===le.get("answerDevice")&&await this.#A.reconnect();let A="";const e=new URL(Gs).host;A=Gs.includes("https")?`wss://${e}`:`ws://${e}`;const{agent_no:t}=Ve.agentInfo;$s.getInstance({url:`${A}/ccs-ws/api/v1/ws/call/${t}?Authorization=`,sipClient:this.#A}),Ve.stateObject.state===exports.AgentStatus.OFFLINE&&setTimeout(()=>{this.#e._changeState({data:{...this.#a,state_name:this.#a.state===exports.AgentStatus.BUSY&&"整理"===this.#a.state_name?"忙碌":this.#a.state_name},success:()=>{le.updateDisplayText(""),ae.emit(exports.CallSipCallEventEnum.AGENT_STATE,this.#a)}})},10)}else this.#a=Ve.stateObject,$s.__internalClose(),le.updateDisplayText("离线")}),this.on(exports.EventName.KICK_OFF,()=>{this.destroy()}),window.addEventListener("online",this.#c),window.addEventListener("offline",this.#l)}#c=()=>{le.updateIsNextState(!0)};#l=()=>{le.updateIsNextState(!1)};async#h(){const A=le.get("isNextState");try{await Ns(),A||le.updateIsNextState(!0)}catch(e){A&&le.updateIsNextState(!1)}}#g(){ei._timer||(ei._timer=setInterval(()=>this.#h(),3e3))}static get instance(){return this._instance}static async destroyInstance(){this._instance&&(await this._instance.destroy(),this._instance=null)}static getInstance(A){if(!this._instance){if(!A)throw new Error("首次调用必须传入配置参数");const{url:e,appKey:t,appSecret:s,agentNo:i}=A;Gs=e||"https://aicc-api.yescloudy.com",Fs=t,Ys=s,xs=i,ei._creatingInstance=!0,this._instance=new ei,delete ei._creatingInstance,window.addEventListener("beforeunload",()=>{this._instance?.destroy()})}return this._instance}getInit(){return this.#r}async initWebRtc(){if(this.#A)return;const A=Ve.agentInfo.sip_account_list.find(A=>1===A.device_type);if(!A)throw new Error(JSON.stringify({code:1,msg:"未找到 sip_account_list"}));{const e=A.sip_register_addr;this.#A=new ge({server:e.split(":")[0],user:A.sip_account,password:A.sip_password,webSocket:`wss://${e}`,callTimeout:3e4},this.#q),await this.#A.start()}}async init({actionNodeParams:A,enableBrowserAlert:e,logBuiltinEnabled:t,browserAlertTime:s,initialState:i,initDevice:n}){try{const{viewHtmlElement:o,rttHTML:r}=A||{};Ve.logBuiltinEnabled=t||!1,Ve.browserAlertTime=s||5e3,await this.#e._agentLogin(xs);const{agent_no:a,current_answer_device:V,current_state:c,out_display_number:l,out_display_select_switch:h}=Ve.agentInfo;(i||c)===exports.AgentStatus.IDLE?(le.updateActionConfigs(ft),Ve.stateObject={state:i||c,state_name:"空闲"},Ve.stateBeforeChange=Ve.stateObject):(i||c)===exports.AgentStatus.BUSY&&(le.updateActionConfigs(Bt),Ve.stateObject={state:c,state_name:"忙碌"},Ve.stateBeforeChange=Ve.stateObject),1===h?le.updateSelectOutNumber(l):le.updateSelectOutNumber("");let g="";const q=new URL(Gs).host;g=Gs.includes("https")?`wss://${q}`:`ws://${q}`,le.updateAnswerDevice(n||V),1===(n||V)&&await this.initWebRtc(),setTimeout(()=>{this.#e._changeState({data:Ve.stateObject}),this.#e.changeDevice({data:{device:n||V}})},500),$s.getInstance({url:`${g}/ccs-ws/api/v1/ws/call/${a}?Authorization=`,sipClient:this.#A}),this.#t=new Ai(this.#A),A&&o&&(this.#i=!0,new Ws({container:o,rttHTML:r,statusParams:{state:exports.AgentStatus.IDLE,statusName:"空闲"}},this,this.#t)),Ve.enableBrowserAlert=e,e&&Ps.requestPermission(),ae.emit(exports.EventName.AGENT_INIT_STATUS,!0),this.#r=!0,clearInterval(ei._timer),ei._timer=null,this.#g()}catch(A){this.#i&&Hs("初始化失败"),ae.emit(exports.EventName.AGENT_INIT_STATUS,!1),this.#r=!1}}#q=A=>{const{type:e,data:t}=A;ae.emit(e,t)};on(A,e){return ae.on(A,e),this}off(A,e){ae.off(A,e)}offAll(){ae.clearAllListeners()}async destroyRtc(){await(this.#A?.destroy()),this.#A=null}async destroy(){ei._instance&&(await this.destroyRtc(),clearInterval(this.#s),$s.__internalClose(),ae.emit(exports.EventName.DESTROY),this.offAll(),this.#n?.(),this.#o?.(),this.#i=!1,ei._instance=null,le.reset(),le.updateSelectOutNumber(""),clearInterval(ei._timer),ei._timer=null)}async#V(){return this.#A?this.#A.getNetworkStats():{}}get call_api(){const A=A=>(...e)=>{if(!this.#i)return A.apply(this,e);console.warn("当前未使用个人开发模式")};return{answerCall:A(()=>this.#t.answerCall()),makeCall:A=>this.#t.makeCall(A),previewMakeCall:(A,e)=>this.#t.previewCall(A,e),cancelCall:A(()=>this.#t.cancelCall()),hangup:A(()=>this.#t.hangup()),sendDTMF:A(A=>this.#t.sendDTMF(A)),holdCall:A(()=>this.#t.holdCall()),unholdCall:A(()=>this.#t.unholdCall()),consultCall:A(async A=>{try{await this.#t.consultCall(A)}catch(A){throw console.warn(A),A}}),consultRetrieve:A(()=>this.#t.consultRetrieve()),consultTransfer:A(()=>this.#t.consultTransfer()),mute:A(()=>this.#t.mute()),unmute:A(()=>this.#t.unmute()),satisfactionEvaluation:A(()=>this.#t.satisfactionEvaluation()),startConference:A(()=>this.#t.startConference()),transferAgent:A(A=>this.#t.transferAgent(A)),transferOutline:A(A=>this.#t.transferOutline(A)),earSpeakStart:A(A=>this.#e.earCall(A)),earSpeakStop:A(A=>this.#e.stopEarCall(A)),forceInsert:A(A=>this.#e.forceInsert(A)),forceDisconnect:A(A=>this.#e.forceDisconnect(A))}}get agent_api(){const A=A=>(...e)=>{if(!this.#i)return A.apply(this,e);console.warn("当前未使用个人开发模式")};return{changeDevice:A(A=>this.#e.changeDevice(A)),changeState:A(A=>this.#e.changeState(A)),getIdleAgentList:A(A=>this.#e.getIdleAgentList(A)),getAgentState:A(A=>this.#e.getAgentState(A)),setAgentExplicit:A(A=>this.#e.setAgentExplicit(A)),checkAgentLogin:A=>this.#e.checkAgentLogin(A),getCallRecord:A=>this.#e.getCallRecord(A),agentLogout:async(A,e)=>{try{await this.#e.logout(A),await this.destroy(),e?.({code:0,msg:""})}catch(A){}},listenAgentCall:A=>this.#e.listenCall(A)}}getAgentData(){const{agent_no:A,agent_name:e,answer_devices:t,out_display_data:s,out_display_select_switch:i,current_state:n}=Ve.agentInfo,{stateObject:o}=Ve,r={1:"软电话",2:"手机模式",3:"SIP话机"};return{agent_no:A,agent_name:e,init_state:n,default_device:le.get("answerDevice"),out_display_data:s,out_display_select_switch:i,answer_devices:(t||"").split(",").map(A=>({value:Number(A),label:r[Number(A)]})),stateObject:o}}async getRealTimeCustomerInfo(){return le.get("customerObject")}setBrowserAlert(A){if("boolean"!=typeof A)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));Ve.logBuiltinEnabled=A||!1}setBrowserAlertTime(A){if("number"!=typeof A)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));Ve.browserAlertTime=A||3e3}}ei=ti,exports.default=ti;
|
|
914
|
+
`;mt(s,this.rttHTML)}}class Ps{static requestPermission(){"Notification"in window&&"default"===Notification.permission&&Notification.requestPermission()}static async requestMediaPermissions(){try{const A=await navigator.mediaDevices.enumerateDevices();if(A.some(A=>"audioinput"===A.kind&&""!==A.label))return null;return await navigator.mediaDevices.getUserMedia({audio:!0})}catch(A){return console.warn("获取音频权限失败:",A),null}}static show(A,e,t,s){if("Notification"in window&&"granted"===Notification.permission){const i=new Notification(A,{body:e,tag:`xy-global-notification${(new Date).getTime()}`,renotify:!0});i.onclick=()=>{window.focus(),i.close(),t?.()},setTimeout(()=>i.close(),1e3*(s||3))}}static async checkMediaPermissions(){try{return(await navigator.mediaDevices.enumerateDevices()).some(A=>"audioinput"===A.kind&&""!==A.label)}catch(A){return console.warn("无法检查设备权限:",A),!1}}}const zs=console.log,Xs=(...A)=>{Ve.logBuiltinEnabled&&zs(...A)};let _s=null;class $s{constructor(A){this.url=A,this.ws=null,this.heartbeatWorker=null,this.reconnectDelay=3e3,this.manualClose=!1,this.apiClient=new Ks,this.sipClient=null,this.pendingMessages=new Map,this.initWebSocket()}static getInstance({url:A,sipClient:e}){if(!_s){if(!A)throw new Error("WebSocket 尚未初始化");_s=new $s(A),_s.sipClient=e}return _s}stateIdleChange(){const{state:A}=Ve.stateObject;A!==exports.AgentStatus.IDLE&&(Ve.stateBeforeChange,this.apiClient._changeState({data:{...Ve.stateBeforeChange,state_name:Ve.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}}))}inCallAutoAnswer(){const{soft_device_auto_answer:A,auto_answer_time:e}=Ve.agentInfo,t=1===A,s=le.get("direction");if(t&&s===exports.DirectionEnum.INCOMING){const A=Number(e)||0;A>0&&(Ve.autoAnswerTimer=setTimeout(()=>{this.sipClient?.answerCall(),Ve.autoAnswerTimer=null},1e3*A))}}async getCustomerInfo(A){try{await this.apiClient._getInCallCrmDetail({data:{phone:A},success:A=>{le.updateCustomerInfo(A.data||{phone:A.data.phone,is_vip:0,customer_name:"未知客户",city:"未知",province:"未知",contact_count:0,in_contact_count:0,trace_id:A.data.trace_id,contact_count_month:0,in_contact_count_month:0})}})}catch(A){}}putAgentState(A,e){if(!A)return;if(5===e)return void this.stateIdleChange();Ve.sessionId="";const{post_call_process_time:t}=Ve.agentInfo,s=t||0;if(Ve.autoStateTimer&&(clearTimeout(Ve.autoStateTimer),Ve.autoStateTimer=null),le.updateCustomerInfo(void 0),s>0){const{state:A}=Ve.stateObject;if(A===exports.AgentStatus.IDLE)return;this.apiClient._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"整理"}}),Ve.autoStateTimer=setTimeout(()=>{Ve.autoStateTimer=null,this.stateIdleChange()},1e3*s)}else this.stateIdleChange()}stateBusyChange(){Ve.sessionId="",clearTimeout(Ve.autoStateTimer),le.updateCustomerInfo(void 0),this.apiClient._changeState({data:{state:exports.AgentStatus.BUSY,state_name:"忙碌"}})}initWebSocket(){if(1===this.ws?.readyState)return;const A=Ds(Fs,Ys);this.ws=new WebSocket(this.url+A),this.ws.onopen=()=>{const A=(new Date).getTime();this.sendMessage({type:0,msg_id:A}),this.pendingMessages.set(A,performance.now()),this.startHeartbeat(),this.manualClose=!1},this.ws.onmessage=async A=>{const e=JSON.parse(A.data),{type:t,data:s,code:i,msg:n,msg_id:o}=e;if(0===t&&o){const A=this.pendingMessages.get(o),e=performance.now()-A;Ve.latency=parseFloat(e.toFixed(2)),this.pendingMessages.delete(o)}if(0!==t&&Xs("%cWebSocket 收到消息:","color: blue; font-weight: bold;",e),t!==exports.WebsocketTypeEnum.OUT_CALL&&t!==exports.WebsocketTypeEnum.PREVIEW_OUT_CALL||(0!==i?(le.reset(),ae.emit(exports.CallSipCallEventEnum.OUT_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n),le.updateActionConfigs(ft),setTimeout(()=>{le.updateCustomerInfo(void 0)},500),this.stateIdleChange()):0===i&&(ae.emit(exports.CallSipCallEventEnum.OUT_SUCCESS),clearTimeout(Ve.autoStateTimer))),t===exports.WebsocketTypeEnum.AGENT_STATE){const{state:A,state_name:e}=s;Ve.stateObject={state:A,state_name:e},"振铃中"===e&&le.updateDisplayText(exports.DisplayTextEnum.AGENT_RINGING),A===exports.AgentStatus.UNREGISTERED&&le.updateActionConfigs(wt),A===exports.AgentStatus.IDLE&&Ve.stateObject.state===exports.AgentStatus.UNREGISTERED&&le.updateActionConfigs(ft),ae.emit(exports.CallSipCallEventEnum.AGENT_STATE,{state:A,state_name:e})}if(t===exports.WebsocketTypeEnum.OUT_CALL_INCOMING_CALL){try{await this.getCustomerInfo(s.trace_id||s.customer_phone)}catch(A){console.error(A)}s.preview_task_id?ae.emit(exports.CallSipCallEventEnum.PREVIEW_OUT_INCOMING_CALL,{customer_phone:s.customer_phone,session_id:s.session_id,preview_task_id:s.preview_task_id,trace_id:s.trace_id}):ae.emit(exports.CallSipCallEventEnum.OUT_INCOMING_CALL,{customer_phone:s.customer_phone,session_id:s.session_id,trace_id:s.trace_id}),Ve.sessionId=s.session_id,le.updateActionConfigs(St)}if(t===exports.WebsocketTypeEnum.OUT_CALL_END)if(le.updateDisplayText(""),1===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.OUT_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft);else if(2===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)le.reset(),ae.emit(exports.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:s.session_id}),this.putAgentState(!0),le.updateActionConfigs(ft);else if(2===s.device_type&&s.agent_no!==Ve.agentInfo.agent_no){le.get("isCalling")&&(le.updateDisplayText(exports.DisplayTextEnum.CALLING),ae.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(Qt))}else if(3===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft);else if(4===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.TRANSFER_END,{session_id:s.session_id}),le.updateActionConfigs(ft);else if(4===s.device_type&&s.agent_no!==Ve.agentInfo.agent_no){ae.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ae.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const A=le.get("direction");A===exports.DirectionEnum.OUTGOING?le.updateActionConfigs(Qt):A===exports.DirectionEnum.INCOMING&&le.updateActionConfigs(Ut)}else 5===s.device_type&&s.agent_no===Ve.agentInfo.agent_no&&(this.putAgentState(!0,5),Ve.monitoredAgentNo="",Ve.earSpeakAgent="",le.reset(),ae.emit(exports.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft));if(t===exports.WebsocketTypeEnum.OUT_CALL_RINGING&&1===s.type&&(ae.emit(exports.CallSipCallEventEnum.OUT_RINGING,{session_id:Ve.sessionId,type:s.type}),le.updateDisplayText(exports.DisplayTextEnum.RINGING)),t===exports.WebsocketTypeEnum.OUT_CALL_ANSWER&&(clearTimeout(Ve.autoStateTimer),le.updateIsCalling(!0),ae.emit(exports.CallSipCallEventEnum.OUT_OFF_ANSWER,{session_id:Ve.sessionId}),le.updateOutCallIsAnswer(!0),le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateActionConfigs(Qt)),t===exports.WebsocketTypeEnum.CONSULT_RINGING&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_RINGING,{session_id:s.session_id}),le.updateDisplayText(exports.DisplayTextEnum.AGENT_RINGING),le.updateActionConfigs([]),clearTimeout(Ve.autoStateTimer)),t===exports.WebsocketTypeEnum.CONSULT_ANSWER&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_OFF_HOOK,{session_id:s.session_id}),le.updateConsultIsAnswer(!0),le.updateDisplayText(exports.DisplayTextEnum.CONSULTING),le.updateActionConfigs(Tt)),t===exports.WebsocketTypeEnum.CONSULT_FAIL&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_FAILED,{custom_reason:s.custom_reason}),le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateActionConfigs(Qt)),t===exports.WebsocketTypeEnum.CONSULT_CALL_IN&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_INCOMING,{agent_no:s.agent_no,agent_mane:s.agent_name,session_id:s.session_id}),Ve.sessionId=s.session_id,le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.CONSULT),le.updateDisplayText(exports.DisplayTextEnum.CONSULT_CALL_IN),le.updateActionConfigs(Rt),Ve.enableBrowserAlert&&Ps.show("📞 咨询来电",`坐席 [${s.agent_name}] 正在咨询...`,()=>{ae.emit(exports.EventName.NOTIFICATION_CLICK,{agent_mane:s.agent_name,agent_no:s.agent_no})},Ve.browserAlertTime)),t===exports.WebsocketTypeEnum.CONSULT_CALL_IN_SUCCESS&&(ae.emit(exports.CallSipCallEventEnum.CONSULT_CALL_IN_SUCCESS,{session_id:s.session_id}),le.updateConsultIsAnswer(!0),le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateActionConfigs(yt)),t===exports.WebsocketTypeEnum.CONSULT_RETURN_CALL_SUCCESS&&("success"===s.status?(le.updateConsultIsAnswer(!1),ae.emit(exports.CallSipCallEventEnum.CONSULT_RETURN_CALL_SUCCESS),le.updateDisplayText(exports.DisplayTextEnum.CALLING),ae.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP),le.updateActionConfigs(Qt)):ae.emit(exports.EventName.FAIL_NOTIFICATION,"媒体失败")),t===exports.WebsocketTypeEnum.MUTE&&(0===i?(le.updateIsMuted(!0),ae.emit(exports.CallSipCallEventEnum.MUTE_SUCCESS),le.updateDisplayText(exports.DisplayTextEnum.MUTING)):(ae.emit(exports.CallSipCallEventEnum.MUTE_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.UNMUTE&&(0===i?(le.updateIsMuted(!1),ae.emit(exports.CallSipCallEventEnum.UNMUTE_SUCCESS),le.updateDisplayText(exports.DisplayTextEnum.CALLING)):(ae.emit(exports.CallSipCallEventEnum.UNMUTE_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CALL_HOLD&&(0===i?(le.updateIsHold(!0),le.updateDisplayText(exports.DisplayTextEnum.HOLDING),ae.emit(exports.CallSipCallEventEnum.HOLD_SUCCESS)):(ae.emit(exports.CallSipCallEventEnum.HOLD_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CALL_UNHOLD&&(0===i?(le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateIsHold(!1),ae.emit(exports.CallSipCallEventEnum.UNHOLD_SUCCESS)):(ae.emit(exports.CallSipCallEventEnum.UNHOLD_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CONSULT_TRANSFER&&(0===i?ae.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_SUCCESS):(ae.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CONSULT_TRANSFER_FAILED&&ae.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_FAILED,s.status),t===exports.WebsocketTypeEnum.CONSULT_TRANSFER_OFF_HOOK&&(le.updateDirection(exports.DirectionEnum.INCOMING),le.updateDisplayText(exports.DisplayTextEnum.CALLING),ae.emit(exports.CallSipCallEventEnum.CONSULT_TRANSFER_OFF_HOOK),le.updateActionConfigs(Ut),le.updateIncomingIsAnswer(!0),le.updateConsultIsAnswer(!1)),t===exports.WebsocketTypeEnum.INCOMING_CALL){clearTimeout(Ve.autoStateTimer),Ve.sessionId=s.session_id;try{await this.getCustomerInfo(s.trace_id||s.customer_phone)}catch(A){console.error(A)}le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.INCOMING),this.inCallAutoAnswer(),le.updateDisplayText(exports.DisplayTextEnum.INCOMING_CALL),1===s.direction&&ae.emit(exports.CallSipCallEventEnum.INCOMING_CALL,{customer_phone:s.customer_phone,trace_id:s.trace_id,session_id:s.session_id}),3===s.direction&&(ae.emit(exports.CallSipCallEventEnum.PREDICT_INCOMING_CALL,{customer_phone:s.customer_phone,trace_id:s.trace_id,session_id:s.session_id}),this.sipClient?.answerCall()),le.updateActionConfigs(Rt),Ve.enableBrowserAlert&&Ps.show("📞 客户来电",`客户 [${s.customer_phone}] 正在呼入...`,()=>{ae.emit(exports.EventName.NOTIFICATION_CLICK,{customer_phone:s.customer_phone})},Ve.browserAlertTime)}if(t===exports.WebsocketTypeEnum.INCOMING_CALL_OFF_HOOK&&(le.updateIncomingIsAnswer(!0),ae.emit(exports.CallSipCallEventEnum.INCOMING_CALL_OFF_HOOK,{session_id:Ve.sessionId}),le.updateActionConfigs(Ut),le.updateDisplayText(exports.DisplayTextEnum.CALLING)),t===exports.WebsocketTypeEnum.INCOMING_CALL_END)if(le.updateDisplayText(""),1===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.INCOMING_CALL_END,{session_id:s.session_id}),le.updateActionConfigs(ft);else if(2===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)le.reset(),ae.emit(exports.CallSipCallEventEnum.OUR_SIDE_CONSULT_HANGUP,{session_id:s.session_id}),this.putAgentState(!0),le.updateActionConfigs(ft);else if(2===s.device_type&&s.agent_no!==Ve.agentInfo.agent_no)le.updateDisplayText(exports.DisplayTextEnum.CALLING),ae.emit(exports.CallSipCallEventEnum.OTHER_SIDE_CONSULT_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(Qt);else if(3===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.THREE_WAY_OUR_SIDE_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft);else if(4===s.device_type&&s.agent_no===Ve.agentInfo.agent_no)this.putAgentState(!0),le.reset(),ae.emit(exports.CallSipCallEventEnum.TRANSFER_END,{session_id:s.session_id}),le.updateActionConfigs(ft);else if(4===s.device_type&&s.agent_no!==Ve.agentInfo.agent_no){ae.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ae.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const A=le.get("direction");A===exports.DirectionEnum.OUTGOING?le.updateActionConfigs(Qt):A===exports.DirectionEnum.INCOMING&&le.updateActionConfigs(Ut)}else 5===s.device_type&&s.agent_no===Ve.agentInfo.agent_no&&(this.putAgentState(!0,5),Ve.monitoredAgentNo="",Ve.earSpeakAgent="",le.reset(),ae.emit(exports.CallSipCallEventEnum.LISTEN_HANGUP,{session_id:s.session_id}),le.updateActionConfigs(ft));if(t===exports.WebsocketTypeEnum.SATISFACTION_EVALUATION&&(0===i?ae.emit(exports.CallSipCallEventEnum.SATISFACTION_EVALUATION_SUCCESS):(ae.emit(exports.CallSipCallEventEnum.SATISFACTION_EVALUATION_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n))),t===exports.WebsocketTypeEnum.CONSULT_THREE_WAY&&(0!==i?(ae.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,n),ae.emit(exports.EventName.FAIL_NOTIFICATION,n)):0===i&&le.updateIsMeeting(!0)),t===exports.WebsocketTypeEnum.CONSULT_THREE_WAY_RESULT&&("success"===s.status?(le.updateDirection(exports.DirectionEnum.MEETING),le.updateDisplayText(exports.DisplayTextEnum.MEETING),le.updateActionConfigs(Dt),ae.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_SUCCESS)):(ae.emit(exports.CallSipCallEventEnum.CONSULT_THREE_WAY_FAILED,{conf_name:s.conf_name}),le.updateIsMeeting(!1))),t===exports.WebsocketTypeEnum.TRANSFER_INCOMING_CALL&&(clearTimeout(Ve.autoStateTimer),s.agent_no===Ve.agentInfo.agent_no?(le.updateDisplayText(exports.DisplayTextEnum.TRANSFERRING),ae.emit(exports.CallSipCallEventEnum.TRANSFER_PROGRESS),le.updateActionConfigs([]),le.updateTransferIsAnswer(!0)):(Ve.sessionId=s.session_id,ae.emit(exports.CallSipCallEventEnum.TRANSFER_INCOMING_CALL,{agent_no:s.agent_no,agent_name:s.agent_name,session_id:s.session_id}),le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.TRANSFER),le.updateDisplayText(exports.DisplayTextEnum.TRANSFER_INCOMING_CALL),le.updateActionConfigs(Rt),Ve.enableBrowserAlert&&Ps.show("📞 转接来电",`坐席 [${s.agent_no}] 正在转接...`,()=>{ae.emit(exports.EventName.NOTIFICATION_CLICK,{agent_no:s.agent_no})},Ve.browserAlertTime))),t===exports.WebsocketTypeEnum.TRANSFER_OFF_HOOK&&(ae.emit(exports.CallSipCallEventEnum.TRANSFER_OFF_HOOK,{session_id:Ve.sessionId}),le.updateTransferIsAnswer(!1),le.updateDisplayText(exports.DisplayTextEnum.CALLING),le.updateActionConfigs(Ut)),t===exports.WebsocketTypeEnum.TRANSFER_FAILED&&"failed"===s.status){ae.emit(exports.CallSipCallEventEnum.TRANSFER_FAILED,"未知原因"),ae.emit(exports.EventName.FAIL_NOTIFICATION,"转接失败");const A=le.get("direction");A===exports.DirectionEnum.OUTGOING?le.updateActionConfigs(Qt):A===exports.DirectionEnum.INCOMING&&le.updateActionConfigs(Ut)}t===exports.WebsocketTypeEnum.KICK_OFFLINE&&ae.emit(exports.EventName.KICK_OFF),t===exports.WebsocketTypeEnum.CONTINUOUS_NOT_ANSWER&&(ae.emit(exports.EventName.FAIL_NOTIFICATION,`已连续 ${s.miss_count} 次未接, 设置忙碌`),this.stateBusyChange()),t===exports.WebsocketTypeEnum.SIGN_OUT&&ae.emit(exports.EventName.SIGN_OUT),t===exports.WebsocketTypeEnum.SIGN_IN_SWITCH_DEVICE&&ae.emit(exports.EventName.SIGN_IN_SWITCH_DEVICE,s),t===exports.WebsocketTypeEnum.LISTEN_INCOMING_CALL&&(clearTimeout(Ve.autoStateTimer),Ve.sessionId=s.session_id,le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.INCOMING),this.inCallAutoAnswer(),le.updateDisplayText(exports.DisplayTextEnum.LISTENING),le.updateActionConfigs(Rt),ae.emit(exports.CallSipCallEventEnum.LISTEN_INCOMING_CALL,{session_id:s.session_id}),Ve.enableBrowserAlert&&Ps.show("📞 监听来电","正在来电...",()=>{ae.emit(exports.EventName.NOTIFICATION_CLICK,{customer_phone:s.customer_phone})},Ve.browserAlertTime)),t===exports.WebsocketTypeEnum.LISTEN_INCOMING_CALL_OFF_HOOK&&(Ve.monitoredAgentNo=s.monitored_agent_no,Ve.earSpeakAgent="",le.updateIncomingIsAnswer(!0),ae.emit(exports.CallSipCallEventEnum.LISTEN_INCOMING_CALL_OFF_HOOK,{session_id:Ve.sessionId,monitored_agent_no:s.monitored_agent_no}),le.updateActionConfigs(kt),le.updateDisplayText(exports.DisplayTextEnum.CALLING)),t===exports.WebsocketTypeEnum.LISTEN_CALL_FAILED&&"failed"===s.status&&(ae.emit(exports.CallSipCallEventEnum.LISTEN_CALL_FAILED),Ve.monitoredAgentNo=""),t===exports.WebsocketTypeEnum.EAR_SPEECH&&("success"===s.status?(s.monitored_agent_no===Ve.agentInfo.agent_no&&(le.updateActionConfigs(Gt),ae.emit(exports.CallSipCallEventEnum.EAR_SPEECH_BE_SUCCESS)),s.monitor_agent_no===Ve.agentInfo.agent_no&&(le.updateActionConfigs(Ft),ae.emit(exports.CallSipCallEventEnum.EAR_SPEECH_SUCCESS,{monitored_agent_no:s.monitored_agent_no,monitor_agent_no:s.monitor_agent_no}),Ve.earSpeakAgent=s.monitored_agent_no)):ae.emit(exports.CallSipCallEventEnum.EAR_SPEECH_FAILED)),t===exports.WebsocketTypeEnum.STOP_EAR_SPEECH&&("success"===s.status?(s.monitored_agent_no===Ve.agentInfo.agent_no&&le.updateActionConfigs(Ut),s.monitor_agent_no===Ve.agentInfo.agent_no&&le.updateActionConfigs(kt),Ve.earSpeakAgent="",ae.emit(exports.CallSipCallEventEnum.STOP_EAR_SPEECH_SUCCESS)):ae.emit(exports.CallSipCallEventEnum.STOP_EAR_SPEECH_FAILED)),t===exports.WebsocketTypeEnum.CALL_FORCE_INSERT&&("success"===s.status?(s.monitored_agent_no===Ve.agentInfo.agent_no&&(le.updateActionConfigs(xt),ae.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS,{monitored_agent_no:s.monitored_agent_no,monitor_agent_no:s.monitor_agent_no})),s.monitor_agent_no===Ve.agentInfo.agent_no&&(le.updateActionConfigs(Yt),ae.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_SUCCESS_LISTENER,{monitored_agent_no:s.monitored_agent_no,monitor_agent_no:s.monitor_agent_no}))):ae.emit(exports.CallSipCallEventEnum.CALL_FORCE_INSERT_FAILED))},this.ws.onclose=()=>{this.stopHeartbeat(),this.manualClose||setTimeout(()=>this.initWebSocket(),this.reconnectDelay)},this.ws.onerror=()=>{this.ws?.close()}}startHeartbeat(){const A=new Blob(["\n let timer;\n self.onmessage = function (e) {\n if (e.data === 'start') {\n timer = setInterval(() => {\n self.postMessage('heartbeat');\n }, 5000);\n } else if (e.data === 'stop') {\n clearInterval(timer);\n }\n };\n "],{type:"application/javascript"}),e=URL.createObjectURL(A);this.heartbeatWorker=new Worker(e),this.heartbeatWorker.onmessage=()=>{const A=(new Date).getTime();this.sendMessage({type:0,msg_id:A}),this.pendingMessages.set(A,performance.now())},this.heartbeatWorker.postMessage("start")}stopHeartbeat(){this.heartbeatWorker&&(this.heartbeatWorker.postMessage("stop"),this.heartbeatWorker.terminate(),this.heartbeatWorker=null)}sendMessage(A){this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(A)),0!==A.type&&Xs("%cWebSocket 发送消息:","color: green; font-weight: bold;",A)):console.warn("WebSocket 未连接,消息未发送")}close(){this.manualClose=!0,this.stopHeartbeat(),this.ws?.close()}reconnect(){this.initWebSocket()}static __internalClose(){_s&&(_s.close(),_s=null)}static __internalSend(A){if(!_s)throw new Error("WebSocket 尚未初始化");_s.sendMessage(A)}}class Ai{constructor(A){this.sipClient=null,this.sipClient=A}roleMute(){const A=le.get("isCalling"),e=Ve.sessionId;if(!A)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}))}holdCall(){this.roleMute();const A=le.get("isHold"),{sessionId:e}=Ve;if(!e)return;if(!le.get("actionConfigs").includes("hold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿保持"}));if(A)throw new Error(JSON.stringify({code:1,msg:"当前已处于保持状态"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CALL_HOLD,data:{session_id:e}})}unholdCall(){this.roleMute();const{isHold:A}=le.getState(),{sessionId:e}=Ve;if(!le.get("actionConfigs").includes("unhold"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取消保持"}));if(e){if(!A)throw new Error(JSON.stringify({code:1,msg:"当前未处于保持状态"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CALL_UNHOLD,data:{session_id:e}})}}sendDTMF(A){if(1!==le.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));if(!le.get("actionConfigs").includes("dtmf"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿发送按键"}));const{isCalling:e}=le.getState();if(!e)throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));this.sipClient.sendDTMF(A)}cancelCall(){if(!le.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const A=Ve.sessionId;ae.emit(exports.CallSipCallEventEnum.REJECT,{session_id:A}),$s.__internalSend({type:exports.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:A}})}async consultCall(A){this.roleMute();const{isCalling:e,outCallIsAnswer:t,consultIsAnswer:s,incomingIsAnswer:i}=le.getState(),n=Ve.sessionId;if(!le.get("actionConfigs").includes("consult"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询"}));if(s)throw new Error(JSON.stringify({code:1,msg:"当前正在咨询"}));if(!(e||t||i))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));if(!n)throw new Error(JSON.stringify({code:1,msg:"sessionId不存在"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_REQUEST,data:{session_id:n,consultation_agent_no:A}})}async answerCall(){if(1!==le.get("answerDevice"))throw new Error(JSON.stringify({code:1,msg:"当前设备不支持此功能"}));await this.sipClient.answerCall()}makeCall(A){const e={};Rs(A)?e.customer_phone=A:e.trace_id=A;const t=le.get("isCalling"),s=le.get("selectOutNumber")||"";if(t)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof A||""===A.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.OUTGOING),$s.__internalSend({type:exports.WebsocketTypeEnum.OUT_CALL,data:{...e,caller:s}})}previewCall(A,e){const t={};Rs(A)?t.customer_phone=A:t.trace_id=A;const s=le.get("isCalling"),i=le.get("selectOutNumber")||"";if(s)throw new Error(JSON.stringify({code:1,msg:"正在呼叫中,请勿重复点击"}));if("string"!=typeof A||""===A.trim())throw new Error(JSON.stringify({code:1,msg:"外呼号码非法"}));le.updateIsCalling(!0),le.updateDirection(exports.DirectionEnum.OUTGOING),$s.__internalSend({type:exports.WebsocketTypeEnum.PREVIEW_OUT_CALL,data:{...t,caller:i,preview_task_id:e}})}async hangup(){if(!le.get("isCalling"))throw new Error(JSON.stringify({code:1,msg:"当前没有通话"}));const A=Ve.sessionId;$s.__internalSend({type:exports.WebsocketTypeEnum.AGENT_HANGUP,data:{session_id:A}})}mute(){this.roleMute();const A=le.get("actionConfigs"),e=le.get("isMuted"),t=Ve.sessionId;if(e)throw new Error(JSON.stringify({code:1,msg:"当前未处于静音状态"}));if(!A.includes("mute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));$s.__internalSend({type:exports.WebsocketTypeEnum.MUTE,data:{session_id:t}})}unmute(){this.roleMute();const A=le.get("actionConfigs"),e=le.get("isMuted"),t=Ve.sessionId;if(!e)throw new Error(JSON.stringify({code:1,msg:"当前未处于未静音状态"}));if(!A.includes("unmute"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用静音"}));$s.__internalSend({type:exports.WebsocketTypeEnum.UNMUTE,data:{session_id:t}})}consultTransfer(){this.roleMute();const A=le.get("consultIsAnswer"),e=Ve.sessionId;if(!le.get("actionConfigs").includes("consult_transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用咨询转移"}));if(!A)throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_TRANSFER,data:{session_id:e}})}satisfactionEvaluation(){this.roleMute();const A=Ve.sessionId;if(!le.get("actionConfigs").includes("satisfaction"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用满意度评价"}));$s.__internalSend({type:exports.WebsocketTypeEnum.SATISFACTION_EVALUATION,data:{session_id:A}})}startConference(){this.roleMute();if(!le.get("actionConfigs").includes("conference"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿调用三方会议"}));const A=Ve.sessionId;if(!le.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_THREE_WAY,data:{session_id:A}})}consultRetrieve(){this.roleMute();if(!le.get("actionConfigs").includes("consult_retrieve"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿取回通话"}));const A=Ve.sessionId;if(!le.get("consultIsAnswer"))throw new Error(JSON.stringify({code:1,msg:"当前未处于咨询中"}));$s.__internalSend({type:exports.WebsocketTypeEnum.CONSULT_RETURN_CALL,data:{session_id:A}})}async transferAgent(A){this.roleMute();if(!le.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));const{transferIsAnswer:e}=le.getState(),t=Ve.sessionId;if(e)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));$s.__internalSend({type:exports.WebsocketTypeEnum.TRANSFER,data:{session_id:t,transfer_type:0,transfer_dest:A}})}async transferOutline(A){this.roleMute();if(!le.get("actionConfigs").includes("transfer"))throw new Error(JSON.stringify({code:1,msg:"当前状态请勿转接"}));if(!A)throw new Error(JSON.stringify({code:1,msg:"号码不能为空"}));if(!/^\d+$/.test(A))throw new Error(JSON.stringify({code:1,msg:"号码格式错误"}));const{transferIsAnswer:e}=le.getState(),t=Ve.sessionId;if(e)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));if(e)throw new Error(JSON.stringify({code:1,msg:"当前正在转接"}));$s.__internalSend({type:exports.WebsocketTypeEnum.TRANSFER,data:{session_id:t,transfer_type:2,transfer_dest:A}})}}var ei;class ti{static{this._instance=null}#A=null;#e=new Ks;#t;#s=null;#i=!1;#n;#o;#r=!1;static{this._timer=null}#a=null;constructor(){if(!ei._creatingInstance)throw new Error("请使用 YSYTAgentSdk.getInstance() 获取实例");clearInterval(this.#s),this.#s=setInterval(async()=>{const A=await this.#V();he.updateRttObject(A)},2e3),Ps.requestMediaPermissions(),this.#n=le.subscribeKey("answerDevice",async A=>{1===A?(await this.initWebRtc(),Ve.stateObject.state===exports.AgentStatus.UNREGISTERED&&await this.#e._changeState({data:{...Ve.stateBeforeChange,state_name:Ve.stateBeforeChange.state===exports.AgentStatus.IDLE?"空闲":"忙碌"}})):await this.destroyRtc()}),this.#o=le.subscribeKey("isNextState",async A=>{if(A){await this.#e._agentLogin(xs);1===le.get("answerDevice")&&await this.#A.reconnect();let A="";const e=new URL(Gs).host;A=Gs.includes("https")?`wss://${e}`:`ws://${e}`;const{agent_no:t}=Ve.agentInfo;$s.getInstance({url:`${A}/ccs-ws/api/v1/ws/call/${t}?Authorization=`,sipClient:this.#A}),Ve.stateObject.state===exports.AgentStatus.OFFLINE&&setTimeout(()=>{this.#e._changeState({data:{...this.#a,state_name:this.#a.state===exports.AgentStatus.BUSY&&"整理"===this.#a.state_name?"忙碌":this.#a.state_name},success:()=>{le.updateDisplayText(""),ae.emit(exports.CallSipCallEventEnum.AGENT_STATE,this.#a)}})},10)}else this.#a=Ve.stateObject,$s.__internalClose(),le.updateDisplayText("离线")}),this.on(exports.EventName.KICK_OFF,()=>{this.destroy()}),window.addEventListener("online",this.#c),window.addEventListener("offline",this.#l)}#c=()=>{le.updateIsNextState(!0)};#l=()=>{le.updateIsNextState(!1)};async#h(){const A=le.get("isNextState");try{await Ns(),A||le.updateIsNextState(!0)}catch(e){A&&le.updateIsNextState(!1)}}#g(){ei._timer||(ei._timer=setInterval(()=>this.#h(),3e3))}static get instance(){return this._instance}static async destroyInstance(){this._instance&&(await this._instance.destroy(),this._instance=null)}static getInstance(A){if(!this._instance){if(!A)throw new Error("首次调用必须传入配置参数");const{url:e,appKey:t,appSecret:s,agentNo:i}=A;Gs=e||"https://aicc-api.yescloudy.com",Fs=t,Ys=s,xs=i,ei._creatingInstance=!0,this._instance=new ei,delete ei._creatingInstance,window.addEventListener("beforeunload",()=>{this._instance?.destroy()})}return this._instance}getInit(){return this.#r}async initWebRtc(){if(this.#A)return;const A=Ve.agentInfo.sip_account_list.find(A=>1===A.device_type);if(!A)throw new Error(JSON.stringify({code:1,msg:"未找到 sip_account_list"}));{const e=A.sip_register_addr;this.#A=new ge({server:e.split(":")[0],user:A.sip_account,password:A.sip_password,webSocket:`wss://${e}`,callTimeout:3e4},this.#q),await this.#A.start()}}async init({actionNodeParams:A,enableBrowserAlert:e,logBuiltinEnabled:t,browserAlertTime:s,initialState:i,initDevice:n}){try{const{viewHtmlElement:o,rttHTML:r}=A||{};Ve.logBuiltinEnabled=t||!1,Ve.browserAlertTime=s||5e3,await this.#e._agentLogin(xs);const{agent_no:a,current_answer_device:V,current_state:c,out_display_number:l,out_display_select_switch:h}=Ve.agentInfo;(i||c)===exports.AgentStatus.IDLE?(le.updateActionConfigs(ft),Ve.stateObject={state:i||c,state_name:"空闲"},Ve.stateBeforeChange=Ve.stateObject):(i||c)===exports.AgentStatus.BUSY&&(le.updateActionConfigs(Bt),Ve.stateObject={state:c,state_name:"忙碌"},Ve.stateBeforeChange=Ve.stateObject),1===h?le.updateSelectOutNumber(l):le.updateSelectOutNumber("");let g="";const q=new URL(Gs).host;g=Gs.includes("https")?`wss://${q}`:`ws://${q}`,le.updateAnswerDevice(n||V),1===(n||V)&&await this.initWebRtc(),setTimeout(()=>{this.#e._changeState({data:Ve.stateObject}),this.#e.changeDevice({data:{device:n||V}})},500),$s.getInstance({url:`${g}/ccs-ws/api/v1/ws/call/${a}?Authorization=`,sipClient:this.#A}),this.#t=new Ai(this.#A),A&&o&&(this.#i=!0,new Ws({container:o,rttHTML:r,statusParams:{state:exports.AgentStatus.IDLE,statusName:"空闲"}},this,this.#t)),Ve.enableBrowserAlert=e,e&&Ps.requestPermission(),ae.emit(exports.EventName.AGENT_INIT_STATUS,!0),this.#r=!0,clearInterval(ei._timer),ei._timer=null,this.#g()}catch(A){this.#i&&Hs("初始化失败"),ae.emit(exports.EventName.AGENT_INIT_STATUS,!1),this.#r=!1}}#q=A=>{const{type:e,data:t}=A;ae.emit(e,t)};on(A,e){return ae.on(A,e),this}off(A,e){ae.off(A,e)}offAll(){ae.clearAllListeners()}async destroyRtc(){await(this.#A?.destroy()),this.#A=null}async destroy(){ei._instance&&(await this.destroyRtc(),clearInterval(this.#s),$s.__internalClose(),ae.emit(exports.EventName.DESTROY),this.offAll(),this.#n?.(),this.#o?.(),this.#i=!1,ei._instance=null,le.reset(),le.updateSelectOutNumber(""),clearInterval(ei._timer),ei._timer=null)}async#V(){return this.#A?this.#A.getNetworkStats():{}}get call_api(){const A=A=>(...e)=>{if(!this.#i)return A.apply(this,e);console.warn("当前未使用个人开发模式")};return{answerCall:A(()=>this.#t.answerCall()),makeCall:A=>this.#t.makeCall(A),previewMakeCall:(A,e)=>this.#t.previewCall(A,e),cancelCall:A(()=>this.#t.cancelCall()),hangup:A(()=>this.#t.hangup()),sendDTMF:A(A=>this.#t.sendDTMF(A)),holdCall:A(()=>this.#t.holdCall()),unholdCall:A(()=>this.#t.unholdCall()),consultCall:A(async A=>{try{await this.#t.consultCall(A)}catch(A){throw console.warn(A),A}}),consultRetrieve:A(()=>this.#t.consultRetrieve()),consultTransfer:A(()=>this.#t.consultTransfer()),mute:A(()=>this.#t.mute()),unmute:A(()=>this.#t.unmute()),satisfactionEvaluation:A(()=>this.#t.satisfactionEvaluation()),startConference:A(()=>this.#t.startConference()),transferAgent:A(A=>this.#t.transferAgent(A)),transferOutline:A(A=>this.#t.transferOutline(A)),earSpeakStart:A(A=>this.#e.earCall(A)),earSpeakStop:A(A=>this.#e.stopEarCall(A)),forceInsert:A(A=>this.#e.forceInsert(A)),forceDisconnect:A(A=>this.#e.forceDisconnect(A))}}get agent_api(){const A=A=>(...e)=>{if(!this.#i)return A.apply(this,e);console.warn("当前未使用个人开发模式")};return{changeDevice:A(A=>this.#e.changeDevice(A)),changeState:A(A=>this.#e.changeState(A)),getIdleAgentList:A(A=>this.#e.getIdleAgentList(A)),getAgentState:A(A=>this.#e.getAgentState(A)),setAgentExplicit:A(A=>this.#e.setAgentExplicit(A)),checkAgentLogin:A=>this.#e.checkAgentLogin(A),getCallRecord:A=>this.#e.getCallRecord(A),agentLogout:async(A,e)=>{try{await this.#e.logout(A),await this.destroy(),e?.({code:0,msg:""})}catch(A){}},listenAgentCall:A=>this.#e.listenCall(A)}}getAgentData(){const{agent_no:A,agent_name:e,answer_devices:t,out_display_data:s,out_display_select_switch:i,current_state:n}=Ve.agentInfo,{stateObject:o}=Ve,r={1:"软电话",2:"手机模式",3:"SIP话机"};return{agent_no:A,agent_name:e,init_state:n,default_device:le.get("answerDevice"),out_display_data:s,out_display_select_switch:i,answer_devices:(t||"").split(",").map(A=>({value:Number(A),label:r[Number(A)]})),stateObject:o}}async getRealTimeCustomerInfo(){return le.get("customerObject")}setBrowserAlert(A){if("boolean"!=typeof A)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));Ve.logBuiltinEnabled=A||!1}setBrowserAlertTime(A){if("number"!=typeof A)throw new Error(JSON.stringify({code:1,msg:"参数类型错误"}));Ve.browserAlertTime=A||3e3}}ei=ti,exports.default=ti;
|