opensips-js 0.1.46 → 0.1.47
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/index.d.ts +259 -12
- package/dist/opensips-js.cjs.js +101 -101
- package/dist/opensips-js.es.js +8645 -8043
- package/dist/opensips-js.iife.js +101 -101
- package/dist/opensips-js.umd.js +101 -101
- package/package.json +1 -1
- package/src/types/listeners.d.ts +50 -0
package/dist/opensips-js.cjs.js
CHANGED
|
@@ -1,159 +1,159 @@
|
|
|
1
|
-
"use strict";var jd=Object.defineProperty;var qd=(c,t,n)=>t in c?jd(c,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):c[t]=n;var Kt=(c,t,n)=>(qd(c,typeof t!="symbol"?t+"":t,n),n);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var Bd=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Xe(c){return c&&c.__esModule&&Object.prototype.hasOwnProperty.call(c,"default")?c.default:c}const Gd="jssip",Wd="JsSIP",Kd="the Javascript SIP library",Yd="3.10.0",Jd="https://jssip.net",zd=["José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)","Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)"],Xd="lib/JsSIP.d.ts",Qd="lib-es5/JsSIP.js",Zd=["sip","websocket","webrtc","node","browser","library"],eh="MIT",th={type:"git",url:"https://github.com/versatica/JsSIP.git"},sh={url:"https://github.com/versatica/JsSIP/issues"},nh={"@types/events":"^3.0.0","@types/debug":"^4.1.7",debug:"^4.3.1",events:"^3.3.0","sdp-transform":"^2.14.1"},rh={"@babel/core":"^7.19.6","@babel/preset-env":"^7.19.4","ansi-colors":"^3.2.4",browserify:"^16.5.1",eslint:"^5.16.0","fancy-log":"^1.3.3",gulp:"^4.0.2","gulp-babel":"^8.0.0","gulp-eslint":"^5.0.0","gulp-expect-file":"^1.0.2","gulp-header":"^2.0.9","gulp-nodeunit-runner":"^0.2.2","gulp-plumber":"^1.2.1","gulp-rename":"^1.4.0","gulp-uglify-es":"^1.0.4",pegjs:"^0.7.0","vinyl-buffer":"^1.0.1","vinyl-source-stream":"^2.0.0"},ih={lint:"node npm-scripts.js lint",test:"node npm-scripts.js test",prepublish:"node npm-scripts.js prepublish",release:"node npm-scripts.js release"},Fo={name:Gd,title:Wd,description:Kd,version:Yd,homepage:Jd,contributors:zd,types:Xd,main:Qd,keywords:Zd,license:eh,repository:th,bugs:sh,dependencies:nh,devDependencies:rh,scripts:ih};var Ku=Fo,lt={USER_AGENT:"".concat(Ku.title," ").concat(Ku.version),SIP:"sip",SIPS:"sips",causes:{CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:"Request Timeout",SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:"Rejected",REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:"Terminated",WEBRTC_ERROR:"WebRTC Error",CANCELED:"Canceled",NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:"ACK",BYE:"BYE",CANCEL:"CANCEL",INFO:"INFO",INVITE:"INVITE",MESSAGE:"MESSAGE",NOTIFY:"NOTIFY",OPTIONS:"OPTIONS",REGISTER:"REGISTER",REFER:"REFER",UPDATE:"UPDATE",SUBSCRIBE:"SUBSCRIBE",DTMF_TRANSPORT:{INFO:"INFO",RFC2833:"RFC2833"},REASON_PHRASE:{100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",424:"Bad Location Information",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:"JsSIP Internal 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"},ALLOWED_METHODS:"INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY",ACCEPTED_BODY_TYPES:"application/sdp, application/dtmf-relay",MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2};function mo(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?mo=function(n){return typeof n}:mo=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},mo(c)}function Vo(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function jo(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&Qi(c,t)}function qo(c){var t=Gf();return function(){var l=Zi(c),a;if(t){var s=Zi(this).constructor;a=Reflect.construct(l,arguments,s)}else a=l.apply(this,arguments);return lh(this,a)}}function lh(c,t){return t&&(mo(t)==="object"||typeof t=="function")?t:oh(c)}function oh(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function pr(c){var t=typeof Map=="function"?new Map:void 0;return pr=function(l){if(l===null||!ah(l))return l;if(typeof l!="function")throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(l))return t.get(l);t.set(l,a)}function a(){return go(l,arguments,Zi(this).constructor)}return a.prototype=Object.create(l.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),Qi(a,l)},pr(c)}function go(c,t,n){return Gf()?go=Reflect.construct:go=function(a,s,r){var h=[null];h.push.apply(h,s);var d=Function.bind.apply(a,h),_=new d;return r&&Qi(_,r.prototype),_},go.apply(null,arguments)}function Gf(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function ah(c){return Function.toString.call(c).indexOf("[native code]")!==-1}function Qi(c,t){return Qi=Object.setPrototypeOf||function(l,a){return l.__proto__=a,l},Qi(c,t)}function Zi(c){return Zi=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Zi(c)}var uh=function(c){jo(n,c);var t=qo(n);function n(l,a){var s;return Vo(this,n),s=t.call(this),s.code=1,s.name="CONFIGURATION_ERROR",s.parameter=l,s.value=a,s.message=s.value?"Invalid value ".concat(JSON.stringify(s.value),' for parameter "').concat(s.parameter,'"'):"Missing parameter: ".concat(s.parameter),s}return n}(pr(Error)),ch=function(c){jo(n,c);var t=qo(n);function n(l){var a;return Vo(this,n),a=t.call(this),a.code=2,a.name="INVALID_STATE_ERROR",a.status=l,a.message="Invalid status: ".concat(l),a}return n}(pr(Error)),fh=function(c){jo(n,c);var t=qo(n);function n(l){var a;return Vo(this,n),a=t.call(this),a.code=3,a.name="NOT_SUPPORTED_ERROR",a.message=l,a}return n}(pr(Error)),dh=function(c){jo(n,c);var t=qo(n);function n(l){var a;return Vo(this,n),a=t.call(this),a.code=4,a.name="NOT_READY_ERROR",a.message=l,a}return n}(pr(Error)),Ws={ConfigurationError:uh,InvalidStateError:ch,NotSupportedError:fh,NotReadyError:dh},et={},fa,Yu;function Nu(){if(Yu)return fa;Yu=1;function c(s,r){if(!(s instanceof r))throw new TypeError("Cannot call a class as a function")}function t(s,r){for(var h=0;h<r.length;h++){var d=r[h];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(s,d.key,d)}}function n(s,r,h){return r&&t(s.prototype,r),h&&t(s,h),s}var l=Ks(),a=as();return fa=function(){n(s,null,[{key:"parse",value:function(h){if(h=a.parse(h,"Name_Addr_Header"),h!==-1)return h}}]);function s(r,h,d){if(c(this,s),!r||!(r instanceof l))throw new TypeError('missing or invalid "uri" parameter');this._uri=r,this._parameters={},this.display_name=h;for(var _ in d)Object.prototype.hasOwnProperty.call(d,_)&&this.setParam(_,d[_])}return n(s,[{key:"setParam",value:function(h,d){h&&(this._parameters[h.toLowerCase()]=typeof d>"u"||d===null?null:d.toString())}},{key:"getParam",value:function(h){if(h)return this._parameters[h.toLowerCase()]}},{key:"hasParam",value:function(h){if(h)return this._parameters.hasOwnProperty(h.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(h){if(h=h.toLowerCase(),this._parameters.hasOwnProperty(h)){var d=this._parameters[h];return delete this._parameters[h],d}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"clone",value:function(){return new s(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}},{key:"_quote",value:function(h){return h.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}},{key:"toString",value:function(){var h=this._display_name?'"'.concat(this._quote(this._display_name),'" '):"";h+="<".concat(this._uri.toString(),">");for(var d in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,d)&&(h+=";".concat(d),this._parameters[d]!==null&&(h+="=".concat(this._parameters[d])));return h}},{key:"uri",get:function(){return this._uri}},{key:"display_name",get:function(){return this._display_name},set:function(h){this._display_name=h===0?"0":h}}]),s}(),fa}var da,Ju;function as(){return Ju||(Ju=1,da=function(){function c(n){return'"'+n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+'"'}var t={parse:function(l,a){var s={CRLF:g,DIGIT:T,ALPHA:S,HEXDIG:E,WSP:C,OCTET:A,DQUOTE:R,SP:V,HTAB:w,alphanum:le,reserved:x,unreserved:H,mark:ve,escaped:pe,LWS:P,SWS:N,HCOLON:q,TEXT_UTF8_TRIM:j,TEXT_UTF8char:Y,UTF8_NONASCII:F,UTF8_CONT:X,LHEX:U,token:k,token_nodot:B,separators:He,word:Q,STAR:W,SLASH:G,EQUAL:re,LPAREN:_e,RPAREN:Ie,RAQUOT:ke,LAQUOT:Ae,COMMA:oe,SEMI:ye,COLON:nt,LDQUOT:ot,RDQUOT:Ee,comment:Ce,ctext:be,quoted_string:Oe,quoted_string_clean:ge,qdtext:ue,quoted_pair:me,SIP_URI_noparams:we,SIP_URI:Ne,uri_scheme:Ze,uri_scheme_sips:Le,uri_scheme_sip:Lt,userinfo:ht,user:bn,user_unreserved:wn,password:Ys,hostport:es,host:us,hostname:Js,domainlabel:On,toplabel:Dn,IPv6reference:zs,IPv6address:Te,h16:ae,ls32:at,IPv4address:Wt,dec_octet:As,port:vr,uri_parameters:Nn,uri_parameter:xn,transport_param:Sr,user_param:Er,method_param:yr,ttl_param:Cr,maddr_param:Ar,lr_param:Rr,other_param:Ir,pname:br,pvalue:Rs,paramchar:Is,param_unreserved:wr,headers:Xs,header:Qs,hname:Or,hvalue:bs,hnv_unreserved:Zs,Request_Response:ml,Request_Line:Dr,Request_URI:Un,absoluteURI:kn,hier_part:Nr,net_path:en,abs_path:tn,opaque_part:ws,uric:Os,uric_no_slash:xr,path_segments:sn,segment:Ds,param:cs,pchar:Ns,scheme:Ur,authority:kr,srvr:Pr,reg_name:Mr,query:Pn,SIP_Version:Mn,INVITEm:Lr,ACKm:$r,OPTIONSm:Hr,BYEm:Fr,CANCELm:Vr,REGISTERm:jr,SUBSCRIBEm:qr,NOTIFYm:Br,REFERm:nn,Method:rn,Status_Line:Gr,Status_Code:Wr,extension_code:Kr,Reason_Phrase:gl,Allow_Events:Jo,Call_ID:zo,Contact:Ln,contact_param:$t,name_addr:Ht,display_name:xs,contact_params:$n,c_p_q:Yr,c_p_expires:ts,delta_seconds:ss,qvalue:We,generic_param:Ke,gen_value:Tl,Content_Disposition:vl,disp_type:Hn,disp_param:Fn,handling_param:Sl,Content_Encoding:Xo,Content_Length:Qo,Content_Type:El,media_type:Jr,m_type:zr,discrete_type:Xr,composite_type:ln,extension_token:on,x_token:Qr,m_subtype:Vn,m_parameter:jn,m_value:yl,CSeq:Cl,CSeq_value:Al,Expires:Zo,Event:an,event_type:un,From:Zr,from_param:cn,tag_param:ei,Max_Forwards:ea,Min_Expires:ta,Name_Addr_Header:sa,Proxy_Authenticate:ti,challenge:qn,other_challenge:Us,auth_param:ns,digest_cln:fn,realm:si,realm_value:ni,domain:dn,URI:hn,nonce:ri,nonce_value:ii,opaque:li,stale:oi,algorithm:ai,qop_options:_n,qop_value:Bn,Proxy_Require:na,Record_Route:Gn,rec_route:Wn,Reason:ui,reason_param:Kn,reason_cause:Rl,Require:ra,Route:Yn,route_param:Jn,Subscription_State:Il,substate_value:zn,subexp_params:Xn,event_reason_value:bl,Subject:ia,Supported:la,To:ci,to_param:fi,Via:Qn,via_param:ks,via_params:Zn,via_ttl:di,via_maddr:hi,via_received:_i,via_branch:pi,response_port:mi,rport:gi,sent_protocol:Ti,protocol_name:vi,transport:Si,sent_by:Ei,via_host:yi,via_port:er,ttl:Ci,WWW_Authenticate:oa,Session_Expires:wl,s_e_expires:tr,s_e_params:sr,s_e_refresher:Ol,extension_header:Dl,header_value:Nl,message_body:aa,uuid_URI:xl,uuid:Ft,hex4:Vt,hex8:Ai,hex12:Ul,Refer_To:ua,Replaces:kl,call_id:nr,replaces_param:rr,to_tag:Ri,from_tag:Ii,early_flag:Pl};if(a!==void 0){if(s[a]===void 0)throw new Error("Invalid rule name: "+c(a)+".")}else a="CRLF";var r=0,h=0,d=[];function _(e){r<h||(r>h&&(h=r,d=[]),d.push(e))}function g(){var e;return l.substr(r,2)===`\r
|
|
1
|
+
"use strict";var Jd=Object.defineProperty;var zd=(c,t,s)=>t in c?Jd(c,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):c[t]=s;var Yt=(c,t,s)=>(zd(c,typeof t!="symbol"?t+"":t,s),s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var Qd=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Xe(c){return c&&c.__esModule&&Object.prototype.hasOwnProperty.call(c,"default")?c.default:c}const Xd="jssip",Zd="JsSIP",eh="the Javascript SIP library",th="3.10.0",sh="https://jssip.net",nh=["José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)","Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)"],rh="lib/JsSIP.d.ts",ih="lib-es5/JsSIP.js",lh=["sip","websocket","webrtc","node","browser","library"],oh="MIT",ah={type:"git",url:"https://github.com/versatica/JsSIP.git"},uh={url:"https://github.com/versatica/JsSIP/issues"},ch={"@types/events":"^3.0.0","@types/debug":"^4.1.7",debug:"^4.3.1",events:"^3.3.0","sdp-transform":"^2.14.1"},fh={"@babel/core":"^7.19.6","@babel/preset-env":"^7.19.4","ansi-colors":"^3.2.4",browserify:"^16.5.1",eslint:"^5.16.0","fancy-log":"^1.3.3",gulp:"^4.0.2","gulp-babel":"^8.0.0","gulp-eslint":"^5.0.0","gulp-expect-file":"^1.0.2","gulp-header":"^2.0.9","gulp-nodeunit-runner":"^0.2.2","gulp-plumber":"^1.2.1","gulp-rename":"^1.4.0","gulp-uglify-es":"^1.0.4",pegjs:"^0.7.0","vinyl-buffer":"^1.0.1","vinyl-source-stream":"^2.0.0"},dh={lint:"node npm-scripts.js lint",test:"node npm-scripts.js test",prepublish:"node npm-scripts.js prepublish",release:"node npm-scripts.js release"},jo={name:Xd,title:Zd,description:eh,version:th,homepage:sh,contributors:nh,types:rh,main:ih,keywords:lh,license:oh,repository:ah,bugs:uh,dependencies:ch,devDependencies:fh,scripts:dh};var Ju=jo,ot={USER_AGENT:"".concat(Ju.title," ").concat(Ju.version),SIP:"sip",SIPS:"sips",causes:{CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:"Request Timeout",SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:"Rejected",REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:"Terminated",WEBRTC_ERROR:"WebRTC Error",CANCELED:"Canceled",NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:"ACK",BYE:"BYE",CANCEL:"CANCEL",INFO:"INFO",INVITE:"INVITE",MESSAGE:"MESSAGE",NOTIFY:"NOTIFY",OPTIONS:"OPTIONS",REGISTER:"REGISTER",REFER:"REFER",UPDATE:"UPDATE",SUBSCRIBE:"SUBSCRIBE",DTMF_TRANSPORT:{INFO:"INFO",RFC2833:"RFC2833"},REASON_PHRASE:{100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",424:"Bad Location Information",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:"JsSIP Internal 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"},ALLOWED_METHODS:"INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY",ACCEPTED_BODY_TYPES:"application/sdp, application/dtmf-relay",MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2};function To(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?To=function(s){return typeof s}:To=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},To(c)}function qo(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Bo(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&Zi(c,t)}function Go(c){var t=Qf();return function(){var i=el(c),a;if(t){var n=el(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return hh(this,a)}}function hh(c,t){return t&&(To(t)==="object"||typeof t=="function")?t:_h(c)}function _h(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function mr(c){var t=typeof Map=="function"?new Map:void 0;return mr=function(i){if(i===null||!ph(i))return i;if(typeof i!="function")throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(i))return t.get(i);t.set(i,a)}function a(){return vo(i,arguments,el(this).constructor)}return a.prototype=Object.create(i.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),Zi(a,i)},mr(c)}function vo(c,t,s){return Qf()?vo=Reflect.construct:vo=function(a,n,r){var h=[null];h.push.apply(h,n);var d=Function.bind.apply(a,h),_=new d;return r&&Zi(_,r.prototype),_},vo.apply(null,arguments)}function Qf(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function ph(c){return Function.toString.call(c).indexOf("[native code]")!==-1}function Zi(c,t){return Zi=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},Zi(c,t)}function el(c){return el=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},el(c)}var mh=function(c){Bo(s,c);var t=Go(s);function s(i,a){var n;return qo(this,s),n=t.call(this),n.code=1,n.name="CONFIGURATION_ERROR",n.parameter=i,n.value=a,n.message=n.value?"Invalid value ".concat(JSON.stringify(n.value),' for parameter "').concat(n.parameter,'"'):"Missing parameter: ".concat(n.parameter),n}return s}(mr(Error)),gh=function(c){Bo(s,c);var t=Go(s);function s(i){var a;return qo(this,s),a=t.call(this),a.code=2,a.name="INVALID_STATE_ERROR",a.status=i,a.message="Invalid status: ".concat(i),a}return s}(mr(Error)),Th=function(c){Bo(s,c);var t=Go(s);function s(i){var a;return qo(this,s),a=t.call(this),a.code=3,a.name="NOT_SUPPORTED_ERROR",a.message=i,a}return s}(mr(Error)),vh=function(c){Bo(s,c);var t=Go(s);function s(i){var a;return qo(this,s),a=t.call(this),a.code=4,a.name="NOT_READY_ERROR",a.message=i,a}return s}(mr(Error)),Ks={ConfigurationError:mh,InvalidStateError:gh,NotSupportedError:Th,NotReadyError:vh},tt={},ha,zu;function Uu(){if(zu)return ha;zu=1;function c(n,r){if(!(n instanceof r))throw new TypeError("Cannot call a class as a function")}function t(n,r){for(var h=0;h<r.length;h++){var d=r[h];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(n,d.key,d)}}function s(n,r,h){return r&&t(n.prototype,r),h&&t(n,h),n}var i=Ys(),a=us();return ha=function(){s(n,null,[{key:"parse",value:function(h){if(h=a.parse(h,"Name_Addr_Header"),h!==-1)return h}}]);function n(r,h,d){if(c(this,n),!r||!(r instanceof i))throw new TypeError('missing or invalid "uri" parameter');this._uri=r,this._parameters={},this.display_name=h;for(var _ in d)Object.prototype.hasOwnProperty.call(d,_)&&this.setParam(_,d[_])}return s(n,[{key:"setParam",value:function(h,d){h&&(this._parameters[h.toLowerCase()]=typeof d>"u"||d===null?null:d.toString())}},{key:"getParam",value:function(h){if(h)return this._parameters[h.toLowerCase()]}},{key:"hasParam",value:function(h){if(h)return this._parameters.hasOwnProperty(h.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(h){if(h=h.toLowerCase(),this._parameters.hasOwnProperty(h)){var d=this._parameters[h];return delete this._parameters[h],d}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"clone",value:function(){return new n(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}},{key:"_quote",value:function(h){return h.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}},{key:"toString",value:function(){var h=this._display_name?'"'.concat(this._quote(this._display_name),'" '):"";h+="<".concat(this._uri.toString(),">");for(var d in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,d)&&(h+=";".concat(d),this._parameters[d]!==null&&(h+="=".concat(this._parameters[d])));return h}},{key:"uri",get:function(){return this._uri}},{key:"display_name",get:function(){return this._display_name},set:function(h){this._display_name=h===0?"0":h}}]),n}(),ha}var _a,Qu;function us(){return Qu||(Qu=1,_a=function(){function c(s){return'"'+s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+'"'}var t={parse:function(i,a){var n={CRLF:g,DIGIT:T,ALPHA:S,HEXDIG:E,WSP:C,OCTET:A,DQUOTE:R,SP:F,HTAB:I,alphanum:ie,reserved:N,unreserved:$,mark:ve,escaped:_e,LWS:U,SWS:x,HCOLON:q,TEXT_UTF8_TRIM:j,TEXT_UTF8char:Y,UTF8_NONASCII:V,UTF8_CONT:Q,LHEX:k,token:M,token_nodot:B,separators:Fe,word:X,STAR:W,SLASH:G,EQUAL:re,LPAREN:pe,RPAREN:Ie,RAQUOT:ke,LAQUOT:Ae,COMMA:oe,SEMI:ye,COLON:rt,LDQUOT:at,RDQUOT:Ee,comment:Ce,ctext:be,quoted_string:Oe,quoted_string_clean:ge,qdtext:ue,quoted_pair:me,SIP_URI_noparams:we,SIP_URI:Ne,uri_scheme:et,uri_scheme_sips:$e,uri_scheme_sip:$t,userinfo:_t,user:wn,user_unreserved:On,password:Js,hostport:ts,host:cs,hostname:zs,domainlabel:Dn,toplabel:Nn,IPv6reference:Qs,IPv6address:Te,h16:ae,ls32:ut,IPv4address:Kt,dec_octet:Rs,port:Sr,uri_parameters:xn,uri_parameter:Un,transport_param:Er,user_param:yr,method_param:Cr,ttl_param:Ar,maddr_param:Rr,lr_param:Ir,other_param:br,pname:wr,pvalue:Is,paramchar:bs,param_unreserved:Or,headers:Xs,header:Zs,hname:Dr,hvalue:ws,hnv_unreserved:en,Request_Response:gl,Request_Line:Nr,Request_URI:kn,absoluteURI:Mn,hier_part:xr,net_path:tn,abs_path:sn,opaque_part:Os,uric:Ds,uric_no_slash:Ur,path_segments:nn,segment:Ns,param:fs,pchar:xs,scheme:kr,authority:Mr,srvr:Pr,reg_name:Lr,query:Pn,SIP_Version:Ln,INVITEm:$r,ACKm:Hr,OPTIONSm:Fr,BYEm:Vr,CANCELm:jr,REGISTERm:qr,SUBSCRIBEm:Br,NOTIFYm:Gr,REFERm:rn,Method:ln,Status_Line:Wr,Status_Code:Kr,extension_code:Yr,Reason_Phrase:Tl,Allow_Events:Qo,Call_ID:Xo,Contact:$n,contact_param:Ht,name_addr:Ft,display_name:Us,contact_params:Hn,c_p_q:Jr,c_p_expires:ss,delta_seconds:ns,qvalue:Ke,generic_param:Ye,gen_value:vl,Content_Disposition:Sl,disp_type:Fn,disp_param:Vn,handling_param:El,Content_Encoding:Zo,Content_Length:ea,Content_Type:yl,media_type:zr,m_type:Qr,discrete_type:Xr,composite_type:on,extension_token:an,x_token:Zr,m_subtype:jn,m_parameter:qn,m_value:Cl,CSeq:Al,CSeq_value:Rl,Expires:ta,Event:un,event_type:cn,From:ei,from_param:fn,tag_param:ti,Max_Forwards:sa,Min_Expires:na,Name_Addr_Header:ra,Proxy_Authenticate:si,challenge:Bn,other_challenge:ks,auth_param:rs,digest_cln:dn,realm:ni,realm_value:ri,domain:hn,URI:_n,nonce:ii,nonce_value:li,opaque:oi,stale:ai,algorithm:ui,qop_options:pn,qop_value:Gn,Proxy_Require:ia,Record_Route:Wn,rec_route:Kn,Reason:ci,reason_param:Yn,reason_cause:Il,Require:la,Route:Jn,route_param:zn,Subscription_State:bl,substate_value:Qn,subexp_params:Xn,event_reason_value:wl,Subject:oa,Supported:aa,To:fi,to_param:di,Via:Zn,via_param:Ms,via_params:er,via_ttl:hi,via_maddr:_i,via_received:pi,via_branch:mi,response_port:gi,rport:Ti,sent_protocol:vi,protocol_name:Si,transport:Ei,sent_by:yi,via_host:Ci,via_port:tr,ttl:Ai,WWW_Authenticate:ua,Session_Expires:Ol,s_e_expires:sr,s_e_params:nr,s_e_refresher:Dl,extension_header:Nl,header_value:xl,message_body:ca,uuid_URI:Ul,uuid:Vt,hex4:jt,hex8:Ri,hex12:kl,Refer_To:fa,Replaces:Ml,call_id:rr,replaces_param:ir,to_tag:Ii,from_tag:bi,early_flag:Pl};if(a!==void 0){if(n[a]===void 0)throw new Error("Invalid rule name: "+c(a)+".")}else a="CRLF";var r=0,h=0,d=[];function _(e){r<h||(r>h&&(h=r,d=[]),d.push(e))}function g(){var e;return i.substr(r,2)===`\r
|
|
2
2
|
`?(e=`\r
|
|
3
|
-
`,r+=2):(e=null,_('"\\r\\n"')),e}function T(){var e;return/^[0-9]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[0-9]")),e}function S(){var e;return/^[a-zA-Z]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[a-zA-Z]")),e}function E(){var e;return/^[0-9a-fA-F]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[0-9a-fA-F]")),e}function C(){var e;return e=V(),e===null&&(e=w()),e}function A(){var e;return/^[\0-\xFF]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[\\0-\\xFF]")),e}function R(){var e;return/^["]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_('["]')),e}function V(){var e;return l.charCodeAt(r)===32?(e=" ",r++):(e=null,_('" "')),e}function w(){var e;return l.charCodeAt(r)===9?(e=" ",r++):(e=null,_('"\\t"')),e}function le(){var e;return/^[a-zA-Z0-9]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[a-zA-Z0-9]")),e}function x(){var e;return l.charCodeAt(r)===59?(e=";",r++):(e=null,_('";"')),e===null&&(l.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e===null&&(l.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(l.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(l.charCodeAt(r)===64?(e="@",r++):(e=null,_('"@"')),e===null&&(l.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(l.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(l.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(l.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')),e===null&&(l.charCodeAt(r)===44?(e=",",r++):(e=null,_('","'))))))))))),e}function H(){var e;return e=le(),e===null&&(e=ve()),e}function ve(){var e;return l.charCodeAt(r)===45?(e="-",r++):(e=null,_('"-"')),e===null&&(l.charCodeAt(r)===95?(e="_",r++):(e=null,_('"_"')),e===null&&(l.charCodeAt(r)===46?(e=".",r++):(e=null,_('"."')),e===null&&(l.charCodeAt(r)===33?(e="!",r++):(e=null,_('"!"')),e===null&&(l.charCodeAt(r)===126?(e="~",r++):(e=null,_('"~"')),e===null&&(l.charCodeAt(r)===42?(e="*",r++):(e=null,_('"*"')),e===null&&(l.charCodeAt(r)===39?(e="'",r++):(e=null,_(`"'"`)),e===null&&(l.charCodeAt(r)===40?(e="(",r++):(e=null,_('"("')),e===null&&(l.charCodeAt(r)===41?(e=")",r++):(e=null,_('")"')))))))))),e}function pe(){var e,o,u,f,p;return f=r,p=r,l.charCodeAt(r)===37?(e="%",r++):(e=null,_('"%"')),e!==null?(o=E(),o!==null?(u=E(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){return v.join("")}(f,e)),e===null&&(r=f),e}function P(){var e,o,u,f,p,m;for(f=r,p=r,m=r,e=[],o=C();o!==null;)e.push(o),o=C();if(e!==null?(o=g(),o!==null?e=[e,o]:(e=null,r=m)):(e=null,r=m),e=e!==null?e:"",e!==null){if(u=C(),u!==null)for(o=[];u!==null;)o.push(u),u=C();else o=null;o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e!==null&&(e=function(v){return" "}()),e===null&&(r=f),e}function N(){var e;return e=P(),e=e!==null?e:"",e}function q(){var e,o,u,f,p;for(f=r,p=r,e=[],o=V(),o===null&&(o=w());o!==null;)e.push(o),o=V(),o===null&&(o=w());return e!==null?(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=N(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return":"}()),e===null&&(r=f),e}function j(){var e,o,u,f,p,m,v;if(p=r,m=r,o=Y(),o!==null)for(e=[];o!==null;)e.push(o),o=Y();else e=null;if(e!==null){for(o=[],v=r,u=[],f=P();f!==null;)u.push(f),f=P();for(u!==null?(f=Y(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;){for(o.push(u),v=r,u=[],f=P();f!==null;)u.push(f),f=P();u!==null?(f=Y(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v)}o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){return l.substring(r,y)}(p)),e===null&&(r=p),e}function Y(){var e;return/^[!-~]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[!-~]")),e===null&&(e=F()),e}function F(){var e;return/^[\x80-\uFFFF]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[\\x80-\\uFFFF]")),e}function X(){var e;return/^[\x80-\xBF]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[\\x80-\\xBF]")),e}function U(){var e;return e=T(),e===null&&(/^[a-f]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[a-f]"))),e}function k(){var e,o,u;if(u=r,o=le(),o===null&&(l.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(l.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o===null&&(l.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(l.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(l.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(l.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(l.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(l.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(l.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"')))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=le(),o===null&&(l.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(l.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o===null&&(l.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(l.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(l.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(l.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(l.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(l.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(l.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"'))))))))))));else e=null;return e!==null&&(e=function(f){return l.substring(r,f)}(u)),e===null&&(r=u),e}function B(){var e,o,u;if(u=r,o=le(),o===null&&(l.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(l.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(l.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(l.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(l.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(l.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(l.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(l.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"'))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=le(),o===null&&(l.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(l.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(l.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(l.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(l.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(l.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(l.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(l.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"')))))))))));else e=null;return e!==null&&(e=function(f){return l.substring(r,f)}(u)),e===null&&(r=u),e}function He(){var e;return l.charCodeAt(r)===40?(e="(",r++):(e=null,_('"("')),e===null&&(l.charCodeAt(r)===41?(e=")",r++):(e=null,_('")"')),e===null&&(l.charCodeAt(r)===60?(e="<",r++):(e=null,_('"<"')),e===null&&(l.charCodeAt(r)===62?(e=">",r++):(e=null,_('">"')),e===null&&(l.charCodeAt(r)===64?(e="@",r++):(e=null,_('"@"')),e===null&&(l.charCodeAt(r)===44?(e=",",r++):(e=null,_('","')),e===null&&(l.charCodeAt(r)===59?(e=";",r++):(e=null,_('";"')),e===null&&(l.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(l.charCodeAt(r)===92?(e="\\",r++):(e=null,_('"\\\\"')),e===null&&(e=R(),e===null&&(l.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e===null&&(l.charCodeAt(r)===91?(e="[",r++):(e=null,_('"["')),e===null&&(l.charCodeAt(r)===93?(e="]",r++):(e=null,_('"]"')),e===null&&(l.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(l.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(l.charCodeAt(r)===123?(e="{",r++):(e=null,_('"{"')),e===null&&(l.charCodeAt(r)===125?(e="}",r++):(e=null,_('"}"')),e===null&&(e=V(),e===null&&(e=w())))))))))))))))))),e}function Q(){var e,o,u;if(u=r,o=le(),o===null&&(l.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(l.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o===null&&(l.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(l.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(l.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(l.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(l.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(l.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(l.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"')),o===null&&(l.charCodeAt(r)===40?(o="(",r++):(o=null,_('"("')),o===null&&(l.charCodeAt(r)===41?(o=")",r++):(o=null,_('")"')),o===null&&(l.charCodeAt(r)===60?(o="<",r++):(o=null,_('"<"')),o===null&&(l.charCodeAt(r)===62?(o=">",r++):(o=null,_('">"')),o===null&&(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o===null&&(l.charCodeAt(r)===92?(o="\\",r++):(o=null,_('"\\\\"')),o===null&&(o=R(),o===null&&(l.charCodeAt(r)===47?(o="/",r++):(o=null,_('"/"')),o===null&&(l.charCodeAt(r)===91?(o="[",r++):(o=null,_('"["')),o===null&&(l.charCodeAt(r)===93?(o="]",r++):(o=null,_('"]"')),o===null&&(l.charCodeAt(r)===63?(o="?",r++):(o=null,_('"?"')),o===null&&(l.charCodeAt(r)===123?(o="{",r++):(o=null,_('"{"')),o===null&&(l.charCodeAt(r)===125?(o="}",r++):(o=null,_('"}"'))))))))))))))))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=le(),o===null&&(l.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(l.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o===null&&(l.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(l.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(l.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(l.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(l.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(l.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(l.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"')),o===null&&(l.charCodeAt(r)===40?(o="(",r++):(o=null,_('"("')),o===null&&(l.charCodeAt(r)===41?(o=")",r++):(o=null,_('")"')),o===null&&(l.charCodeAt(r)===60?(o="<",r++):(o=null,_('"<"')),o===null&&(l.charCodeAt(r)===62?(o=">",r++):(o=null,_('">"')),o===null&&(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o===null&&(l.charCodeAt(r)===92?(o="\\",r++):(o=null,_('"\\\\"')),o===null&&(o=R(),o===null&&(l.charCodeAt(r)===47?(o="/",r++):(o=null,_('"/"')),o===null&&(l.charCodeAt(r)===91?(o="[",r++):(o=null,_('"["')),o===null&&(l.charCodeAt(r)===93?(o="]",r++):(o=null,_('"]"')),o===null&&(l.charCodeAt(r)===63?(o="?",r++):(o=null,_('"?"')),o===null&&(l.charCodeAt(r)===123?(o="{",r++):(o=null,_('"{"')),o===null&&(l.charCodeAt(r)===125?(o="}",r++):(o=null,_('"}"')))))))))))))))))))))))));else e=null;return e!==null&&(e=function(f){return l.substring(r,f)}(u)),e===null&&(r=u),e}function W(){var e,o,u,f,p;return f=r,p=r,e=N(),e!==null?(l.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o!==null?(u=N(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return"*"}()),e===null&&(r=f),e}function G(){var e,o,u,f,p;return f=r,p=r,e=N(),e!==null?(l.charCodeAt(r)===47?(o="/",r++):(o=null,_('"/"')),o!==null?(u=N(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return"/"}()),e===null&&(r=f),e}function re(){var e,o,u,f,p;return f=r,p=r,e=N(),e!==null?(l.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o!==null?(u=N(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return"="}()),e===null&&(r=f),e}function _e(){var e,o,u,f,p;return f=r,p=r,e=N(),e!==null?(l.charCodeAt(r)===40?(o="(",r++):(o=null,_('"("')),o!==null?(u=N(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return"("}()),e===null&&(r=f),e}function Ie(){var e,o,u,f,p;return f=r,p=r,e=N(),e!==null?(l.charCodeAt(r)===41?(o=")",r++):(o=null,_('")"')),o!==null?(u=N(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return")"}()),e===null&&(r=f),e}function ke(){var e,o,u,f;return u=r,f=r,l.charCodeAt(r)===62?(e=">",r++):(e=null,_('">"')),e!==null?(o=N(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return">"}()),e===null&&(r=u),e}function Ae(){var e,o,u,f;return u=r,f=r,e=N(),e!==null?(l.charCodeAt(r)===60?(o="<",r++):(o=null,_('"<"')),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return"<"}()),e===null&&(r=u),e}function oe(){var e,o,u,f,p;return f=r,p=r,e=N(),e!==null?(l.charCodeAt(r)===44?(o=",",r++):(o=null,_('","')),o!==null?(u=N(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return","}()),e===null&&(r=f),e}function ye(){var e,o,u,f,p;return f=r,p=r,e=N(),e!==null?(l.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o!==null?(u=N(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return";"}()),e===null&&(r=f),e}function nt(){var e,o,u,f,p;return f=r,p=r,e=N(),e!==null?(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=N(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return":"}()),e===null&&(r=f),e}function ot(){var e,o,u,f;return u=r,f=r,e=N(),e!==null?(o=R(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return'"'}()),e===null&&(r=u),e}function Ee(){var e,o,u,f;return u=r,f=r,e=R(),e!==null?(o=N(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return'"'}()),e===null&&(r=u),e}function Ce(){var e,o,u,f;if(f=r,e=_e(),e!==null){for(o=[],u=be(),u===null&&(u=me(),u===null&&(u=Ce()));u!==null;)o.push(u),u=be(),u===null&&(u=me(),u===null&&(u=Ce()));o!==null?(u=Ie(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)}else e=null,r=f;return e}function be(){var e;return/^[!-']/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[!-']")),e===null&&(/^[*-[]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[*-[]")),e===null&&(/^[\]-~]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[\\]-~]")),e===null&&(e=F(),e===null&&(e=P())))),e}function Oe(){var e,o,u,f,p,m;if(p=r,m=r,e=N(),e!==null)if(o=R(),o!==null){for(u=[],f=ue(),f===null&&(f=me());f!==null;)u.push(f),f=ue(),f===null&&(f=me());u!==null?(f=R(),f!==null?e=[e,o,u,f]:(e=null,r=m)):(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e!==null&&(e=function(v){return l.substring(r,v)}(p)),e===null&&(r=p),e}function ge(){var e,o,u,f,p,m;if(p=r,m=r,e=N(),e!==null)if(o=R(),o!==null){for(u=[],f=ue(),f===null&&(f=me());f!==null;)u.push(f),f=ue(),f===null&&(f=me());u!==null?(f=R(),f!==null?e=[e,o,u,f]:(e=null,r=m)):(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e!==null&&(e=function(v){var y=l.substring(r,v).trim();return y.substring(1,y.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(p)),e===null&&(r=p),e}function ue(){var e;return e=P(),e===null&&(l.charCodeAt(r)===33?(e="!",r++):(e=null,_('"!"')),e===null&&(/^[#-[]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[#-[]")),e===null&&(/^[\]-~]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[\\]-~]")),e===null&&(e=F())))),e}function me(){var e,o,u;return u=r,l.charCodeAt(r)===92?(e="\\",r++):(e=null,_('"\\\\"')),e!==null?(/^[\0-\t]/.test(l.charAt(r))?(o=l.charAt(r),r++):(o=null,_("[\\0-\\t]")),o===null&&(/^[\x0B-\f]/.test(l.charAt(r))?(o=l.charAt(r),r++):(o=null,_("[\\x0B-\\f]")),o===null&&(/^[\x0E-]/.test(l.charAt(r))?(o=l.charAt(r),r++):(o=null,_("[\\x0E-]")))),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function we(){var e,o,u,f,p,m;return p=r,m=r,e=Ze(),e!==null?(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ht(),u=u!==null?u:"",u!==null?(f=es(),f!==null?e=[e,o,u,f]:(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m),e!==null&&(e=function(v){try{O.uri=new fs(O.scheme,O.user,O.host,O.port),delete O.scheme,delete O.user,delete O.host,delete O.host_type,delete O.port}catch{O=-1}}()),e===null&&(r=p),e}function Ne(){var e,o,u,f,p,m,v,y;return v=r,y=r,e=Ze(),e!==null?(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ht(),u=u!==null?u:"",u!==null?(f=es(),f!==null?(p=Nn(),p!==null?(m=Xs(),m=m!==null?m:"",m!==null?e=[e,o,u,f,p,m]:(e=null,r=y)):(e=null,r=y)):(e=null,r=y)):(e=null,r=y)):(e=null,r=y)):(e=null,r=y),e!==null&&(e=function(D){try{O.uri=new fs(O.scheme,O.user,O.host,O.port,O.uri_params,O.uri_headers),delete O.scheme,delete O.user,delete O.host,delete O.host_type,delete O.port,delete O.uri_params,a==="SIP_URI"&&(O=O.uri)}catch{O=-1}}()),e===null&&(r=v),e}function Ze(){var e;return e=Le(),e===null&&(e=Lt()),e}function Le(){var e,o;return o=r,l.substr(r,4).toLowerCase()==="sips"?(e=l.substr(r,4),r+=4):(e=null,_('"sips"')),e!==null&&(e=function(u,f){O.scheme=f.toLowerCase()}(o,e)),e===null&&(r=o),e}function Lt(){var e,o;return o=r,l.substr(r,3).toLowerCase()==="sip"?(e=l.substr(r,3),r+=3):(e=null,_('"sip"')),e!==null&&(e=function(u,f){O.scheme=f.toLowerCase()}(o,e)),e===null&&(r=o),e}function ht(){var e,o,u,f,p,m;return f=r,p=r,e=bn(),e!==null?(m=r,l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=Ys(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?(l.charCodeAt(r)===64?(u="@",r++):(u=null,_('"@"')),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){O.user=decodeURIComponent(l.substring(r-1,v))}(f)),e===null&&(r=f),e}function bn(){var e,o;if(o=H(),o===null&&(o=pe(),o===null&&(o=wn())),o!==null)for(e=[];o!==null;)e.push(o),o=H(),o===null&&(o=pe(),o===null&&(o=wn()));else e=null;return e}function wn(){var e;return l.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(l.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(l.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(l.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')),e===null&&(l.charCodeAt(r)===44?(e=",",r++):(e=null,_('","')),e===null&&(l.charCodeAt(r)===59?(e=";",r++):(e=null,_('";"')),e===null&&(l.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(l.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"'))))))))),e}function Ys(){var e,o,u;for(u=r,e=[],o=H(),o===null&&(o=pe(),o===null&&(l.charCodeAt(r)===38?(o="&",r++):(o=null,_('"&"')),o===null&&(l.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(l.charCodeAt(r)===36?(o="$",r++):(o=null,_('"$"')),o===null&&(l.charCodeAt(r)===44?(o=",",r++):(o=null,_('","'))))))));o!==null;)e.push(o),o=H(),o===null&&(o=pe(),o===null&&(l.charCodeAt(r)===38?(o="&",r++):(o=null,_('"&"')),o===null&&(l.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(l.charCodeAt(r)===36?(o="$",r++):(o=null,_('"$"')),o===null&&(l.charCodeAt(r)===44?(o=",",r++):(o=null,_('","'))))))));return e!==null&&(e=function(f){O.password=l.substring(r,f)}(u)),e===null&&(r=u),e}function es(){var e,o,u,f,p;return f=r,e=us(),e!==null?(p=r,l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=vr(),u!==null?o=[o,u]:(o=null,r=p)):(o=null,r=p),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e}function us(){var e,o;return o=r,e=Js(),e===null&&(e=Wt(),e===null&&(e=zs())),e!==null&&(e=function(u){return O.host=l.substring(r,u).toLowerCase(),O.host}(o)),e===null&&(r=o),e}function Js(){var e,o,u,f,p,m;for(f=r,p=r,e=[],m=r,o=On(),o!==null?(l.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m);o!==null;)e.push(o),m=r,o=On(),o!==null?(l.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m);return e!==null?(o=Dn(),o!==null?(l.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u=u!==null?u:"",u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){return O.host_type="domain",l.substring(r,v)}(f)),e===null&&(r=f),e}function On(){var e,o,u,f;if(f=r,e=le(),e!==null){for(o=[],u=le(),u===null&&(l.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(l.charCodeAt(r)===95?(u="_",r++):(u=null,_('"_"'))));u!==null;)o.push(u),u=le(),u===null&&(l.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(l.charCodeAt(r)===95?(u="_",r++):(u=null,_('"_"'))));o!==null?e=[e,o]:(e=null,r=f)}else e=null,r=f;return e}function Dn(){var e,o,u,f;if(f=r,e=S(),e!==null){for(o=[],u=le(),u===null&&(l.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(l.charCodeAt(r)===95?(u="_",r++):(u=null,_('"_"'))));u!==null;)o.push(u),u=le(),u===null&&(l.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(l.charCodeAt(r)===95?(u="_",r++):(u=null,_('"_"'))));o!==null?e=[e,o]:(e=null,r=f)}else e=null,r=f;return e}function zs(){var e,o,u,f,p;return f=r,p=r,l.charCodeAt(r)===91?(e="[",r++):(e=null,_('"["')),e!==null?(o=Te(),o!==null?(l.charCodeAt(r)===93?(u="]",r++):(u=null,_('"]"')),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return O.host_type="IPv6",l.substring(r,m)}(f)),e===null&&(r=f),e}function Te(){var e,o,u,f,p,m,v,y,D,ie,xe,wt,Ps,L,I,Se;return L=r,I=r,e=ae(),e!==null?(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?(l.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?(l.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?(l.charCodeAt(r)===58?(y=":",r++):(y=null,_('":"')),y!==null?(D=ae(),D!==null?(l.charCodeAt(r)===58?(ie=":",r++):(ie=null,_('":"')),ie!==null?(xe=ae(),xe!==null?(l.charCodeAt(r)===58?(wt=":",r++):(wt=null,_('":"')),wt!==null?(Ps=at(),Ps!==null?e=[e,o,u,f,p,m,v,y,D,ie,xe,wt,Ps]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,l.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?(l.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?(l.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ae(),y!==null?(l.charCodeAt(r)===58?(D=":",r++):(D=null,_('":"')),D!==null?(ie=ae(),ie!==null?(l.charCodeAt(r)===58?(xe=":",r++):(xe=null,_('":"')),xe!==null?(wt=at(),wt!==null?e=[e,o,u,f,p,m,v,y,D,ie,xe,wt]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,l.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?(l.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?(l.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ae(),y!==null?(l.charCodeAt(r)===58?(D=":",r++):(D=null,_('":"')),D!==null?(ie=at(),ie!==null?e=[e,o,u,f,p,m,v,y,D,ie]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,l.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?(l.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?(l.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=at(),y!==null?e=[e,o,u,f,p,m,v,y]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,l.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?(l.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=at(),m!==null?e=[e,o,u,f,p,m]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,l.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=at(),f!==null?e=[e,o,u,f]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,l.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=at(),o!==null?e=[e,o]:(e=null,r=I)):(e=null,r=I),e===null&&(I=r,l.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?e=[e,o]:(e=null,r=I)):(e=null,r=I),e===null&&(I=r,e=ae(),e!==null?(l.substr(r,2)==="::"?(o="::",r+=2):(o=null,_('"::"')),o!==null?(u=ae(),u!==null?(l.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?(l.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?(l.charCodeAt(r)===58?(y=":",r++):(y=null,_('":"')),y!==null?(D=ae(),D!==null?(l.charCodeAt(r)===58?(ie=":",r++):(ie=null,_('":"')),ie!==null?(xe=at(),xe!==null?e=[e,o,u,f,p,m,v,y,D,ie,xe]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,e=ae(),e!==null?(Se=r,l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(l.substr(r,2)==="::"?(u="::",r+=2):(u=null,_('"::"')),u!==null?(f=ae(),f!==null?(l.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?(l.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ae(),y!==null?(l.charCodeAt(r)===58?(D=":",r++):(D=null,_('":"')),D!==null?(ie=at(),ie!==null?e=[e,o,u,f,p,m,v,y,D,ie]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,e=ae(),e!==null?(Se=r,l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(l.substr(r,2)==="::"?(f="::",r+=2):(f=null,_('"::"')),f!==null?(p=ae(),p!==null?(l.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?(l.charCodeAt(r)===58?(y=":",r++):(y=null,_('":"')),y!==null?(D=at(),D!==null?e=[e,o,u,f,p,m,v,y,D]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,e=ae(),e!==null?(Se=r,l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(Se=r,l.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(l.substr(r,2)==="::"?(p="::",r+=2):(p=null,_('"::"')),p!==null?(m=ae(),m!==null?(l.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=at(),y!==null?e=[e,o,u,f,p,m,v,y]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,e=ae(),e!==null?(Se=r,l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(Se=r,l.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(Se=r,l.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?p=[p,m]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(l.substr(r,2)==="::"?(m="::",r+=2):(m=null,_('"::"')),m!==null?(v=at(),v!==null?e=[e,o,u,f,p,m,v]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,e=ae(),e!==null?(Se=r,l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(Se=r,l.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(Se=r,l.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?p=[p,m]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(Se=r,l.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?m=[m,v]:(m=null,r=Se)):(m=null,r=Se),m=m!==null?m:"",m!==null?(l.substr(r,2)==="::"?(v="::",r+=2):(v=null,_('"::"')),v!==null?(y=ae(),y!==null?e=[e,o,u,f,p,m,v,y]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I),e===null&&(I=r,e=ae(),e!==null?(Se=r,l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,l.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(Se=r,l.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(Se=r,l.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?p=[p,m]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(Se=r,l.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?m=[m,v]:(m=null,r=Se)):(m=null,r=Se),m=m!==null?m:"",m!==null?(Se=r,l.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ae(),y!==null?v=[v,y]:(v=null,r=Se)):(v=null,r=Se),v=v!==null?v:"",v!==null?(l.substr(r,2)==="::"?(y="::",r+=2):(y=null,_('"::"')),y!==null?e=[e,o,u,f,p,m,v,y]:(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I)):(e=null,r=I))))))))))))))),e!==null&&(e=function(Vd){return O.host_type="IPv6",l.substring(r,Vd)}(L)),e===null&&(r=L),e}function ae(){var e,o,u,f,p;return p=r,e=E(),e!==null?(o=E(),o=o!==null?o:"",o!==null?(u=E(),u=u!==null?u:"",u!==null?(f=E(),f=f!==null?f:"",f!==null?e=[e,o,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function at(){var e,o,u,f;return f=r,e=ae(),e!==null?(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(e=Wt()),e}function Wt(){var e,o,u,f,p,m,v,y,D;return y=r,D=r,e=As(),e!==null?(l.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o!==null?(u=As(),u!==null?(l.charCodeAt(r)===46?(f=".",r++):(f=null,_('"."')),f!==null?(p=As(),p!==null?(l.charCodeAt(r)===46?(m=".",r++):(m=null,_('"."')),m!==null?(v=As(),v!==null?e=[e,o,u,f,p,m,v]:(e=null,r=D)):(e=null,r=D)):(e=null,r=D)):(e=null,r=D)):(e=null,r=D)):(e=null,r=D)):(e=null,r=D),e!==null&&(e=function(ie){return O.host_type="IPv4",l.substring(r,ie)}(y)),e===null&&(r=y),e}function As(){var e,o,u,f;return f=r,l.substr(r,2)==="25"?(e="25",r+=2):(e=null,_('"25"')),e!==null?(/^[0-5]/.test(l.charAt(r))?(o=l.charAt(r),r++):(o=null,_("[0-5]")),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e===null&&(f=r,l.charCodeAt(r)===50?(e="2",r++):(e=null,_('"2"')),e!==null?(/^[0-4]/.test(l.charAt(r))?(o=l.charAt(r),r++):(o=null,_("[0-4]")),o!==null?(u=T(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(f=r,l.charCodeAt(r)===49?(e="1",r++):(e=null,_('"1"')),e!==null?(o=T(),o!==null?(u=T(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(f=r,/^[1-9]/.test(l.charAt(r))?(e=l.charAt(r),r++):(e=null,_("[1-9]")),e!==null?(o=T(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e===null&&(e=T())))),e}function vr(){var e,o,u,f,p,m,v;return m=r,v=r,e=T(),e=e!==null?e:"",e!==null?(o=T(),o=o!==null?o:"",o!==null?(u=T(),u=u!==null?u:"",u!==null?(f=T(),f=f!==null?f:"",f!==null?(p=T(),p=p!==null?p:"",p!==null?e=[e,o,u,f,p]:(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(y,D){return D=parseInt(D.join("")),O.port=D,D}(m,e)),e===null&&(r=m),e}function Nn(){var e,o,u,f;for(e=[],f=r,l.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o!==null?(u=xn(),u!==null?o=[o,u]:(o=null,r=f)):(o=null,r=f);o!==null;)e.push(o),f=r,l.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o!==null?(u=xn(),u!==null?o=[o,u]:(o=null,r=f)):(o=null,r=f);return e}function xn(){var e;return e=Sr(),e===null&&(e=Er(),e===null&&(e=yr(),e===null&&(e=Cr(),e===null&&(e=Ar(),e===null&&(e=Rr(),e===null&&(e=Ir())))))),e}function Sr(){var e,o,u,f;return u=r,f=r,l.substr(r,10).toLowerCase()==="transport="?(e=l.substr(r,10),r+=10):(e=null,_('"transport="')),e!==null?(l.substr(r,3).toLowerCase()==="udp"?(o=l.substr(r,3),r+=3):(o=null,_('"udp"')),o===null&&(l.substr(r,3).toLowerCase()==="tcp"?(o=l.substr(r,3),r+=3):(o=null,_('"tcp"')),o===null&&(l.substr(r,4).toLowerCase()==="sctp"?(o=l.substr(r,4),r+=4):(o=null,_('"sctp"')),o===null&&(l.substr(r,3).toLowerCase()==="tls"?(o=l.substr(r,3),r+=3):(o=null,_('"tls"')),o===null&&(o=k())))),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.uri_params||(O.uri_params={}),O.uri_params.transport=m.toLowerCase()}(u,e[1])),e===null&&(r=u),e}function Er(){var e,o,u,f;return u=r,f=r,l.substr(r,5).toLowerCase()==="user="?(e=l.substr(r,5),r+=5):(e=null,_('"user="')),e!==null?(l.substr(r,5).toLowerCase()==="phone"?(o=l.substr(r,5),r+=5):(o=null,_('"phone"')),o===null&&(l.substr(r,2).toLowerCase()==="ip"?(o=l.substr(r,2),r+=2):(o=null,_('"ip"')),o===null&&(o=k())),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.uri_params||(O.uri_params={}),O.uri_params.user=m.toLowerCase()}(u,e[1])),e===null&&(r=u),e}function yr(){var e,o,u,f;return u=r,f=r,l.substr(r,7).toLowerCase()==="method="?(e=l.substr(r,7),r+=7):(e=null,_('"method="')),e!==null?(o=rn(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.uri_params||(O.uri_params={}),O.uri_params.method=m}(u,e[1])),e===null&&(r=u),e}function Cr(){var e,o,u,f;return u=r,f=r,l.substr(r,4).toLowerCase()==="ttl="?(e=l.substr(r,4),r+=4):(e=null,_('"ttl="')),e!==null?(o=Ci(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.params||(O.params={}),O.params.ttl=m}(u,e[1])),e===null&&(r=u),e}function Ar(){var e,o,u,f;return u=r,f=r,l.substr(r,6).toLowerCase()==="maddr="?(e=l.substr(r,6),r+=6):(e=null,_('"maddr="')),e!==null?(o=us(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.uri_params||(O.uri_params={}),O.uri_params.maddr=m}(u,e[1])),e===null&&(r=u),e}function Rr(){var e,o,u,f,p,m;return f=r,p=r,l.substr(r,2).toLowerCase()==="lr"?(e=l.substr(r,2),r+=2):(e=null,_('"lr"')),e!==null?(m=r,l.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){O.uri_params||(O.uri_params={}),O.uri_params.lr=void 0}()),e===null&&(r=f),e}function Ir(){var e,o,u,f,p,m;return f=r,p=r,e=br(),e!==null?(m=r,l.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o!==null?(u=Rs(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v,y,D){O.uri_params||(O.uri_params={}),typeof D>"u"?D=void 0:D=D[1],O.uri_params[y.toLowerCase()]=D}(f,e[0],e[1])),e===null&&(r=f),e}function br(){var e,o,u;if(u=r,o=Is(),o!==null)for(e=[];o!==null;)e.push(o),o=Is();else e=null;return e!==null&&(e=function(f,p){return p.join("")}(u,e)),e===null&&(r=u),e}function Rs(){var e,o,u;if(u=r,o=Is(),o!==null)for(e=[];o!==null;)e.push(o),o=Is();else e=null;return e!==null&&(e=function(f,p){return p.join("")}(u,e)),e===null&&(r=u),e}function Is(){var e;return e=wr(),e===null&&(e=H(),e===null&&(e=pe())),e}function wr(){var e;return l.charCodeAt(r)===91?(e="[",r++):(e=null,_('"["')),e===null&&(l.charCodeAt(r)===93?(e="]",r++):(e=null,_('"]"')),e===null&&(l.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e===null&&(l.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(l.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(l.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(l.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')))))))),e}function Xs(){var e,o,u,f,p,m,v;if(m=r,l.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e!==null)if(o=Qs(),o!==null){for(u=[],v=r,l.charCodeAt(r)===38?(f="&",r++):(f=null,_('"&"')),f!==null?(p=Qs(),p!==null?f=[f,p]:(f=null,r=v)):(f=null,r=v);f!==null;)u.push(f),v=r,l.charCodeAt(r)===38?(f="&",r++):(f=null,_('"&"')),f!==null?(p=Qs(),p!==null?f=[f,p]:(f=null,r=v)):(f=null,r=v);u!==null?e=[e,o,u]:(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e}function Qs(){var e,o,u,f,p;return f=r,p=r,e=Or(),e!==null?(l.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o!==null?(u=bs(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v,y){v=v.join("").toLowerCase(),y=y.join(""),O.uri_headers||(O.uri_headers={}),O.uri_headers[v]?O.uri_headers[v].push(y):O.uri_headers[v]=[y]}(f,e[0],e[2])),e===null&&(r=f),e}function Or(){var e,o;if(o=Zs(),o===null&&(o=H(),o===null&&(o=pe())),o!==null)for(e=[];o!==null;)e.push(o),o=Zs(),o===null&&(o=H(),o===null&&(o=pe()));else e=null;return e}function bs(){var e,o;for(e=[],o=Zs(),o===null&&(o=H(),o===null&&(o=pe()));o!==null;)e.push(o),o=Zs(),o===null&&(o=H(),o===null&&(o=pe()));return e}function Zs(){var e;return l.charCodeAt(r)===91?(e="[",r++):(e=null,_('"["')),e===null&&(l.charCodeAt(r)===93?(e="]",r++):(e=null,_('"]"')),e===null&&(l.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e===null&&(l.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(l.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(l.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(l.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')))))))),e}function ml(){var e;return e=Gr(),e===null&&(e=Dr()),e}function Dr(){var e,o,u,f,p,m;return m=r,e=rn(),e!==null?(o=V(),o!==null?(u=Un(),u!==null?(f=V(),f!==null?(p=Mn(),p!==null?e=[e,o,u,f,p]:(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m),e}function Un(){var e;return e=Ne(),e===null&&(e=kn()),e}function kn(){var e,o,u,f;return f=r,e=Ur(),e!==null?(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=Nr(),u===null&&(u=ws()),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Nr(){var e,o,u,f,p;return f=r,e=en(),e===null&&(e=tn()),e!==null?(p=r,l.charCodeAt(r)===63?(o="?",r++):(o=null,_('"?"')),o!==null?(u=Pn(),u!==null?o=[o,u]:(o=null,r=p)):(o=null,r=p),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e}function en(){var e,o,u,f;return f=r,l.substr(r,2)==="//"?(e="//",r+=2):(e=null,_('"//"')),e!==null?(o=kr(),o!==null?(u=tn(),u=u!==null?u:"",u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function tn(){var e,o,u;return u=r,l.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e!==null?(o=sn(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function ws(){var e,o,u,f;if(f=r,e=xr(),e!==null){for(o=[],u=Os();u!==null;)o.push(u),u=Os();o!==null?e=[e,o]:(e=null,r=f)}else e=null,r=f;return e}function Os(){var e;return e=x(),e===null&&(e=H(),e===null&&(e=pe())),e}function xr(){var e;return e=H(),e===null&&(e=pe(),e===null&&(l.charCodeAt(r)===59?(e=";",r++):(e=null,_('";"')),e===null&&(l.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(l.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(l.charCodeAt(r)===64?(e="@",r++):(e=null,_('"@"')),e===null&&(l.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(l.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(l.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(l.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')),e===null&&(l.charCodeAt(r)===44?(e=",",r++):(e=null,_('","')))))))))))),e}function sn(){var e,o,u,f,p,m;if(p=r,e=Ds(),e!==null){for(o=[],m=r,l.charCodeAt(r)===47?(u="/",r++):(u=null,_('"/"')),u!==null?(f=Ds(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,l.charCodeAt(r)===47?(u="/",r++):(u=null,_('"/"')),u!==null?(f=Ds(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Ds(){var e,o,u,f,p,m;for(p=r,e=[],o=Ns();o!==null;)e.push(o),o=Ns();if(e!==null){for(o=[],m=r,l.charCodeAt(r)===59?(u=";",r++):(u=null,_('";"')),u!==null?(f=cs(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,l.charCodeAt(r)===59?(u=";",r++):(u=null,_('";"')),u!==null?(f=cs(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function cs(){var e,o;for(e=[],o=Ns();o!==null;)e.push(o),o=Ns();return e}function Ns(){var e;return e=H(),e===null&&(e=pe(),e===null&&(l.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(l.charCodeAt(r)===64?(e="@",r++):(e=null,_('"@"')),e===null&&(l.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(l.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(l.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(l.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')),e===null&&(l.charCodeAt(r)===44?(e=",",r++):(e=null,_('","')))))))))),e}function Ur(){var e,o,u,f,p;if(f=r,p=r,e=S(),e!==null){for(o=[],u=S(),u===null&&(u=T(),u===null&&(l.charCodeAt(r)===43?(u="+",r++):(u=null,_('"+"')),u===null&&(l.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(l.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."'))))));u!==null;)o.push(u),u=S(),u===null&&(u=T(),u===null&&(l.charCodeAt(r)===43?(u="+",r++):(u=null,_('"+"')),u===null&&(l.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(l.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."'))))));o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e!==null&&(e=function(m){O.scheme=l.substring(r,m)}(f)),e===null&&(r=f),e}function kr(){var e;return e=Pr(),e===null&&(e=Mr()),e}function Pr(){var e,o,u,f;return u=r,f=r,e=ht(),e!==null?(l.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e=e!==null?e:"",e!==null?(o=es(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e=e!==null?e:"",e}function Mr(){var e,o;if(o=H(),o===null&&(o=pe(),o===null&&(l.charCodeAt(r)===36?(o="$",r++):(o=null,_('"$"')),o===null&&(l.charCodeAt(r)===44?(o=",",r++):(o=null,_('","')),o===null&&(l.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o===null&&(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o===null&&(l.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o===null&&(l.charCodeAt(r)===38?(o="&",r++):(o=null,_('"&"')),o===null&&(l.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"'))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=H(),o===null&&(o=pe(),o===null&&(l.charCodeAt(r)===36?(o="$",r++):(o=null,_('"$"')),o===null&&(l.charCodeAt(r)===44?(o=",",r++):(o=null,_('","')),o===null&&(l.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o===null&&(l.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o===null&&(l.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o===null&&(l.charCodeAt(r)===38?(o="&",r++):(o=null,_('"&"')),o===null&&(l.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o===null&&(l.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')))))))))));else e=null;return e}function Pn(){var e,o;for(e=[],o=Os();o!==null;)e.push(o),o=Os();return e}function Mn(){var e,o,u,f,p,m,v,y;if(v=r,y=r,l.substr(r,3).toLowerCase()==="sip"?(e=l.substr(r,3),r+=3):(e=null,_('"SIP"')),e!==null)if(l.charCodeAt(r)===47?(o="/",r++):(o=null,_('"/"')),o!==null){if(f=T(),f!==null)for(u=[];f!==null;)u.push(f),f=T();else u=null;if(u!==null)if(l.charCodeAt(r)===46?(f=".",r++):(f=null,_('"."')),f!==null){if(m=T(),m!==null)for(p=[];m!==null;)p.push(m),m=T();else p=null;p!==null?e=[e,o,u,f,p]:(e=null,r=y)}else e=null,r=y;else e=null,r=y}else e=null,r=y;else e=null,r=y;return e!==null&&(e=function(D){O.sip_version=l.substring(r,D)}(v)),e===null&&(r=v),e}function Lr(){var e;return l.substr(r,6)==="INVITE"?(e="INVITE",r+=6):(e=null,_('"INVITE"')),e}function $r(){var e;return l.substr(r,3)==="ACK"?(e="ACK",r+=3):(e=null,_('"ACK"')),e}function Hr(){var e;return l.substr(r,7)==="OPTIONS"?(e="OPTIONS",r+=7):(e=null,_('"OPTIONS"')),e}function Fr(){var e;return l.substr(r,3)==="BYE"?(e="BYE",r+=3):(e=null,_('"BYE"')),e}function Vr(){var e;return l.substr(r,6)==="CANCEL"?(e="CANCEL",r+=6):(e=null,_('"CANCEL"')),e}function jr(){var e;return l.substr(r,8)==="REGISTER"?(e="REGISTER",r+=8):(e=null,_('"REGISTER"')),e}function qr(){var e;return l.substr(r,9)==="SUBSCRIBE"?(e="SUBSCRIBE",r+=9):(e=null,_('"SUBSCRIBE"')),e}function Br(){var e;return l.substr(r,6)==="NOTIFY"?(e="NOTIFY",r+=6):(e=null,_('"NOTIFY"')),e}function nn(){var e;return l.substr(r,5)==="REFER"?(e="REFER",r+=5):(e=null,_('"REFER"')),e}function rn(){var e,o;return o=r,e=Lr(),e===null&&(e=$r(),e===null&&(e=Hr(),e===null&&(e=Fr(),e===null&&(e=Vr(),e===null&&(e=jr(),e===null&&(e=qr(),e===null&&(e=Br(),e===null&&(e=nn(),e===null&&(e=k()))))))))),e!==null&&(e=function(u){return O.method=l.substring(r,u),O.method}(o)),e===null&&(r=o),e}function Gr(){var e,o,u,f,p,m;return m=r,e=Mn(),e!==null?(o=V(),o!==null?(u=Wr(),u!==null?(f=V(),f!==null?(p=gl(),p!==null?e=[e,o,u,f,p]:(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m),e}function Wr(){var e,o;return o=r,e=Kr(),e!==null&&(e=function(u,f){O.status_code=parseInt(f.join(""))}(o,e)),e===null&&(r=o),e}function Kr(){var e,o,u,f;return f=r,e=T(),e!==null?(o=T(),o!==null?(u=T(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function gl(){var e,o,u;for(u=r,e=[],o=x(),o===null&&(o=H(),o===null&&(o=pe(),o===null&&(o=F(),o===null&&(o=X(),o===null&&(o=V(),o===null&&(o=w()))))));o!==null;)e.push(o),o=x(),o===null&&(o=H(),o===null&&(o=pe(),o===null&&(o=F(),o===null&&(o=X(),o===null&&(o=V(),o===null&&(o=w()))))));return e!==null&&(e=function(f){O.reason_phrase=l.substring(r,f)}(u)),e===null&&(r=u),e}function Jo(){var e,o,u,f,p,m;if(p=r,e=un(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=un(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=un(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function zo(){var e,o,u,f,p,m;return f=r,p=r,e=Q(),e!==null?(m=r,l.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o!==null?(u=Q(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){O=l.substring(r,v)}(f)),e===null&&(r=f),e}function Ln(){var e,o,u,f,p,m,v;if(p=r,e=W(),e===null)if(m=r,e=$t(),e!==null){for(o=[],v=r,u=oe(),u!==null?(f=$t(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=oe(),u!==null?(f=$t(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D,ie;for(ie=O.multi_header.length,D=0;D<ie;D++)if(O.multi_header[D].parsed===null){O=null;break}O!==null?O=O.multi_header:O=-1}()),e===null&&(r=p),e}function $t(){var e,o,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=Ht()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=$n(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=$n(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D;O.multi_header||(O.multi_header=[]);try{D=new b(O.uri,O.display_name,O.params),delete O.uri,delete O.display_name,delete O.params}catch{D=null}O.multi_header.push({possition:r,offset:y,parsed:D})}(p)),e===null&&(r=p),e}function Ht(){var e,o,u,f,p;return p=r,e=xs(),e=e!==null?e:"",e!==null?(o=Ae(),o!==null?(u=Ne(),u!==null?(f=ke(),f!==null?e=[e,o,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function xs(){var e,o,u,f,p,m,v;if(p=r,m=r,e=k(),e!==null){for(o=[],v=r,u=P(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=P(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e===null&&(e=ge()),e!==null&&(e=function(y,D){typeof D=="string"?O.display_name=D:O.display_name=D[1].reduce(function(ie,xe){return ie+xe[0]+xe[1]},D[0])}(p,e)),e===null&&(r=p),e}function $n(){var e;return e=Yr(),e===null&&(e=ts(),e===null&&(e=Ke())),e}function Yr(){var e,o,u,f,p;return f=r,p=r,l.substr(r,1).toLowerCase()==="q"?(e=l.substr(r,1),r++):(e=null,_('"q"')),e!==null?(o=re(),o!==null?(u=We(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.params||(O.params={}),O.params.q=v}(f,e[2])),e===null&&(r=f),e}function ts(){var e,o,u,f,p;return f=r,p=r,l.substr(r,7).toLowerCase()==="expires"?(e=l.substr(r,7),r+=7):(e=null,_('"expires"')),e!==null?(o=re(),o!==null?(u=ss(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.params||(O.params={}),O.params.expires=v}(f,e[2])),e===null&&(r=f),e}function ss(){var e,o,u;if(u=r,o=T(),o!==null)for(e=[];o!==null;)e.push(o),o=T();else e=null;return e!==null&&(e=function(f,p){return parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function We(){var e,o,u,f,p,m,v,y;return m=r,v=r,l.charCodeAt(r)===48?(e="0",r++):(e=null,_('"0"')),e!==null?(y=r,l.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o!==null?(u=T(),u=u!==null?u:"",u!==null?(f=T(),f=f!==null?f:"",f!==null?(p=T(),p=p!==null?p:"",p!==null?o=[o,u,f,p]:(o=null,r=y)):(o=null,r=y)):(o=null,r=y)):(o=null,r=y),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(D){return parseFloat(l.substring(r,D))}(m)),e===null&&(r=m),e}function Ke(){var e,o,u,f,p,m;return f=r,p=r,e=k(),e!==null?(m=r,o=re(),o!==null?(u=Tl(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v,y,D){O.params||(O.params={}),typeof D>"u"?D=void 0:D=D[1],O.params[y.toLowerCase()]=D}(f,e[0],e[1])),e===null&&(r=f),e}function Tl(){var e;return e=k(),e===null&&(e=us(),e===null&&(e=Oe())),e}function vl(){var e,o,u,f,p,m;if(p=r,e=Hn(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=Fn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=Fn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Hn(){var e;return l.substr(r,6).toLowerCase()==="render"?(e=l.substr(r,6),r+=6):(e=null,_('"render"')),e===null&&(l.substr(r,7).toLowerCase()==="session"?(e=l.substr(r,7),r+=7):(e=null,_('"session"')),e===null&&(l.substr(r,4).toLowerCase()==="icon"?(e=l.substr(r,4),r+=4):(e=null,_('"icon"')),e===null&&(l.substr(r,5).toLowerCase()==="alert"?(e=l.substr(r,5),r+=5):(e=null,_('"alert"')),e===null&&(e=k())))),e}function Fn(){var e;return e=Sl(),e===null&&(e=Ke()),e}function Sl(){var e,o,u,f;return f=r,l.substr(r,8).toLowerCase()==="handling"?(e=l.substr(r,8),r+=8):(e=null,_('"handling"')),e!==null?(o=re(),o!==null?(l.substr(r,8).toLowerCase()==="optional"?(u=l.substr(r,8),r+=8):(u=null,_('"optional"')),u===null&&(l.substr(r,8).toLowerCase()==="required"?(u=l.substr(r,8),r+=8):(u=null,_('"required"')),u===null&&(u=k())),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Xo(){var e,o,u,f,p,m;if(p=r,e=k(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Qo(){var e,o,u;if(u=r,o=T(),o!==null)for(e=[];o!==null;)e.push(o),o=T();else e=null;return e!==null&&(e=function(f,p){O=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function El(){var e,o;return o=r,e=Jr(),e!==null&&(e=function(u){O=l.substring(r,u)}(o)),e===null&&(r=o),e}function Jr(){var e,o,u,f,p,m,v,y;if(v=r,e=zr(),e!==null)if(o=G(),o!==null)if(u=Vn(),u!==null){for(f=[],y=r,p=ye(),p!==null?(m=jn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=ye(),p!==null?(m=jn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,o,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function zr(){var e;return e=Xr(),e===null&&(e=ln()),e}function Xr(){var e;return l.substr(r,4).toLowerCase()==="text"?(e=l.substr(r,4),r+=4):(e=null,_('"text"')),e===null&&(l.substr(r,5).toLowerCase()==="image"?(e=l.substr(r,5),r+=5):(e=null,_('"image"')),e===null&&(l.substr(r,5).toLowerCase()==="audio"?(e=l.substr(r,5),r+=5):(e=null,_('"audio"')),e===null&&(l.substr(r,5).toLowerCase()==="video"?(e=l.substr(r,5),r+=5):(e=null,_('"video"')),e===null&&(l.substr(r,11).toLowerCase()==="application"?(e=l.substr(r,11),r+=11):(e=null,_('"application"')),e===null&&(e=on()))))),e}function ln(){var e;return l.substr(r,7).toLowerCase()==="message"?(e=l.substr(r,7),r+=7):(e=null,_('"message"')),e===null&&(l.substr(r,9).toLowerCase()==="multipart"?(e=l.substr(r,9),r+=9):(e=null,_('"multipart"')),e===null&&(e=on())),e}function on(){var e;return e=k(),e===null&&(e=Qr()),e}function Qr(){var e,o,u;return u=r,l.substr(r,2).toLowerCase()==="x-"?(e=l.substr(r,2),r+=2):(e=null,_('"x-"')),e!==null?(o=k(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function Vn(){var e;return e=on(),e===null&&(e=k()),e}function jn(){var e,o,u,f;return f=r,e=k(),e!==null?(o=re(),o!==null?(u=yl(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function yl(){var e;return e=k(),e===null&&(e=Oe()),e}function Cl(){var e,o,u,f;return f=r,e=Al(),e!==null?(o=P(),o!==null?(u=rn(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Al(){var e,o,u;if(u=r,o=T(),o!==null)for(e=[];o!==null;)e.push(o),o=T();else e=null;return e!==null&&(e=function(f,p){O.value=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function Zo(){var e,o;return o=r,e=ss(),e!==null&&(e=function(u,f){O=f}(o,e)),e===null&&(r=o),e}function an(){var e,o,u,f,p,m,v;if(p=r,m=r,e=un(),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=Ke(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=Ke(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y,D){O.event=D.join("").toLowerCase()}(p,e[0])),e===null&&(r=p),e}function un(){var e,o,u,f,p,m;if(p=r,e=B(),e!==null){for(o=[],m=r,l.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u!==null?(f=B(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,l.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u!==null?(f=B(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Zr(){var e,o,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=Ht()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=cn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=cn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D=O.tag;try{O=new b(O.uri,O.display_name,O.params),D&&O.setParam("tag",D)}catch{O=-1}}()),e===null&&(r=p),e}function cn(){var e;return e=ei(),e===null&&(e=Ke()),e}function ei(){var e,o,u,f,p;return f=r,p=r,l.substr(r,3).toLowerCase()==="tag"?(e=l.substr(r,3),r+=3):(e=null,_('"tag"')),e!==null?(o=re(),o!==null?(u=k(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.tag=v}(f,e[2])),e===null&&(r=f),e}function ea(){var e,o,u;if(u=r,o=T(),o!==null)for(e=[];o!==null;)e.push(o),o=T();else e=null;return e!==null&&(e=function(f,p){O=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function ta(){var e,o;return o=r,e=ss(),e!==null&&(e=function(u,f){O=f}(o,e)),e===null&&(r=o),e}function sa(){var e,o,u,f,p,m,v,y,D,ie;for(y=r,D=r,e=[],o=xs();o!==null;)e.push(o),o=xs();if(e!==null)if(o=Ae(),o!==null)if(u=Ne(),u!==null)if(f=ke(),f!==null){for(p=[],ie=r,m=ye(),m!==null?(v=Ke(),v!==null?m=[m,v]:(m=null,r=ie)):(m=null,r=ie);m!==null;)p.push(m),ie=r,m=ye(),m!==null?(v=Ke(),v!==null?m=[m,v]:(m=null,r=ie)):(m=null,r=ie);p!==null?e=[e,o,u,f,p]:(e=null,r=D)}else e=null,r=D;else e=null,r=D;else e=null,r=D;else e=null,r=D;return e!==null&&(e=function(xe){try{O=new b(O.uri,O.display_name,O.params)}catch{O=-1}}()),e===null&&(r=y),e}function ti(){var e;return e=qn(),e}function qn(){var e,o,u,f,p,m,v,y;if(v=r,l.substr(r,6).toLowerCase()==="digest"?(e=l.substr(r,6),r+=6):(e=null,_('"Digest"')),e!==null)if(o=P(),o!==null)if(u=fn(),u!==null){for(f=[],y=r,p=oe(),p!==null?(m=fn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=oe(),p!==null?(m=fn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,o,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e===null&&(e=Us()),e}function Us(){var e,o,u,f,p,m,v,y;if(v=r,e=k(),e!==null)if(o=P(),o!==null)if(u=ns(),u!==null){for(f=[],y=r,p=oe(),p!==null?(m=ns(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=oe(),p!==null?(m=ns(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,o,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function ns(){var e,o,u,f;return f=r,e=k(),e!==null?(o=re(),o!==null?(u=k(),u===null&&(u=Oe()),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function fn(){var e;return e=si(),e===null&&(e=dn(),e===null&&(e=ri(),e===null&&(e=li(),e===null&&(e=oi(),e===null&&(e=ai(),e===null&&(e=_n(),e===null&&(e=ns()))))))),e}function si(){var e,o,u,f;return f=r,l.substr(r,5).toLowerCase()==="realm"?(e=l.substr(r,5),r+=5):(e=null,_('"realm"')),e!==null?(o=re(),o!==null?(u=ni(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function ni(){var e,o;return o=r,e=ge(),e!==null&&(e=function(u,f){O.realm=f}(o,e)),e===null&&(r=o),e}function dn(){var e,o,u,f,p,m,v,y,D;if(y=r,l.substr(r,6).toLowerCase()==="domain"?(e=l.substr(r,6),r+=6):(e=null,_('"domain"')),e!==null)if(o=re(),o!==null)if(u=ot(),u!==null)if(f=hn(),f!==null){if(p=[],D=r,v=V(),v!==null)for(m=[];v!==null;)m.push(v),v=V();else m=null;for(m!==null?(v=hn(),v!==null?m=[m,v]:(m=null,r=D)):(m=null,r=D);m!==null;){if(p.push(m),D=r,v=V(),v!==null)for(m=[];v!==null;)m.push(v),v=V();else m=null;m!==null?(v=hn(),v!==null?m=[m,v]:(m=null,r=D)):(m=null,r=D)}p!==null?(m=Ee(),m!==null?e=[e,o,u,f,p,m]:(e=null,r=y)):(e=null,r=y)}else e=null,r=y;else e=null,r=y;else e=null,r=y;else e=null,r=y;return e}function hn(){var e;return e=kn(),e===null&&(e=tn()),e}function ri(){var e,o,u,f;return f=r,l.substr(r,5).toLowerCase()==="nonce"?(e=l.substr(r,5),r+=5):(e=null,_('"nonce"')),e!==null?(o=re(),o!==null?(u=ii(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function ii(){var e,o;return o=r,e=ge(),e!==null&&(e=function(u,f){O.nonce=f}(o,e)),e===null&&(r=o),e}function li(){var e,o,u,f,p;return f=r,p=r,l.substr(r,6).toLowerCase()==="opaque"?(e=l.substr(r,6),r+=6):(e=null,_('"opaque"')),e!==null?(o=re(),o!==null?(u=ge(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.opaque=v}(f,e[2])),e===null&&(r=f),e}function oi(){var e,o,u,f,p;return f=r,l.substr(r,5).toLowerCase()==="stale"?(e=l.substr(r,5),r+=5):(e=null,_('"stale"')),e!==null?(o=re(),o!==null?(p=r,l.substr(r,4).toLowerCase()==="true"?(u=l.substr(r,4),r+=4):(u=null,_('"true"')),u!==null&&(u=function(m){O.stale=!0}()),u===null&&(r=p),u===null&&(p=r,l.substr(r,5).toLowerCase()==="false"?(u=l.substr(r,5),r+=5):(u=null,_('"false"')),u!==null&&(u=function(m){O.stale=!1}()),u===null&&(r=p)),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function ai(){var e,o,u,f,p;return f=r,p=r,l.substr(r,9).toLowerCase()==="algorithm"?(e=l.substr(r,9),r+=9):(e=null,_('"algorithm"')),e!==null?(o=re(),o!==null?(l.substr(r,3).toLowerCase()==="md5"?(u=l.substr(r,3),r+=3):(u=null,_('"MD5"')),u===null&&(l.substr(r,8).toLowerCase()==="md5-sess"?(u=l.substr(r,8),r+=8):(u=null,_('"MD5-sess"')),u===null&&(u=k())),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.algorithm=v.toUpperCase()}(f,e[2])),e===null&&(r=f),e}function _n(){var e,o,u,f,p,m,v,y,D,ie;if(y=r,l.substr(r,3).toLowerCase()==="qop"?(e=l.substr(r,3),r+=3):(e=null,_('"qop"')),e!==null)if(o=re(),o!==null)if(u=ot(),u!==null){if(D=r,f=Bn(),f!==null){for(p=[],ie=r,l.charCodeAt(r)===44?(m=",",r++):(m=null,_('","')),m!==null?(v=Bn(),v!==null?m=[m,v]:(m=null,r=ie)):(m=null,r=ie);m!==null;)p.push(m),ie=r,l.charCodeAt(r)===44?(m=",",r++):(m=null,_('","')),m!==null?(v=Bn(),v!==null?m=[m,v]:(m=null,r=ie)):(m=null,r=ie);p!==null?f=[f,p]:(f=null,r=D)}else f=null,r=D;f!==null?(p=Ee(),p!==null?e=[e,o,u,f,p]:(e=null,r=y)):(e=null,r=y)}else e=null,r=y;else e=null,r=y;else e=null,r=y;return e}function Bn(){var e,o;return o=r,l.substr(r,8).toLowerCase()==="auth-int"?(e=l.substr(r,8),r+=8):(e=null,_('"auth-int"')),e===null&&(l.substr(r,4).toLowerCase()==="auth"?(e=l.substr(r,4),r+=4):(e=null,_('"auth"')),e===null&&(e=k())),e!==null&&(e=function(u,f){O.qop||(O.qop=[]),O.qop.push(f.toLowerCase())}(o,e)),e===null&&(r=o),e}function na(){var e,o,u,f,p,m;if(p=r,e=k(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Gn(){var e,o,u,f,p,m,v;if(p=r,m=r,e=Wn(),e!==null){for(o=[],v=r,u=oe(),u!==null?(f=Wn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=oe(),u!==null?(f=Wn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D,ie;for(ie=O.multi_header.length,D=0;D<ie;D++)if(O.multi_header[D].parsed===null){O=null;break}O!==null?O=O.multi_header:O=-1}()),e===null&&(r=p),e}function Wn(){var e,o,u,f,p,m,v;if(p=r,m=r,e=Ht(),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=Ke(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=Ke(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D;O.multi_header||(O.multi_header=[]);try{D=new b(O.uri,O.display_name,O.params),delete O.uri,delete O.display_name,delete O.params}catch{D=null}O.multi_header.push({possition:r,offset:y,parsed:D})}(p)),e===null&&(r=p),e}function ui(){var e,o,u,f,p,m,v;if(p=r,m=r,l.substr(r,3).toLowerCase()==="sip"?(e=l.substr(r,3),r+=3):(e=null,_('"SIP"')),e===null&&(e=k()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=Kn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=Kn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y,D){if(O.protocol=D.toLowerCase(),O.params||(O.params={}),O.params.text&&O.params.text[0]==='"'){var ie=O.params.text;O.text=ie.substring(1,ie.length-1),delete O.params.text}}(p,e[0])),e===null&&(r=p),e}function Kn(){var e;return e=Rl(),e===null&&(e=Ke()),e}function Rl(){var e,o,u,f,p,m;if(p=r,m=r,l.substr(r,5).toLowerCase()==="cause"?(e=l.substr(r,5),r+=5):(e=null,_('"cause"')),e!==null)if(o=re(),o!==null){if(f=T(),f!==null)for(u=[];f!==null;)u.push(f),f=T();else u=null;u!==null?e=[e,o,u]:(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e!==null&&(e=function(v,y){O.cause=parseInt(y.join(""))}(p,e[2])),e===null&&(r=p),e}function ra(){var e,o,u,f,p,m;if(p=r,e=k(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Yn(){var e,o,u,f,p,m;if(p=r,e=Jn(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=Jn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=Jn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Jn(){var e,o,u,f,p,m;if(p=r,e=Ht(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=Ke(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=Ke(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Il(){var e,o,u,f,p,m;if(p=r,e=zn(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=Xn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=Xn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function zn(){var e,o;return o=r,l.substr(r,6).toLowerCase()==="active"?(e=l.substr(r,6),r+=6):(e=null,_('"active"')),e===null&&(l.substr(r,7).toLowerCase()==="pending"?(e=l.substr(r,7),r+=7):(e=null,_('"pending"')),e===null&&(l.substr(r,10).toLowerCase()==="terminated"?(e=l.substr(r,10),r+=10):(e=null,_('"terminated"')),e===null&&(e=k()))),e!==null&&(e=function(u){O.state=l.substring(r,u)}(o)),e===null&&(r=o),e}function Xn(){var e,o,u,f,p;return f=r,p=r,l.substr(r,6).toLowerCase()==="reason"?(e=l.substr(r,6),r+=6):(e=null,_('"reason"')),e!==null?(o=re(),o!==null?(u=bl(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){typeof v<"u"&&(O.reason=v)}(f,e[2])),e===null&&(r=f),e===null&&(f=r,p=r,l.substr(r,7).toLowerCase()==="expires"?(e=l.substr(r,7),r+=7):(e=null,_('"expires"')),e!==null?(o=re(),o!==null?(u=ss(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){typeof v<"u"&&(O.expires=v)}(f,e[2])),e===null&&(r=f),e===null&&(f=r,p=r,l.substr(r,11).toLowerCase()==="retry_after"?(e=l.substr(r,11),r+=11):(e=null,_('"retry_after"')),e!==null?(o=re(),o!==null?(u=ss(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){typeof v<"u"&&(O.retry_after=v)}(f,e[2])),e===null&&(r=f),e===null&&(e=Ke()))),e}function bl(){var e;return l.substr(r,11).toLowerCase()==="deactivated"?(e=l.substr(r,11),r+=11):(e=null,_('"deactivated"')),e===null&&(l.substr(r,9).toLowerCase()==="probation"?(e=l.substr(r,9),r+=9):(e=null,_('"probation"')),e===null&&(l.substr(r,8).toLowerCase()==="rejected"?(e=l.substr(r,8),r+=8):(e=null,_('"rejected"')),e===null&&(l.substr(r,7).toLowerCase()==="timeout"?(e=l.substr(r,7),r+=7):(e=null,_('"timeout"')),e===null&&(l.substr(r,6).toLowerCase()==="giveup"?(e=l.substr(r,6),r+=6):(e=null,_('"giveup"')),e===null&&(l.substr(r,10).toLowerCase()==="noresource"?(e=l.substr(r,10),r+=10):(e=null,_('"noresource"')),e===null&&(l.substr(r,9).toLowerCase()==="invariant"?(e=l.substr(r,9),r+=9):(e=null,_('"invariant"')),e===null&&(e=k()))))))),e}function ia(){var e;return e=j(),e=e!==null?e:"",e}function la(){var e,o,u,f,p,m;if(p=r,e=k(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=k(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e=e!==null?e:"",e}function ci(){var e,o,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=Ht()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=fi(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=fi(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D=O.tag;try{O=new b(O.uri,O.display_name,O.params),D&&O.setParam("tag",D)}catch{O=-1}}()),e===null&&(r=p),e}function fi(){var e;return e=ei(),e===null&&(e=Ke()),e}function Qn(){var e,o,u,f,p,m;if(p=r,e=ks(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=ks(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=ks(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function ks(){var e,o,u,f,p,m,v,y;if(v=r,e=Ti(),e!==null)if(o=P(),o!==null)if(u=Ei(),u!==null){for(f=[],y=r,p=ye(),p!==null?(m=Zn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=ye(),p!==null?(m=Zn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,o,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function Zn(){var e;return e=di(),e===null&&(e=hi(),e===null&&(e=_i(),e===null&&(e=pi(),e===null&&(e=mi(),e===null&&(e=Ke()))))),e}function di(){var e,o,u,f,p;return f=r,p=r,l.substr(r,3).toLowerCase()==="ttl"?(e=l.substr(r,3),r+=3):(e=null,_('"ttl"')),e!==null?(o=re(),o!==null?(u=Ci(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.ttl=v}(f,e[2])),e===null&&(r=f),e}function hi(){var e,o,u,f,p;return f=r,p=r,l.substr(r,5).toLowerCase()==="maddr"?(e=l.substr(r,5),r+=5):(e=null,_('"maddr"')),e!==null?(o=re(),o!==null?(u=us(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.maddr=v}(f,e[2])),e===null&&(r=f),e}function _i(){var e,o,u,f,p;return f=r,p=r,l.substr(r,8).toLowerCase()==="received"?(e=l.substr(r,8),r+=8):(e=null,_('"received"')),e!==null?(o=re(),o!==null?(u=Wt(),u===null&&(u=Te()),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.received=v}(f,e[2])),e===null&&(r=f),e}function pi(){var e,o,u,f,p;return f=r,p=r,l.substr(r,6).toLowerCase()==="branch"?(e=l.substr(r,6),r+=6):(e=null,_('"branch"')),e!==null?(o=re(),o!==null?(u=k(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.branch=v}(f,e[2])),e===null&&(r=f),e}function mi(){var e,o,u,f,p;return f=r,l.substr(r,5).toLowerCase()==="rport"?(e=l.substr(r,5),r+=5):(e=null,_('"rport"')),e!==null?(p=r,o=re(),o!==null?(u=gi(),u!==null?o=[o,u]:(o=null,r=p)):(o=null,r=p),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e}function gi(){var e,o,u,f,p,m,v;return m=r,v=r,e=T(),e=e!==null?e:"",e!==null?(o=T(),o=o!==null?o:"",o!==null?(u=T(),u=u!==null?u:"",u!==null?(f=T(),f=f!==null?f:"",f!==null?(p=T(),p=p!==null?p:"",p!==null?e=[e,o,u,f,p]:(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(y,D){O.rport=parseInt(D.join(""))}(m,e)),e===null&&(r=m),e}function Ti(){var e,o,u,f,p,m;return m=r,e=vi(),e!==null?(o=G(),o!==null?(u=k(),u!==null?(f=G(),f!==null?(p=Si(),p!==null?e=[e,o,u,f,p]:(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m),e}function vi(){var e,o;return o=r,l.substr(r,3).toLowerCase()==="sip"?(e=l.substr(r,3),r+=3):(e=null,_('"SIP"')),e===null&&(e=k()),e!==null&&(e=function(u,f){O.protocol=f}(o,e)),e===null&&(r=o),e}function Si(){var e,o;return o=r,l.substr(r,3).toLowerCase()==="udp"?(e=l.substr(r,3),r+=3):(e=null,_('"UDP"')),e===null&&(l.substr(r,3).toLowerCase()==="tcp"?(e=l.substr(r,3),r+=3):(e=null,_('"TCP"')),e===null&&(l.substr(r,3).toLowerCase()==="tls"?(e=l.substr(r,3),r+=3):(e=null,_('"TLS"')),e===null&&(l.substr(r,4).toLowerCase()==="sctp"?(e=l.substr(r,4),r+=4):(e=null,_('"SCTP"')),e===null&&(e=k())))),e!==null&&(e=function(u,f){O.transport=f}(o,e)),e===null&&(r=o),e}function Ei(){var e,o,u,f,p;return f=r,e=yi(),e!==null?(p=r,o=nt(),o!==null?(u=er(),u!==null?o=[o,u]:(o=null,r=p)):(o=null,r=p),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e}function yi(){var e,o;return o=r,e=Wt(),e===null&&(e=zs(),e===null&&(e=Js())),e!==null&&(e=function(u){O.host=l.substring(r,u)}(o)),e===null&&(r=o),e}function er(){var e,o,u,f,p,m,v;return m=r,v=r,e=T(),e=e!==null?e:"",e!==null?(o=T(),o=o!==null?o:"",o!==null?(u=T(),u=u!==null?u:"",u!==null?(f=T(),f=f!==null?f:"",f!==null?(p=T(),p=p!==null?p:"",p!==null?e=[e,o,u,f,p]:(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(y,D){O.port=parseInt(D.join(""))}(m,e)),e===null&&(r=m),e}function Ci(){var e,o,u,f,p;return f=r,p=r,e=T(),e!==null?(o=T(),o=o!==null?o:"",o!==null?(u=T(),u=u!==null?u:"",u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){return parseInt(v.join(""))}(f,e)),e===null&&(r=f),e}function oa(){var e;return e=qn(),e}function wl(){var e,o,u,f,p,m;if(p=r,e=tr(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=sr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=sr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function tr(){var e,o;return o=r,e=ss(),e!==null&&(e=function(u,f){O.expires=f}(o,e)),e===null&&(r=o),e}function sr(){var e;return e=Ol(),e===null&&(e=Ke()),e}function Ol(){var e,o,u,f,p;return f=r,p=r,l.substr(r,9).toLowerCase()==="refresher"?(e=l.substr(r,9),r+=9):(e=null,_('"refresher"')),e!==null?(o=re(),o!==null?(l.substr(r,3).toLowerCase()==="uac"?(u=l.substr(r,3),r+=3):(u=null,_('"uac"')),u===null&&(l.substr(r,3).toLowerCase()==="uas"?(u=l.substr(r,3),r+=3):(u=null,_('"uas"'))),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.refresher=v.toLowerCase()}(f,e[2])),e===null&&(r=f),e}function Dl(){var e,o,u,f;return f=r,e=k(),e!==null?(o=q(),o!==null?(u=Nl(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Nl(){var e,o;for(e=[],o=Y(),o===null&&(o=X(),o===null&&(o=P()));o!==null;)e.push(o),o=Y(),o===null&&(o=X(),o===null&&(o=P()));return e}function aa(){var e,o;for(e=[],o=A();o!==null;)e.push(o),o=A();return e}function xl(){var e,o,u;return u=r,l.substr(r,5)==="uuid:"?(e="uuid:",r+=5):(e=null,_('"uuid:"')),e!==null?(o=Ft(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function Ft(){var e,o,u,f,p,m,v,y,D,ie,xe;return ie=r,xe=r,e=Ai(),e!==null?(l.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o!==null?(u=Vt(),u!==null?(l.charCodeAt(r)===45?(f="-",r++):(f=null,_('"-"')),f!==null?(p=Vt(),p!==null?(l.charCodeAt(r)===45?(m="-",r++):(m=null,_('"-"')),m!==null?(v=Vt(),v!==null?(l.charCodeAt(r)===45?(y="-",r++):(y=null,_('"-"')),y!==null?(D=Ul(),D!==null?e=[e,o,u,f,p,m,v,y,D]:(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe),e!==null&&(e=function(wt,Ps){O=l.substring(r+5,wt)}(ie,e[0])),e===null&&(r=ie),e}function Vt(){var e,o,u,f,p;return p=r,e=E(),e!==null?(o=E(),o!==null?(u=E(),u!==null?(f=E(),f!==null?e=[e,o,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function Ai(){var e,o,u;return u=r,e=Vt(),e!==null?(o=Vt(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function Ul(){var e,o,u,f;return f=r,e=Vt(),e!==null?(o=Vt(),o!==null?(u=Vt(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function ua(){var e,o,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=Ht()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=Ke(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=Ke(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){try{O=new b(O.uri,O.display_name,O.params)}catch{O=-1}}()),e===null&&(r=p),e}function kl(){var e,o,u,f,p,m;if(p=r,e=nr(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=rr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=rr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function nr(){var e,o,u,f,p,m;return f=r,p=r,e=Q(),e!==null?(m=r,l.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o!==null?(u=Q(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){O.call_id=l.substring(r,v)}(f)),e===null&&(r=f),e}function rr(){var e;return e=Ri(),e===null&&(e=Ii(),e===null&&(e=Pl(),e===null&&(e=Ke()))),e}function Ri(){var e,o,u,f,p;return f=r,p=r,l.substr(r,6)==="to-tag"?(e="to-tag",r+=6):(e=null,_('"to-tag"')),e!==null?(o=re(),o!==null?(u=k(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.to_tag=v}(f,e[2])),e===null&&(r=f),e}function Ii(){var e,o,u,f,p;return f=r,p=r,l.substr(r,8)==="from-tag"?(e="from-tag",r+=8):(e=null,_('"from-tag"')),e!==null?(o=re(),o!==null?(u=k(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.from_tag=v}(f,e[2])),e===null&&(r=f),e}function Pl(){var e,o;return o=r,l.substr(r,10)==="early-only"?(e="early-only",r+=10):(e=null,_('"early-only"')),e!==null&&(e=function(u){O.early_only=!0}()),e===null&&(r=o),e}function ca(e){e.sort();for(var o=null,u=[],f=0;f<e.length;f++)e[f]!==o&&(u.push(e[f]),o=e[f]);return u}function Ml(){for(var e=1,o=1,u=!1,f=0;f<Math.max(r,h);f++){var p=l.charAt(f);p===`
|
|
4
|
-
`?(u||e++,o=1,u=!1):p==="\r"||p==="\u2028"||p==="\u2029"?(e++,o=1,u=!0):(o++,u=!1)}return{line:e,column:o}}var
|
|
5
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var C=!0,A=!1,R;return{s:function(){T=_[Symbol.iterator]()},n:function(){var
|
|
6
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var A=!0,R=!1,V;return{s:function(){S=g[Symbol.iterator]()},n:function(){var le=S.next();return A=le.done,le},e:function(le){R=!0,V=le},f:function(){try{!A&&S.return!=null&&S.return()}finally{if(R)throw V}}}}function n(g,T){if(g){if(typeof g=="string")return l(g,T);var S=Object.prototype.toString.call(g).slice(8,-1);if(S==="Object"&&g.constructor&&(S=g.constructor.name),S==="Map"||S==="Set")return Array.from(g);if(S==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(S))return l(g,T)}}function l(g,T){(T==null||T>g.length)&&(T=g.length);for(var S=0,E=new Array(T);S<T;S++)E[S]=g[S];return E}var a=lt,s=Ks(),r=as();et.str_utf8_length=function(g){return unescape(encodeURIComponent(g)).length};var h=et.isFunction=function(g){return g!==void 0?Object.prototype.toString.call(g)==="[object Function]":!1};et.isString=function(g){return g!==void 0?Object.prototype.toString.call(g)==="[object String]":!1},et.isDecimal=function(g){return!isNaN(g)&&parseFloat(g)===parseInt(g,10)},et.isEmpty=function(g){return g===null||g===""||g===void 0||Array.isArray(g)&&g.length===0||typeof g=="number"&&isNaN(g)},et.hasMethods=function(g){for(var T=arguments.length,S=new Array(T>1?T-1:0),E=1;E<T;E++)S[E-1]=arguments[E];for(var C=0,A=S;C<A.length;C++){var R=A[C];if(h(g[R]))return!1}return!0};var d=et.createRandomToken=function(g){var T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:32,S,E,C="";for(S=0;S<g;S++)E=Math.random()*T|0,C+=E.toString(T);return C};et.newTag=function(){return d(10)},et.newUUID=function(){var g="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(T){var S=Math.random()*16|0,E=T==="x"?S:S&3|8;return E.toString(16)});return g},et.hostType=function(g){if(g){if(g=r.parse(g,"host"),g!==-1)return g.host_type}else return};var _=et.escapeUser=function(g){return encodeURIComponent(decodeURIComponent(g)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/")};return et.normalizeTarget=function(g,T){if(g){if(g instanceof s)return g;if(typeof g=="string"){var S=g.split("@"),E,C;switch(S.length){case 1:if(!T)return;E=g,C=T;break;case 2:E=S[0],C=S[1];break;default:E=S.slice(0,S.length-1).join("@"),C=S[S.length-1]}E=E.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(E)&&(E=E.replace(/[-.()]/g,"")),g="".concat(a.SIP,":").concat(_(E),"@").concat(C);var A;return(A=s.parse(g))?A:void 0}else return}else return},et.headerize=function(g){var T={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},S=g.toLowerCase().replace(/_/g,"-").split("-"),E="",C=S.length,A;for(A=0;A<C;A++)A!==0&&(E+="-"),E+=S[A].charAt(0).toUpperCase()+S[A].substring(1);return T[E]&&(E=T[E]),E},et.sipErrorCause=function(g){for(var T in a.SIP_ERROR_CAUSES)if(a.SIP_ERROR_CAUSES[T].indexOf(g)!==-1)return a.causes[T];return a.causes.SIP_FAILURE_CODE},et.getRandomTestNetIP=function(){function g(T,S){return Math.floor(Math.random()*(S-T+1)+T)}return"192.0.2.".concat(g(1,254))},et.calculateMD5=function(g){function T(ge,ue){return ge<<ue|ge>>>32-ue}function S(ge,ue){var me=ge&2147483648,we=ue&2147483648,Ne=ge&1073741824,Ze=ue&1073741824,Le=(ge&1073741823)+(ue&1073741823);return Ne&Ze?Le^2147483648^me^we:Ne|Ze?Le&1073741824?Le^3221225472^me^we:Le^1073741824^me^we:Le^me^we}function E(ge,ue,me){return ge&ue|~ge&me}function C(ge,ue,me){return ge&me|ue&~me}function A(ge,ue,me){return ge^ue^me}function R(ge,ue,me){return ue^(ge|~me)}function V(ge,ue,me,we,Ne,Ze,Le){return ge=S(ge,S(S(E(ue,me,we),Ne),Le)),S(T(ge,Ze),ue)}function w(ge,ue,me,we,Ne,Ze,Le){return ge=S(ge,S(S(C(ue,me,we),Ne),Le)),S(T(ge,Ze),ue)}function le(ge,ue,me,we,Ne,Ze,Le){return ge=S(ge,S(S(A(ue,me,we),Ne),Le)),S(T(ge,Ze),ue)}function x(ge,ue,me,we,Ne,Ze,Le){return ge=S(ge,S(S(R(ue,me,we),Ne),Le)),S(T(ge,Ze),ue)}function H(ge){for(var ue,me=ge.length,we=me+8,Ne=(we-we%64)/64,Ze=(Ne+1)*16,Le=new Array(Ze-1),Lt=0,ht=0;ht<me;)ue=(ht-ht%4)/4,Lt=ht%4*8,Le[ue]=Le[ue]|ge.charCodeAt(ht)<<Lt,ht++;return ue=(ht-ht%4)/4,Lt=ht%4*8,Le[ue]=Le[ue]|128<<Lt,Le[Ze-2]=me<<3,Le[Ze-1]=me>>>29,Le}function ve(ge){var ue="",me="",we,Ne;for(Ne=0;Ne<=3;Ne++)we=ge>>>Ne*8&255,me="0".concat(we.toString(16)),ue=ue+me.substr(me.length-2,2);return ue}function pe(ge){for(var ue="",me=0;me<ge.length;me++){var we=ge.charCodeAt(me);we<128?ue+=String.fromCharCode(we):we>127&&we<2048?(ue+=String.fromCharCode(we>>6|192),ue+=String.fromCharCode(we&63|128)):(ue+=String.fromCharCode(we>>12|224),ue+=String.fromCharCode(we>>6&63|128),ue+=String.fromCharCode(we&63|128))}return ue}var P=[],N,q,j,Y,F,X,U,k,B,He=7,Q=12,W=17,G=22,re=5,_e=9,Ie=14,ke=20,Ae=4,oe=11,ye=16,nt=23,ot=6,Ee=10,Ce=15,be=21;for(g=pe(g),P=H(g),X=1732584193,U=4023233417,k=2562383102,B=271733878,N=0;N<P.length;N+=16)q=X,j=U,Y=k,F=B,X=V(X,U,k,B,P[N+0],He,3614090360),B=V(B,X,U,k,P[N+1],Q,3905402710),k=V(k,B,X,U,P[N+2],W,606105819),U=V(U,k,B,X,P[N+3],G,3250441966),X=V(X,U,k,B,P[N+4],He,4118548399),B=V(B,X,U,k,P[N+5],Q,1200080426),k=V(k,B,X,U,P[N+6],W,2821735955),U=V(U,k,B,X,P[N+7],G,4249261313),X=V(X,U,k,B,P[N+8],He,1770035416),B=V(B,X,U,k,P[N+9],Q,2336552879),k=V(k,B,X,U,P[N+10],W,4294925233),U=V(U,k,B,X,P[N+11],G,2304563134),X=V(X,U,k,B,P[N+12],He,1804603682),B=V(B,X,U,k,P[N+13],Q,4254626195),k=V(k,B,X,U,P[N+14],W,2792965006),U=V(U,k,B,X,P[N+15],G,1236535329),X=w(X,U,k,B,P[N+1],re,4129170786),B=w(B,X,U,k,P[N+6],_e,3225465664),k=w(k,B,X,U,P[N+11],Ie,643717713),U=w(U,k,B,X,P[N+0],ke,3921069994),X=w(X,U,k,B,P[N+5],re,3593408605),B=w(B,X,U,k,P[N+10],_e,38016083),k=w(k,B,X,U,P[N+15],Ie,3634488961),U=w(U,k,B,X,P[N+4],ke,3889429448),X=w(X,U,k,B,P[N+9],re,568446438),B=w(B,X,U,k,P[N+14],_e,3275163606),k=w(k,B,X,U,P[N+3],Ie,4107603335),U=w(U,k,B,X,P[N+8],ke,1163531501),X=w(X,U,k,B,P[N+13],re,2850285829),B=w(B,X,U,k,P[N+2],_e,4243563512),k=w(k,B,X,U,P[N+7],Ie,1735328473),U=w(U,k,B,X,P[N+12],ke,2368359562),X=le(X,U,k,B,P[N+5],Ae,4294588738),B=le(B,X,U,k,P[N+8],oe,2272392833),k=le(k,B,X,U,P[N+11],ye,1839030562),U=le(U,k,B,X,P[N+14],nt,4259657740),X=le(X,U,k,B,P[N+1],Ae,2763975236),B=le(B,X,U,k,P[N+4],oe,1272893353),k=le(k,B,X,U,P[N+7],ye,4139469664),U=le(U,k,B,X,P[N+10],nt,3200236656),X=le(X,U,k,B,P[N+13],Ae,681279174),B=le(B,X,U,k,P[N+0],oe,3936430074),k=le(k,B,X,U,P[N+3],ye,3572445317),U=le(U,k,B,X,P[N+6],nt,76029189),X=le(X,U,k,B,P[N+9],Ae,3654602809),B=le(B,X,U,k,P[N+12],oe,3873151461),k=le(k,B,X,U,P[N+15],ye,530742520),U=le(U,k,B,X,P[N+2],nt,3299628645),X=x(X,U,k,B,P[N+0],ot,4096336452),B=x(B,X,U,k,P[N+7],Ee,1126891415),k=x(k,B,X,U,P[N+14],Ce,2878612391),U=x(U,k,B,X,P[N+5],be,4237533241),X=x(X,U,k,B,P[N+12],ot,1700485571),B=x(B,X,U,k,P[N+3],Ee,2399980690),k=x(k,B,X,U,P[N+10],Ce,4293915773),U=x(U,k,B,X,P[N+1],be,2240044497),X=x(X,U,k,B,P[N+8],ot,1873313359),B=x(B,X,U,k,P[N+15],Ee,4264355552),k=x(k,B,X,U,P[N+6],Ce,2734768916),U=x(U,k,B,X,P[N+13],be,1309151649),X=x(X,U,k,B,P[N+4],ot,4149444226),B=x(B,X,U,k,P[N+11],Ee,3174756917),k=x(k,B,X,U,P[N+2],Ce,718787259),U=x(U,k,B,X,P[N+9],be,3951481745),X=S(X,q),U=S(U,j),k=S(k,Y),B=S(B,F);var Oe=ve(X)+ve(U)+ve(k)+ve(B);return Oe.toLowerCase()},et.closeMediaStream=function(g){if(g)try{var T;if(g.getTracks){T=g.getTracks();var S=t(T),E;try{for(S.s();!(E=S.n()).done;){var C=E.value;C.stop()}}catch(H){S.e(H)}finally{S.f()}}else{T=g.getAudioTracks();var A=t(T),R;try{for(A.s();!(R=A.n()).done;){var V=R.value;V.stop()}}catch(H){A.e(H)}finally{A.f()}T=g.getVideoTracks();var w=t(T),le;try{for(w.s();!(le=w.n()).done;){var x=le.value;x.stop()}}catch(H){w.e(H)}finally{w.f()}}}catch{(typeof g.stop=="function"||c(g.stop)==="object")&&g.stop()}},et.cloneArray=function(g){return g&&g.slice()||[]},et.cloneObject=function(g){var T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return g&&Object.assign({},g)||T},et}var xu={exports:{}},hr=typeof Reflect=="object"?Reflect:null,Qu=hr&&typeof hr.apply=="function"?hr.apply:function(t,n,l){return Function.prototype.apply.call(t,n,l)},To;hr&&typeof hr.ownKeys=="function"?To=hr.ownKeys:Object.getOwnPropertySymbols?To=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:To=function(t){return Object.getOwnPropertyNames(t)};function hh(c){console&&console.warn&&console.warn(c)}var Wf=Number.isNaN||function(t){return t!==t};function Me(){Me.init.call(this)}xu.exports=Me;xu.exports.once=gh;Me.EventEmitter=Me;Me.prototype._events=void 0;Me.prototype._eventsCount=0;Me.prototype._maxListeners=void 0;var Zu=10;function Bo(c){if(typeof c!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof c)}Object.defineProperty(Me,"defaultMaxListeners",{enumerable:!0,get:function(){return Zu},set:function(c){if(typeof c!="number"||c<0||Wf(c))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+c+".");Zu=c}});Me.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Me.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Wf(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Kf(c){return c._maxListeners===void 0?Me.defaultMaxListeners:c._maxListeners}Me.prototype.getMaxListeners=function(){return Kf(this)};Me.prototype.emit=function(t){for(var n=[],l=1;l<arguments.length;l++)n.push(arguments[l]);var a=t==="error",s=this._events;if(s!==void 0)a=a&&s.error===void 0;else if(!a)return!1;if(a){var r;if(n.length>0&&(r=n[0]),r instanceof Error)throw r;var h=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw h.context=r,h}var d=s[t];if(d===void 0)return!1;if(typeof d=="function")Qu(d,this,n);else for(var _=d.length,g=Qf(d,_),l=0;l<_;++l)Qu(g[l],this,n);return!0};function Yf(c,t,n,l){var a,s,r;if(Bo(n),s=c._events,s===void 0?(s=c._events=Object.create(null),c._eventsCount=0):(s.newListener!==void 0&&(c.emit("newListener",t,n.listener?n.listener:n),s=c._events),r=s[t]),r===void 0)r=s[t]=n,++c._eventsCount;else if(typeof r=="function"?r=s[t]=l?[n,r]:[r,n]:l?r.unshift(n):r.push(n),a=Kf(c),a>0&&r.length>a&&!r.warned){r.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=c,h.type=t,h.count=r.length,hh(h)}return c}Me.prototype.addListener=function(t,n){return Yf(this,t,n,!1)};Me.prototype.on=Me.prototype.addListener;Me.prototype.prependListener=function(t,n){return Yf(this,t,n,!0)};function _h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Jf(c,t,n){var l={fired:!1,wrapFn:void 0,target:c,type:t,listener:n},a=_h.bind(l);return a.listener=n,l.wrapFn=a,a}Me.prototype.once=function(t,n){return Bo(n),this.on(t,Jf(this,t,n)),this};Me.prototype.prependOnceListener=function(t,n){return Bo(n),this.prependListener(t,Jf(this,t,n)),this};Me.prototype.removeListener=function(t,n){var l,a,s,r,h;if(Bo(n),a=this._events,a===void 0)return this;if(l=a[t],l===void 0)return this;if(l===n||l.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete a[t],a.removeListener&&this.emit("removeListener",t,l.listener||n));else if(typeof l!="function"){for(s=-1,r=l.length-1;r>=0;r--)if(l[r]===n||l[r].listener===n){h=l[r].listener,s=r;break}if(s<0)return this;s===0?l.shift():ph(l,s),l.length===1&&(a[t]=l[0]),a.removeListener!==void 0&&this.emit("removeListener",t,h||n)}return this};Me.prototype.off=Me.prototype.removeListener;Me.prototype.removeAllListeners=function(t){var n,l,a;if(l=this._events,l===void 0)return this;if(l.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):l[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete l[t]),this;if(arguments.length===0){var s=Object.keys(l),r;for(a=0;a<s.length;++a)r=s[a],r!=="removeListener"&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=l[t],typeof n=="function")this.removeListener(t,n);else if(n!==void 0)for(a=n.length-1;a>=0;a--)this.removeListener(t,n[a]);return this};function zf(c,t,n){var l=c._events;if(l===void 0)return[];var a=l[t];return a===void 0?[]:typeof a=="function"?n?[a.listener||a]:[a]:n?mh(a):Qf(a,a.length)}Me.prototype.listeners=function(t){return zf(this,t,!0)};Me.prototype.rawListeners=function(t){return zf(this,t,!1)};Me.listenerCount=function(c,t){return typeof c.listenerCount=="function"?c.listenerCount(t):Xf.call(c,t)};Me.prototype.listenerCount=Xf;function Xf(c){var t=this._events;if(t!==void 0){var n=t[c];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}Me.prototype.eventNames=function(){return this._eventsCount>0?To(this._events):[]};function Qf(c,t){for(var n=new Array(t),l=0;l<t;++l)n[l]=c[l];return n}function ph(c,t){for(;t+1<c.length;t++)c[t]=c[t+1];c.pop()}function mh(c){for(var t=new Array(c.length),n=0;n<t.length;++n)t[n]=c[n].listener||c[n];return t}function gh(c,t){return new Promise(function(n,l){function a(r){c.removeListener(t,s),l(r)}function s(){typeof c.removeListener=="function"&&c.removeListener("error",a),n([].slice.call(arguments))}Zf(c,t,s,{once:!0}),t!=="error"&&Th(c,a,{once:!0})})}function Th(c,t,n){typeof c.on=="function"&&Zf(c,"error",t,n)}function Zf(c,t,n,l){if(typeof c.on=="function")l.once?c.once(t,n):c.on(t,n);else if(typeof c.addEventListener=="function")c.addEventListener(t,function a(s){l.once&&c.removeEventListener(t,a),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof c)}var ft=xu.exports,fu={exports:{}},_a,ec;function vh(){if(ec)return _a;ec=1;var c=1e3,t=c*60,n=t*60,l=n*24,a=l*7,s=l*365.25;_a=function(g,T){T=T||{};var S=typeof g;if(S==="string"&&g.length>0)return r(g);if(S==="number"&&isFinite(g))return T.long?d(g):h(g);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(g))};function r(g){if(g=String(g),!(g.length>100)){var T=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(g);if(T){var S=parseFloat(T[1]),E=(T[2]||"ms").toLowerCase();switch(E){case"years":case"year":case"yrs":case"yr":case"y":return S*s;case"weeks":case"week":case"w":return S*a;case"days":case"day":case"d":return S*l;case"hours":case"hour":case"hrs":case"hr":case"h":return S*n;case"minutes":case"minute":case"mins":case"min":case"m":return S*t;case"seconds":case"second":case"secs":case"sec":case"s":return S*c;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return S;default:return}}}}function h(g){var T=Math.abs(g);return T>=l?Math.round(g/l)+"d":T>=n?Math.round(g/n)+"h":T>=t?Math.round(g/t)+"m":T>=c?Math.round(g/c)+"s":g+"ms"}function d(g){var T=Math.abs(g);return T>=l?_(g,T,l,"day"):T>=n?_(g,T,n,"hour"):T>=t?_(g,T,t,"minute"):T>=c?_(g,T,c,"second"):g+" ms"}function _(g,T,S,E){var C=T>=S*1.5;return Math.round(g/S)+" "+E+(C?"s":"")}return _a}function Sh(c){n.debug=n,n.default=n,n.coerce=d,n.disable=s,n.enable=a,n.enabled=r,n.humanize=vh(),n.destroy=_,Object.keys(c).forEach(g=>{n[g]=c[g]}),n.names=[],n.skips=[],n.formatters={};function t(g){let T=0;for(let S=0;S<g.length;S++)T=(T<<5)-T+g.charCodeAt(S),T|=0;return n.colors[Math.abs(T)%n.colors.length]}n.selectColor=t;function n(g){let T,S=null,E,C;function A(...R){if(!A.enabled)return;const V=A,w=Number(new Date),le=w-(T||w);V.diff=le,V.prev=T,V.curr=w,T=w,R[0]=n.coerce(R[0]),typeof R[0]!="string"&&R.unshift("%O");let x=0;R[0]=R[0].replace(/%([a-zA-Z%])/g,(ve,pe)=>{if(ve==="%%")return"%";x++;const P=n.formatters[pe];if(typeof P=="function"){const N=R[x];ve=P.call(V,N),R.splice(x,1),x--}return ve}),n.formatArgs.call(V,R),(V.log||n.log).apply(V,R)}return A.namespace=g,A.useColors=n.useColors(),A.color=n.selectColor(g),A.extend=l,A.destroy=n.destroy,Object.defineProperty(A,"enabled",{enumerable:!0,configurable:!1,get:()=>S!==null?S:(E!==n.namespaces&&(E=n.namespaces,C=n.enabled(g)),C),set:R=>{S=R}}),typeof n.init=="function"&&n.init(A),A}function l(g,T){const S=n(this.namespace+(typeof T>"u"?":":T)+g);return S.log=this.log,S}function a(g){n.save(g),n.namespaces=g,n.names=[],n.skips=[];let T;const S=(typeof g=="string"?g:"").split(/[\s,]+/),E=S.length;for(T=0;T<E;T++)S[T]&&(g=S[T].replace(/\*/g,".*?"),g[0]==="-"?n.skips.push(new RegExp("^"+g.slice(1)+"$")):n.names.push(new RegExp("^"+g+"$")))}function s(){const g=[...n.names.map(h),...n.skips.map(h).map(T=>"-"+T)].join(",");return n.enable(""),g}function r(g){if(g[g.length-1]==="*")return!0;let T,S;for(T=0,S=n.skips.length;T<S;T++)if(n.skips[T].test(g))return!1;for(T=0,S=n.names.length;T<S;T++)if(n.names[T].test(g))return!0;return!1}function h(g){return g.toString().substring(2,g.toString().length-2).replace(/\.\*\?$/,"*")}function d(g){return g instanceof Error?g.stack||g.message:g}function _(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}var Eh=Sh;(function(c,t){t.formatArgs=l,t.save=a,t.load=s,t.useColors=n,t.storage=r(),t.destroy=(()=>{let d=!1;return()=>{d||(d=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function n(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function l(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+c.exports.humanize(this.diff),!this.useColors)return;const _="color: "+this.color;d.splice(1,0,_,"color: inherit");let g=0,T=0;d[0].replace(/%[a-zA-Z%]/g,S=>{S!=="%%"&&(g++,S==="%c"&&(T=g))}),d.splice(T,0,_)}t.log=console.debug||console.log||(()=>{});function a(d){try{d?t.storage.setItem("debug",d):t.storage.removeItem("debug")}catch{}}function s(){let d;try{d=t.storage.getItem("debug")}catch{}return!d&&typeof process<"u"&&"env"in process&&(d=process.env.DEBUG),d}function r(){try{return localStorage}catch{}}c.exports=Eh(t);const{formatters:h}=c.exports;h.j=function(d){try{return JSON.stringify(d)}catch(_){return"[UnexpectedJSONParseError]: "+_.message}}})(fu,fu.exports);var mr=fu.exports;function yh(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function tc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function Ch(c,t,n){return t&&tc(c.prototype,t),n&&tc(c,n),c}var ir=mr,lr="JsSIP",dt=function(){function c(t){yh(this,c),t?(this._debug=ir.default("".concat(lr,":").concat(t)),this._warn=ir.default("".concat(lr,":WARN:").concat(t)),this._error=ir.default("".concat(lr,":ERROR:").concat(t))):(this._debug=ir.default(lr),this._warn=ir.default("".concat(lr,":WARN")),this._error=ir.default("".concat(lr,":ERROR"))),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}return Ch(c,[{key:"debug",get:function(){return this._debug}},{key:"warn",get:function(){return this._warn}},{key:"error",get:function(){return this._error}}]),c}(),kt={},ed={},td={exports:{}},sc=td.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(c){return c.encoding?"rtpmap:%d %s/%s/%s":c.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(c){return c.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(c){return c.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(c){return"extmap:%d"+(c.direction?"/%s":"%v")+(c["encrypt-uri"]?" %s":"%v")+" %s"+(c.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(c){return c.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(c){var t="candidate:%s %d %s %d %s %d typ %s";return t+=c.raddr!=null?" raddr %s rport %d":"%v%v",t+=c.tcptype!=null?" tcptype %s":"%v",c.generation!=null&&(t+=" generation %d"),t+=c["network-id"]!=null?" network-id %d":"%v",t+=c["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(c){var t="ssrc:%d";return c.attribute!=null&&(t+=" %s",c.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(c){return c.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(c){return c.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(c){return"imageattr:%s %s %s"+(c.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(c){return"simulcast:%s %s"+(c.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(c){return"ts-refclk:%s"+(c.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(c){var t="mediaclk:";return t+=c.id!=null?"id=%s %s":"%v%s",t+=c.mediaClockValue!=null?"=%s":"",t+=c.rateNumerator!=null?" rate=%s":"",t+=c.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(sc).forEach(function(c){var t=sc[c];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})});var sd=td.exports;(function(c){var t=function(h){return String(Number(h))===h?Number(h):h},n=function(h,d,_,g){if(g&&!_)d[g]=t(h[1]);else for(var T=0;T<_.length;T+=1)h[T+1]!=null&&(d[_[T]]=t(h[T+1]))},l=function(h,d,_){var g=h.name&&h.names;h.push&&!d[h.push]?d[h.push]=[]:g&&!d[h.name]&&(d[h.name]={});var T=h.push?{}:g?d[h.name]:d;n(_.match(h.reg),T,h.names,h.name),h.push&&d[h.push].push(T)},a=sd,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);c.parse=function(h){var d={},_=[],g=d;return h.split(/(\r\n|\r|\n)/).filter(s).forEach(function(T){var S=T[0],E=T.slice(2);S==="m"&&(_.push({rtp:[],fmtp:[]}),g=_[_.length-1]);for(var C=0;C<(a[S]||[]).length;C+=1){var A=a[S][C];if(A.reg.test(E))return l(A,g,E)}}),d.media=_,d};var r=function(h,d){var _=d.split(/=(.+)/,2);return _.length===2?h[_[0]]=t(_[1]):_.length===1&&d.length>1&&(h[_[0]]=void 0),h};c.parseParams=function(h){return h.split(/;\s?/).reduce(r,{})},c.parseFmtpConfig=c.parseParams,c.parsePayloads=function(h){return h.toString().split(" ").map(Number)},c.parseRemoteCandidates=function(h){for(var d=[],_=h.split(" ").map(t),g=0;g<_.length;g+=3)d.push({component:_[g],ip:_[g+1],port:_[g+2]});return d},c.parseImageAttributes=function(h){return h.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(r,{})})},c.parseSimulcastStreamList=function(h){return h.split(";").map(function(d){return d.split(",").map(function(_){var g,T=!1;return _[0]!=="~"?g=t(_):(g=t(_.substring(1,_.length)),T=!0),{scid:g,paused:T}})})}})(ed);var pa=sd,Ah=/%[sdv%]/g,Rh=function(c){var t=1,n=arguments,l=n.length;return c.replace(Ah,function(a){if(t>=l)return a;var s=n[t];switch(t+=1,a){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Oi=function(c,t,n){var l=t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format,a=[c+"="+l];if(t.names)for(var s=0;s<t.names.length;s+=1){var r=t.names[s];t.name?a.push(n[t.name][r]):a.push(n[t.names[s]])}else a.push(n[t.name]);return Rh.apply(null,a)},Ih=["v","o","s","i","u","e","p","c","b","t","r","z","a"],bh=["i","c","b","a"],wh=function(c,t){t=t||{},c.version==null&&(c.version=0),c.name==null&&(c.name=" "),c.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var n=t.outerOrder||Ih,l=t.innerOrder||bh,a=[];return n.forEach(function(s){pa[s].forEach(function(r){r.name in c&&c[r.name]!=null?a.push(Oi(s,r,c)):r.push in c&&c[r.push]!=null&&c[r.push].forEach(function(h){a.push(Oi(s,r,h))})})}),c.media.forEach(function(s){a.push(Oi("m",pa.m[0],s)),l.forEach(function(r){pa[r].forEach(function(h){h.name in s&&s[h.name]!=null?a.push(Oi(r,h,s)):h.push in s&&s[h.push]!=null&&s[h.push].forEach(function(d){a.push(Oi(r,h,d))})})})}),a.join(`\r
|
|
3
|
+
`,r+=2):(e=null,_('"\\r\\n"')),e}function T(){var e;return/^[0-9]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[0-9]")),e}function S(){var e;return/^[a-zA-Z]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[a-zA-Z]")),e}function E(){var e;return/^[0-9a-fA-F]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[0-9a-fA-F]")),e}function C(){var e;return e=F(),e===null&&(e=I()),e}function A(){var e;return/^[\0-\xFF]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[\\0-\\xFF]")),e}function R(){var e;return/^["]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_('["]')),e}function F(){var e;return i.charCodeAt(r)===32?(e=" ",r++):(e=null,_('" "')),e}function I(){var e;return i.charCodeAt(r)===9?(e=" ",r++):(e=null,_('"\\t"')),e}function ie(){var e;return/^[a-zA-Z0-9]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[a-zA-Z0-9]")),e}function N(){var e;return i.charCodeAt(r)===59?(e=";",r++):(e=null,_('";"')),e===null&&(i.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e===null&&(i.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(i.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(i.charCodeAt(r)===64?(e="@",r++):(e=null,_('"@"')),e===null&&(i.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(i.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(i.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(i.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')),e===null&&(i.charCodeAt(r)===44?(e=",",r++):(e=null,_('","'))))))))))),e}function $(){var e;return e=ie(),e===null&&(e=ve()),e}function ve(){var e;return i.charCodeAt(r)===45?(e="-",r++):(e=null,_('"-"')),e===null&&(i.charCodeAt(r)===95?(e="_",r++):(e=null,_('"_"')),e===null&&(i.charCodeAt(r)===46?(e=".",r++):(e=null,_('"."')),e===null&&(i.charCodeAt(r)===33?(e="!",r++):(e=null,_('"!"')),e===null&&(i.charCodeAt(r)===126?(e="~",r++):(e=null,_('"~"')),e===null&&(i.charCodeAt(r)===42?(e="*",r++):(e=null,_('"*"')),e===null&&(i.charCodeAt(r)===39?(e="'",r++):(e=null,_(`"'"`)),e===null&&(i.charCodeAt(r)===40?(e="(",r++):(e=null,_('"("')),e===null&&(i.charCodeAt(r)===41?(e=")",r++):(e=null,_('")"')))))))))),e}function _e(){var e,o,u,f,p;return f=r,p=r,i.charCodeAt(r)===37?(e="%",r++):(e=null,_('"%"')),e!==null?(o=E(),o!==null?(u=E(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){return v.join("")}(f,e)),e===null&&(r=f),e}function U(){var e,o,u,f,p,m;for(f=r,p=r,m=r,e=[],o=C();o!==null;)e.push(o),o=C();if(e!==null?(o=g(),o!==null?e=[e,o]:(e=null,r=m)):(e=null,r=m),e=e!==null?e:"",e!==null){if(u=C(),u!==null)for(o=[];u!==null;)o.push(u),u=C();else o=null;o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e!==null&&(e=function(v){return" "}()),e===null&&(r=f),e}function x(){var e;return e=U(),e=e!==null?e:"",e}function q(){var e,o,u,f,p;for(f=r,p=r,e=[],o=F(),o===null&&(o=I());o!==null;)e.push(o),o=F(),o===null&&(o=I());return e!==null?(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=x(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return":"}()),e===null&&(r=f),e}function j(){var e,o,u,f,p,m,v;if(p=r,m=r,o=Y(),o!==null)for(e=[];o!==null;)e.push(o),o=Y();else e=null;if(e!==null){for(o=[],v=r,u=[],f=U();f!==null;)u.push(f),f=U();for(u!==null?(f=Y(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;){for(o.push(u),v=r,u=[],f=U();f!==null;)u.push(f),f=U();u!==null?(f=Y(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v)}o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){return i.substring(r,y)}(p)),e===null&&(r=p),e}function Y(){var e;return/^[!-~]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[!-~]")),e===null&&(e=V()),e}function V(){var e;return/^[\x80-\uFFFF]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[\\x80-\\uFFFF]")),e}function Q(){var e;return/^[\x80-\xBF]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[\\x80-\\xBF]")),e}function k(){var e;return e=T(),e===null&&(/^[a-f]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[a-f]"))),e}function M(){var e,o,u;if(u=r,o=ie(),o===null&&(i.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(i.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o===null&&(i.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(i.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(i.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(i.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(i.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(i.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(i.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"')))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=ie(),o===null&&(i.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(i.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o===null&&(i.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(i.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(i.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(i.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(i.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(i.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(i.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"'))))))))))));else e=null;return e!==null&&(e=function(f){return i.substring(r,f)}(u)),e===null&&(r=u),e}function B(){var e,o,u;if(u=r,o=ie(),o===null&&(i.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(i.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(i.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(i.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(i.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(i.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(i.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(i.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"'))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=ie(),o===null&&(i.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(i.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(i.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(i.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(i.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(i.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(i.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(i.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"')))))))))));else e=null;return e!==null&&(e=function(f){return i.substring(r,f)}(u)),e===null&&(r=u),e}function Fe(){var e;return i.charCodeAt(r)===40?(e="(",r++):(e=null,_('"("')),e===null&&(i.charCodeAt(r)===41?(e=")",r++):(e=null,_('")"')),e===null&&(i.charCodeAt(r)===60?(e="<",r++):(e=null,_('"<"')),e===null&&(i.charCodeAt(r)===62?(e=">",r++):(e=null,_('">"')),e===null&&(i.charCodeAt(r)===64?(e="@",r++):(e=null,_('"@"')),e===null&&(i.charCodeAt(r)===44?(e=",",r++):(e=null,_('","')),e===null&&(i.charCodeAt(r)===59?(e=";",r++):(e=null,_('";"')),e===null&&(i.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(i.charCodeAt(r)===92?(e="\\",r++):(e=null,_('"\\\\"')),e===null&&(e=R(),e===null&&(i.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e===null&&(i.charCodeAt(r)===91?(e="[",r++):(e=null,_('"["')),e===null&&(i.charCodeAt(r)===93?(e="]",r++):(e=null,_('"]"')),e===null&&(i.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(i.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(i.charCodeAt(r)===123?(e="{",r++):(e=null,_('"{"')),e===null&&(i.charCodeAt(r)===125?(e="}",r++):(e=null,_('"}"')),e===null&&(e=F(),e===null&&(e=I())))))))))))))))))),e}function X(){var e,o,u;if(u=r,o=ie(),o===null&&(i.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(i.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o===null&&(i.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(i.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(i.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(i.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(i.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(i.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(i.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"')),o===null&&(i.charCodeAt(r)===40?(o="(",r++):(o=null,_('"("')),o===null&&(i.charCodeAt(r)===41?(o=")",r++):(o=null,_('")"')),o===null&&(i.charCodeAt(r)===60?(o="<",r++):(o=null,_('"<"')),o===null&&(i.charCodeAt(r)===62?(o=">",r++):(o=null,_('">"')),o===null&&(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o===null&&(i.charCodeAt(r)===92?(o="\\",r++):(o=null,_('"\\\\"')),o===null&&(o=R(),o===null&&(i.charCodeAt(r)===47?(o="/",r++):(o=null,_('"/"')),o===null&&(i.charCodeAt(r)===91?(o="[",r++):(o=null,_('"["')),o===null&&(i.charCodeAt(r)===93?(o="]",r++):(o=null,_('"]"')),o===null&&(i.charCodeAt(r)===63?(o="?",r++):(o=null,_('"?"')),o===null&&(i.charCodeAt(r)===123?(o="{",r++):(o=null,_('"{"')),o===null&&(i.charCodeAt(r)===125?(o="}",r++):(o=null,_('"}"'))))))))))))))))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=ie(),o===null&&(i.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o===null&&(i.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o===null&&(i.charCodeAt(r)===33?(o="!",r++):(o=null,_('"!"')),o===null&&(i.charCodeAt(r)===37?(o="%",r++):(o=null,_('"%"')),o===null&&(i.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o===null&&(i.charCodeAt(r)===95?(o="_",r++):(o=null,_('"_"')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(i.charCodeAt(r)===96?(o="`",r++):(o=null,_('"`"')),o===null&&(i.charCodeAt(r)===39?(o="'",r++):(o=null,_(`"'"`)),o===null&&(i.charCodeAt(r)===126?(o="~",r++):(o=null,_('"~"')),o===null&&(i.charCodeAt(r)===40?(o="(",r++):(o=null,_('"("')),o===null&&(i.charCodeAt(r)===41?(o=")",r++):(o=null,_('")"')),o===null&&(i.charCodeAt(r)===60?(o="<",r++):(o=null,_('"<"')),o===null&&(i.charCodeAt(r)===62?(o=">",r++):(o=null,_('">"')),o===null&&(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o===null&&(i.charCodeAt(r)===92?(o="\\",r++):(o=null,_('"\\\\"')),o===null&&(o=R(),o===null&&(i.charCodeAt(r)===47?(o="/",r++):(o=null,_('"/"')),o===null&&(i.charCodeAt(r)===91?(o="[",r++):(o=null,_('"["')),o===null&&(i.charCodeAt(r)===93?(o="]",r++):(o=null,_('"]"')),o===null&&(i.charCodeAt(r)===63?(o="?",r++):(o=null,_('"?"')),o===null&&(i.charCodeAt(r)===123?(o="{",r++):(o=null,_('"{"')),o===null&&(i.charCodeAt(r)===125?(o="}",r++):(o=null,_('"}"')))))))))))))))))))))))));else e=null;return e!==null&&(e=function(f){return i.substring(r,f)}(u)),e===null&&(r=u),e}function W(){var e,o,u,f,p;return f=r,p=r,e=x(),e!==null?(i.charCodeAt(r)===42?(o="*",r++):(o=null,_('"*"')),o!==null?(u=x(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return"*"}()),e===null&&(r=f),e}function G(){var e,o,u,f,p;return f=r,p=r,e=x(),e!==null?(i.charCodeAt(r)===47?(o="/",r++):(o=null,_('"/"')),o!==null?(u=x(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return"/"}()),e===null&&(r=f),e}function re(){var e,o,u,f,p;return f=r,p=r,e=x(),e!==null?(i.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o!==null?(u=x(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return"="}()),e===null&&(r=f),e}function pe(){var e,o,u,f,p;return f=r,p=r,e=x(),e!==null?(i.charCodeAt(r)===40?(o="(",r++):(o=null,_('"("')),o!==null?(u=x(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return"("}()),e===null&&(r=f),e}function Ie(){var e,o,u,f,p;return f=r,p=r,e=x(),e!==null?(i.charCodeAt(r)===41?(o=")",r++):(o=null,_('")"')),o!==null?(u=x(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return")"}()),e===null&&(r=f),e}function ke(){var e,o,u,f;return u=r,f=r,i.charCodeAt(r)===62?(e=">",r++):(e=null,_('">"')),e!==null?(o=x(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return">"}()),e===null&&(r=u),e}function Ae(){var e,o,u,f;return u=r,f=r,e=x(),e!==null?(i.charCodeAt(r)===60?(o="<",r++):(o=null,_('"<"')),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return"<"}()),e===null&&(r=u),e}function oe(){var e,o,u,f,p;return f=r,p=r,e=x(),e!==null?(i.charCodeAt(r)===44?(o=",",r++):(o=null,_('","')),o!==null?(u=x(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return","}()),e===null&&(r=f),e}function ye(){var e,o,u,f,p;return f=r,p=r,e=x(),e!==null?(i.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o!==null?(u=x(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return";"}()),e===null&&(r=f),e}function rt(){var e,o,u,f,p;return f=r,p=r,e=x(),e!==null?(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=x(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return":"}()),e===null&&(r=f),e}function at(){var e,o,u,f;return u=r,f=r,e=x(),e!==null?(o=R(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return'"'}()),e===null&&(r=u),e}function Ee(){var e,o,u,f;return u=r,f=r,e=R(),e!==null?(o=x(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return'"'}()),e===null&&(r=u),e}function Ce(){var e,o,u,f;if(f=r,e=pe(),e!==null){for(o=[],u=be(),u===null&&(u=me(),u===null&&(u=Ce()));u!==null;)o.push(u),u=be(),u===null&&(u=me(),u===null&&(u=Ce()));o!==null?(u=Ie(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)}else e=null,r=f;return e}function be(){var e;return/^[!-']/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[!-']")),e===null&&(/^[*-[]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[*-[]")),e===null&&(/^[\]-~]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[\\]-~]")),e===null&&(e=V(),e===null&&(e=U())))),e}function Oe(){var e,o,u,f,p,m;if(p=r,m=r,e=x(),e!==null)if(o=R(),o!==null){for(u=[],f=ue(),f===null&&(f=me());f!==null;)u.push(f),f=ue(),f===null&&(f=me());u!==null?(f=R(),f!==null?e=[e,o,u,f]:(e=null,r=m)):(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e!==null&&(e=function(v){return i.substring(r,v)}(p)),e===null&&(r=p),e}function ge(){var e,o,u,f,p,m;if(p=r,m=r,e=x(),e!==null)if(o=R(),o!==null){for(u=[],f=ue(),f===null&&(f=me());f!==null;)u.push(f),f=ue(),f===null&&(f=me());u!==null?(f=R(),f!==null?e=[e,o,u,f]:(e=null,r=m)):(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e!==null&&(e=function(v){var y=i.substring(r,v).trim();return y.substring(1,y.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(p)),e===null&&(r=p),e}function ue(){var e;return e=U(),e===null&&(i.charCodeAt(r)===33?(e="!",r++):(e=null,_('"!"')),e===null&&(/^[#-[]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[#-[]")),e===null&&(/^[\]-~]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[\\]-~]")),e===null&&(e=V())))),e}function me(){var e,o,u;return u=r,i.charCodeAt(r)===92?(e="\\",r++):(e=null,_('"\\\\"')),e!==null?(/^[\0-\t]/.test(i.charAt(r))?(o=i.charAt(r),r++):(o=null,_("[\\0-\\t]")),o===null&&(/^[\x0B-\f]/.test(i.charAt(r))?(o=i.charAt(r),r++):(o=null,_("[\\x0B-\\f]")),o===null&&(/^[\x0E-]/.test(i.charAt(r))?(o=i.charAt(r),r++):(o=null,_("[\\x0E-]")))),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function we(){var e,o,u,f,p,m;return p=r,m=r,e=et(),e!==null?(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=_t(),u=u!==null?u:"",u!==null?(f=ts(),f!==null?e=[e,o,u,f]:(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m),e!==null&&(e=function(v){try{O.uri=new ds(O.scheme,O.user,O.host,O.port),delete O.scheme,delete O.user,delete O.host,delete O.host_type,delete O.port}catch{O=-1}}()),e===null&&(r=p),e}function Ne(){var e,o,u,f,p,m,v,y;return v=r,y=r,e=et(),e!==null?(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=_t(),u=u!==null?u:"",u!==null?(f=ts(),f!==null?(p=xn(),p!==null?(m=Xs(),m=m!==null?m:"",m!==null?e=[e,o,u,f,p,m]:(e=null,r=y)):(e=null,r=y)):(e=null,r=y)):(e=null,r=y)):(e=null,r=y)):(e=null,r=y),e!==null&&(e=function(D){try{O.uri=new ds(O.scheme,O.user,O.host,O.port,O.uri_params,O.uri_headers),delete O.scheme,delete O.user,delete O.host,delete O.host_type,delete O.port,delete O.uri_params,a==="SIP_URI"&&(O=O.uri)}catch{O=-1}}()),e===null&&(r=v),e}function et(){var e;return e=$e(),e===null&&(e=$t()),e}function $e(){var e,o;return o=r,i.substr(r,4).toLowerCase()==="sips"?(e=i.substr(r,4),r+=4):(e=null,_('"sips"')),e!==null&&(e=function(u,f){O.scheme=f.toLowerCase()}(o,e)),e===null&&(r=o),e}function $t(){var e,o;return o=r,i.substr(r,3).toLowerCase()==="sip"?(e=i.substr(r,3),r+=3):(e=null,_('"sip"')),e!==null&&(e=function(u,f){O.scheme=f.toLowerCase()}(o,e)),e===null&&(r=o),e}function _t(){var e,o,u,f,p,m;return f=r,p=r,e=wn(),e!==null?(m=r,i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=Js(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?(i.charCodeAt(r)===64?(u="@",r++):(u=null,_('"@"')),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){O.user=decodeURIComponent(i.substring(r-1,v))}(f)),e===null&&(r=f),e}function wn(){var e,o;if(o=$(),o===null&&(o=_e(),o===null&&(o=On())),o!==null)for(e=[];o!==null;)e.push(o),o=$(),o===null&&(o=_e(),o===null&&(o=On()));else e=null;return e}function On(){var e;return i.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(i.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(i.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(i.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')),e===null&&(i.charCodeAt(r)===44?(e=",",r++):(e=null,_('","')),e===null&&(i.charCodeAt(r)===59?(e=";",r++):(e=null,_('";"')),e===null&&(i.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(i.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"'))))))))),e}function Js(){var e,o,u;for(u=r,e=[],o=$(),o===null&&(o=_e(),o===null&&(i.charCodeAt(r)===38?(o="&",r++):(o=null,_('"&"')),o===null&&(i.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(i.charCodeAt(r)===36?(o="$",r++):(o=null,_('"$"')),o===null&&(i.charCodeAt(r)===44?(o=",",r++):(o=null,_('","'))))))));o!==null;)e.push(o),o=$(),o===null&&(o=_e(),o===null&&(i.charCodeAt(r)===38?(o="&",r++):(o=null,_('"&"')),o===null&&(i.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')),o===null&&(i.charCodeAt(r)===36?(o="$",r++):(o=null,_('"$"')),o===null&&(i.charCodeAt(r)===44?(o=",",r++):(o=null,_('","'))))))));return e!==null&&(e=function(f){O.password=i.substring(r,f)}(u)),e===null&&(r=u),e}function ts(){var e,o,u,f,p;return f=r,e=cs(),e!==null?(p=r,i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=Sr(),u!==null?o=[o,u]:(o=null,r=p)):(o=null,r=p),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e}function cs(){var e,o;return o=r,e=zs(),e===null&&(e=Kt(),e===null&&(e=Qs())),e!==null&&(e=function(u){return O.host=i.substring(r,u).toLowerCase(),O.host}(o)),e===null&&(r=o),e}function zs(){var e,o,u,f,p,m;for(f=r,p=r,e=[],m=r,o=Dn(),o!==null?(i.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m);o!==null;)e.push(o),m=r,o=Dn(),o!==null?(i.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m);return e!==null?(o=Nn(),o!==null?(i.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u=u!==null?u:"",u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){return O.host_type="domain",i.substring(r,v)}(f)),e===null&&(r=f),e}function Dn(){var e,o,u,f;if(f=r,e=ie(),e!==null){for(o=[],u=ie(),u===null&&(i.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(i.charCodeAt(r)===95?(u="_",r++):(u=null,_('"_"'))));u!==null;)o.push(u),u=ie(),u===null&&(i.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(i.charCodeAt(r)===95?(u="_",r++):(u=null,_('"_"'))));o!==null?e=[e,o]:(e=null,r=f)}else e=null,r=f;return e}function Nn(){var e,o,u,f;if(f=r,e=S(),e!==null){for(o=[],u=ie(),u===null&&(i.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(i.charCodeAt(r)===95?(u="_",r++):(u=null,_('"_"'))));u!==null;)o.push(u),u=ie(),u===null&&(i.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(i.charCodeAt(r)===95?(u="_",r++):(u=null,_('"_"'))));o!==null?e=[e,o]:(e=null,r=f)}else e=null,r=f;return e}function Qs(){var e,o,u,f,p;return f=r,p=r,i.charCodeAt(r)===91?(e="[",r++):(e=null,_('"["')),e!==null?(o=Te(),o!==null?(i.charCodeAt(r)===93?(u="]",r++):(u=null,_('"]"')),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return O.host_type="IPv6",i.substring(r,m)}(f)),e===null&&(r=f),e}function Te(){var e,o,u,f,p,m,v,y,D,le,xe,Ot,Ps,L,b,Se;return L=r,b=r,e=ae(),e!==null?(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?(i.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?(i.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?(i.charCodeAt(r)===58?(y=":",r++):(y=null,_('":"')),y!==null?(D=ae(),D!==null?(i.charCodeAt(r)===58?(le=":",r++):(le=null,_('":"')),le!==null?(xe=ae(),xe!==null?(i.charCodeAt(r)===58?(Ot=":",r++):(Ot=null,_('":"')),Ot!==null?(Ps=ut(),Ps!==null?e=[e,o,u,f,p,m,v,y,D,le,xe,Ot,Ps]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,i.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?(i.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?(i.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ae(),y!==null?(i.charCodeAt(r)===58?(D=":",r++):(D=null,_('":"')),D!==null?(le=ae(),le!==null?(i.charCodeAt(r)===58?(xe=":",r++):(xe=null,_('":"')),xe!==null?(Ot=ut(),Ot!==null?e=[e,o,u,f,p,m,v,y,D,le,xe,Ot]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,i.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?(i.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?(i.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ae(),y!==null?(i.charCodeAt(r)===58?(D=":",r++):(D=null,_('":"')),D!==null?(le=ut(),le!==null?e=[e,o,u,f,p,m,v,y,D,le]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,i.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?(i.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?(i.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ut(),y!==null?e=[e,o,u,f,p,m,v,y]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,i.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?(i.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ut(),m!==null?e=[e,o,u,f,p,m]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,i.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?(i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ut(),f!==null?e=[e,o,u,f]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,i.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ut(),o!==null?e=[e,o]:(e=null,r=b)):(e=null,r=b),e===null&&(b=r,i.substr(r,2)==="::"?(e="::",r+=2):(e=null,_('"::"')),e!==null?(o=ae(),o!==null?e=[e,o]:(e=null,r=b)):(e=null,r=b),e===null&&(b=r,e=ae(),e!==null?(i.substr(r,2)==="::"?(o="::",r+=2):(o=null,_('"::"')),o!==null?(u=ae(),u!==null?(i.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?(i.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?(i.charCodeAt(r)===58?(y=":",r++):(y=null,_('":"')),y!==null?(D=ae(),D!==null?(i.charCodeAt(r)===58?(le=":",r++):(le=null,_('":"')),le!==null?(xe=ut(),xe!==null?e=[e,o,u,f,p,m,v,y,D,le,xe]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,e=ae(),e!==null?(Se=r,i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(i.substr(r,2)==="::"?(u="::",r+=2):(u=null,_('"::"')),u!==null?(f=ae(),f!==null?(i.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?(i.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ae(),y!==null?(i.charCodeAt(r)===58?(D=":",r++):(D=null,_('":"')),D!==null?(le=ut(),le!==null?e=[e,o,u,f,p,m,v,y,D,le]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,e=ae(),e!==null?(Se=r,i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(i.substr(r,2)==="::"?(f="::",r+=2):(f=null,_('"::"')),f!==null?(p=ae(),p!==null?(i.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?(i.charCodeAt(r)===58?(y=":",r++):(y=null,_('":"')),y!==null?(D=ut(),D!==null?e=[e,o,u,f,p,m,v,y,D]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,e=ae(),e!==null?(Se=r,i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(Se=r,i.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(i.substr(r,2)==="::"?(p="::",r+=2):(p=null,_('"::"')),p!==null?(m=ae(),m!==null?(i.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ut(),y!==null?e=[e,o,u,f,p,m,v,y]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,e=ae(),e!==null?(Se=r,i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(Se=r,i.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(Se=r,i.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?p=[p,m]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(i.substr(r,2)==="::"?(m="::",r+=2):(m=null,_('"::"')),m!==null?(v=ut(),v!==null?e=[e,o,u,f,p,m,v]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,e=ae(),e!==null?(Se=r,i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(Se=r,i.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(Se=r,i.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?p=[p,m]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(Se=r,i.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?m=[m,v]:(m=null,r=Se)):(m=null,r=Se),m=m!==null?m:"",m!==null?(i.substr(r,2)==="::"?(v="::",r+=2):(v=null,_('"::"')),v!==null?(y=ae(),y!==null?e=[e,o,u,f,p,m,v,y]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,e=ae(),e!==null?(Se=r,i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?o=[o,u]:(o=null,r=Se)):(o=null,r=Se),o=o!==null?o:"",o!==null?(Se=r,i.charCodeAt(r)===58?(u=":",r++):(u=null,_('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(Se=r,i.charCodeAt(r)===58?(f=":",r++):(f=null,_('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(Se=r,i.charCodeAt(r)===58?(p=":",r++):(p=null,_('":"')),p!==null?(m=ae(),m!==null?p=[p,m]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(Se=r,i.charCodeAt(r)===58?(m=":",r++):(m=null,_('":"')),m!==null?(v=ae(),v!==null?m=[m,v]:(m=null,r=Se)):(m=null,r=Se),m=m!==null?m:"",m!==null?(Se=r,i.charCodeAt(r)===58?(v=":",r++):(v=null,_('":"')),v!==null?(y=ae(),y!==null?v=[v,y]:(v=null,r=Se)):(v=null,r=Se),v=v!==null?v:"",v!==null?(i.substr(r,2)==="::"?(y="::",r+=2):(y=null,_('"::"')),y!==null?e=[e,o,u,f,p,m,v,y]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b))))))))))))))),e!==null&&(e=function(Yd){return O.host_type="IPv6",i.substring(r,Yd)}(L)),e===null&&(r=L),e}function ae(){var e,o,u,f,p;return p=r,e=E(),e!==null?(o=E(),o=o!==null?o:"",o!==null?(u=E(),u=u!==null?u:"",u!==null?(f=E(),f=f!==null?f:"",f!==null?e=[e,o,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function ut(){var e,o,u,f;return f=r,e=ae(),e!==null?(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=ae(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(e=Kt()),e}function Kt(){var e,o,u,f,p,m,v,y,D;return y=r,D=r,e=Rs(),e!==null?(i.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o!==null?(u=Rs(),u!==null?(i.charCodeAt(r)===46?(f=".",r++):(f=null,_('"."')),f!==null?(p=Rs(),p!==null?(i.charCodeAt(r)===46?(m=".",r++):(m=null,_('"."')),m!==null?(v=Rs(),v!==null?e=[e,o,u,f,p,m,v]:(e=null,r=D)):(e=null,r=D)):(e=null,r=D)):(e=null,r=D)):(e=null,r=D)):(e=null,r=D)):(e=null,r=D),e!==null&&(e=function(le){return O.host_type="IPv4",i.substring(r,le)}(y)),e===null&&(r=y),e}function Rs(){var e,o,u,f;return f=r,i.substr(r,2)==="25"?(e="25",r+=2):(e=null,_('"25"')),e!==null?(/^[0-5]/.test(i.charAt(r))?(o=i.charAt(r),r++):(o=null,_("[0-5]")),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e===null&&(f=r,i.charCodeAt(r)===50?(e="2",r++):(e=null,_('"2"')),e!==null?(/^[0-4]/.test(i.charAt(r))?(o=i.charAt(r),r++):(o=null,_("[0-4]")),o!==null?(u=T(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(f=r,i.charCodeAt(r)===49?(e="1",r++):(e=null,_('"1"')),e!==null?(o=T(),o!==null?(u=T(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(f=r,/^[1-9]/.test(i.charAt(r))?(e=i.charAt(r),r++):(e=null,_("[1-9]")),e!==null?(o=T(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e===null&&(e=T())))),e}function Sr(){var e,o,u,f,p,m,v;return m=r,v=r,e=T(),e=e!==null?e:"",e!==null?(o=T(),o=o!==null?o:"",o!==null?(u=T(),u=u!==null?u:"",u!==null?(f=T(),f=f!==null?f:"",f!==null?(p=T(),p=p!==null?p:"",p!==null?e=[e,o,u,f,p]:(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(y,D){return D=parseInt(D.join("")),O.port=D,D}(m,e)),e===null&&(r=m),e}function xn(){var e,o,u,f;for(e=[],f=r,i.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o!==null?(u=Un(),u!==null?o=[o,u]:(o=null,r=f)):(o=null,r=f);o!==null;)e.push(o),f=r,i.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o!==null?(u=Un(),u!==null?o=[o,u]:(o=null,r=f)):(o=null,r=f);return e}function Un(){var e;return e=Er(),e===null&&(e=yr(),e===null&&(e=Cr(),e===null&&(e=Ar(),e===null&&(e=Rr(),e===null&&(e=Ir(),e===null&&(e=br())))))),e}function Er(){var e,o,u,f;return u=r,f=r,i.substr(r,10).toLowerCase()==="transport="?(e=i.substr(r,10),r+=10):(e=null,_('"transport="')),e!==null?(i.substr(r,3).toLowerCase()==="udp"?(o=i.substr(r,3),r+=3):(o=null,_('"udp"')),o===null&&(i.substr(r,3).toLowerCase()==="tcp"?(o=i.substr(r,3),r+=3):(o=null,_('"tcp"')),o===null&&(i.substr(r,4).toLowerCase()==="sctp"?(o=i.substr(r,4),r+=4):(o=null,_('"sctp"')),o===null&&(i.substr(r,3).toLowerCase()==="tls"?(o=i.substr(r,3),r+=3):(o=null,_('"tls"')),o===null&&(o=M())))),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.uri_params||(O.uri_params={}),O.uri_params.transport=m.toLowerCase()}(u,e[1])),e===null&&(r=u),e}function yr(){var e,o,u,f;return u=r,f=r,i.substr(r,5).toLowerCase()==="user="?(e=i.substr(r,5),r+=5):(e=null,_('"user="')),e!==null?(i.substr(r,5).toLowerCase()==="phone"?(o=i.substr(r,5),r+=5):(o=null,_('"phone"')),o===null&&(i.substr(r,2).toLowerCase()==="ip"?(o=i.substr(r,2),r+=2):(o=null,_('"ip"')),o===null&&(o=M())),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.uri_params||(O.uri_params={}),O.uri_params.user=m.toLowerCase()}(u,e[1])),e===null&&(r=u),e}function Cr(){var e,o,u,f;return u=r,f=r,i.substr(r,7).toLowerCase()==="method="?(e=i.substr(r,7),r+=7):(e=null,_('"method="')),e!==null?(o=ln(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.uri_params||(O.uri_params={}),O.uri_params.method=m}(u,e[1])),e===null&&(r=u),e}function Ar(){var e,o,u,f;return u=r,f=r,i.substr(r,4).toLowerCase()==="ttl="?(e=i.substr(r,4),r+=4):(e=null,_('"ttl="')),e!==null?(o=Ai(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.params||(O.params={}),O.params.ttl=m}(u,e[1])),e===null&&(r=u),e}function Rr(){var e,o,u,f;return u=r,f=r,i.substr(r,6).toLowerCase()==="maddr="?(e=i.substr(r,6),r+=6):(e=null,_('"maddr="')),e!==null?(o=cs(),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){O.uri_params||(O.uri_params={}),O.uri_params.maddr=m}(u,e[1])),e===null&&(r=u),e}function Ir(){var e,o,u,f,p,m;return f=r,p=r,i.substr(r,2).toLowerCase()==="lr"?(e=i.substr(r,2),r+=2):(e=null,_('"lr"')),e!==null?(m=r,i.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o!==null?(u=M(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){O.uri_params||(O.uri_params={}),O.uri_params.lr=void 0}()),e===null&&(r=f),e}function br(){var e,o,u,f,p,m;return f=r,p=r,e=wr(),e!==null?(m=r,i.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o!==null?(u=Is(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v,y,D){O.uri_params||(O.uri_params={}),typeof D>"u"?D=void 0:D=D[1],O.uri_params[y.toLowerCase()]=D}(f,e[0],e[1])),e===null&&(r=f),e}function wr(){var e,o,u;if(u=r,o=bs(),o!==null)for(e=[];o!==null;)e.push(o),o=bs();else e=null;return e!==null&&(e=function(f,p){return p.join("")}(u,e)),e===null&&(r=u),e}function Is(){var e,o,u;if(u=r,o=bs(),o!==null)for(e=[];o!==null;)e.push(o),o=bs();else e=null;return e!==null&&(e=function(f,p){return p.join("")}(u,e)),e===null&&(r=u),e}function bs(){var e;return e=Or(),e===null&&(e=$(),e===null&&(e=_e())),e}function Or(){var e;return i.charCodeAt(r)===91?(e="[",r++):(e=null,_('"["')),e===null&&(i.charCodeAt(r)===93?(e="]",r++):(e=null,_('"]"')),e===null&&(i.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e===null&&(i.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(i.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(i.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(i.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')))))))),e}function Xs(){var e,o,u,f,p,m,v;if(m=r,i.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e!==null)if(o=Zs(),o!==null){for(u=[],v=r,i.charCodeAt(r)===38?(f="&",r++):(f=null,_('"&"')),f!==null?(p=Zs(),p!==null?f=[f,p]:(f=null,r=v)):(f=null,r=v);f!==null;)u.push(f),v=r,i.charCodeAt(r)===38?(f="&",r++):(f=null,_('"&"')),f!==null?(p=Zs(),p!==null?f=[f,p]:(f=null,r=v)):(f=null,r=v);u!==null?e=[e,o,u]:(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e}function Zs(){var e,o,u,f,p;return f=r,p=r,e=Dr(),e!==null?(i.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o!==null?(u=ws(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v,y){v=v.join("").toLowerCase(),y=y.join(""),O.uri_headers||(O.uri_headers={}),O.uri_headers[v]?O.uri_headers[v].push(y):O.uri_headers[v]=[y]}(f,e[0],e[2])),e===null&&(r=f),e}function Dr(){var e,o;if(o=en(),o===null&&(o=$(),o===null&&(o=_e())),o!==null)for(e=[];o!==null;)e.push(o),o=en(),o===null&&(o=$(),o===null&&(o=_e()));else e=null;return e}function ws(){var e,o;for(e=[],o=en(),o===null&&(o=$(),o===null&&(o=_e()));o!==null;)e.push(o),o=en(),o===null&&(o=$(),o===null&&(o=_e()));return e}function en(){var e;return i.charCodeAt(r)===91?(e="[",r++):(e=null,_('"["')),e===null&&(i.charCodeAt(r)===93?(e="]",r++):(e=null,_('"]"')),e===null&&(i.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e===null&&(i.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(i.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(i.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(i.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')))))))),e}function gl(){var e;return e=Wr(),e===null&&(e=Nr()),e}function Nr(){var e,o,u,f,p,m;return m=r,e=ln(),e!==null?(o=F(),o!==null?(u=kn(),u!==null?(f=F(),f!==null?(p=Ln(),p!==null?e=[e,o,u,f,p]:(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m),e}function kn(){var e;return e=Ne(),e===null&&(e=Mn()),e}function Mn(){var e,o,u,f;return f=r,e=kr(),e!==null?(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o!==null?(u=xr(),u===null&&(u=Os()),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function xr(){var e,o,u,f,p;return f=r,e=tn(),e===null&&(e=sn()),e!==null?(p=r,i.charCodeAt(r)===63?(o="?",r++):(o=null,_('"?"')),o!==null?(u=Pn(),u!==null?o=[o,u]:(o=null,r=p)):(o=null,r=p),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e}function tn(){var e,o,u,f;return f=r,i.substr(r,2)==="//"?(e="//",r+=2):(e=null,_('"//"')),e!==null?(o=Mr(),o!==null?(u=sn(),u=u!==null?u:"",u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function sn(){var e,o,u;return u=r,i.charCodeAt(r)===47?(e="/",r++):(e=null,_('"/"')),e!==null?(o=nn(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function Os(){var e,o,u,f;if(f=r,e=Ur(),e!==null){for(o=[],u=Ds();u!==null;)o.push(u),u=Ds();o!==null?e=[e,o]:(e=null,r=f)}else e=null,r=f;return e}function Ds(){var e;return e=N(),e===null&&(e=$(),e===null&&(e=_e())),e}function Ur(){var e;return e=$(),e===null&&(e=_e(),e===null&&(i.charCodeAt(r)===59?(e=";",r++):(e=null,_('";"')),e===null&&(i.charCodeAt(r)===63?(e="?",r++):(e=null,_('"?"')),e===null&&(i.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(i.charCodeAt(r)===64?(e="@",r++):(e=null,_('"@"')),e===null&&(i.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(i.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(i.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(i.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')),e===null&&(i.charCodeAt(r)===44?(e=",",r++):(e=null,_('","')))))))))))),e}function nn(){var e,o,u,f,p,m;if(p=r,e=Ns(),e!==null){for(o=[],m=r,i.charCodeAt(r)===47?(u="/",r++):(u=null,_('"/"')),u!==null?(f=Ns(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,i.charCodeAt(r)===47?(u="/",r++):(u=null,_('"/"')),u!==null?(f=Ns(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Ns(){var e,o,u,f,p,m;for(p=r,e=[],o=xs();o!==null;)e.push(o),o=xs();if(e!==null){for(o=[],m=r,i.charCodeAt(r)===59?(u=";",r++):(u=null,_('";"')),u!==null?(f=fs(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,i.charCodeAt(r)===59?(u=";",r++):(u=null,_('";"')),u!==null?(f=fs(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function fs(){var e,o;for(e=[],o=xs();o!==null;)e.push(o),o=xs();return e}function xs(){var e;return e=$(),e===null&&(e=_e(),e===null&&(i.charCodeAt(r)===58?(e=":",r++):(e=null,_('":"')),e===null&&(i.charCodeAt(r)===64?(e="@",r++):(e=null,_('"@"')),e===null&&(i.charCodeAt(r)===38?(e="&",r++):(e=null,_('"&"')),e===null&&(i.charCodeAt(r)===61?(e="=",r++):(e=null,_('"="')),e===null&&(i.charCodeAt(r)===43?(e="+",r++):(e=null,_('"+"')),e===null&&(i.charCodeAt(r)===36?(e="$",r++):(e=null,_('"$"')),e===null&&(i.charCodeAt(r)===44?(e=",",r++):(e=null,_('","')))))))))),e}function kr(){var e,o,u,f,p;if(f=r,p=r,e=S(),e!==null){for(o=[],u=S(),u===null&&(u=T(),u===null&&(i.charCodeAt(r)===43?(u="+",r++):(u=null,_('"+"')),u===null&&(i.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(i.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."'))))));u!==null;)o.push(u),u=S(),u===null&&(u=T(),u===null&&(i.charCodeAt(r)===43?(u="+",r++):(u=null,_('"+"')),u===null&&(i.charCodeAt(r)===45?(u="-",r++):(u=null,_('"-"')),u===null&&(i.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."'))))));o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e!==null&&(e=function(m){O.scheme=i.substring(r,m)}(f)),e===null&&(r=f),e}function Mr(){var e;return e=Pr(),e===null&&(e=Lr()),e}function Pr(){var e,o,u,f;return u=r,f=r,e=_t(),e!==null?(i.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e=e!==null?e:"",e!==null?(o=ts(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e=e!==null?e:"",e}function Lr(){var e,o;if(o=$(),o===null&&(o=_e(),o===null&&(i.charCodeAt(r)===36?(o="$",r++):(o=null,_('"$"')),o===null&&(i.charCodeAt(r)===44?(o=",",r++):(o=null,_('","')),o===null&&(i.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o===null&&(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o===null&&(i.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o===null&&(i.charCodeAt(r)===38?(o="&",r++):(o=null,_('"&"')),o===null&&(i.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"'))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=$(),o===null&&(o=_e(),o===null&&(i.charCodeAt(r)===36?(o="$",r++):(o=null,_('"$"')),o===null&&(i.charCodeAt(r)===44?(o=",",r++):(o=null,_('","')),o===null&&(i.charCodeAt(r)===59?(o=";",r++):(o=null,_('";"')),o===null&&(i.charCodeAt(r)===58?(o=":",r++):(o=null,_('":"')),o===null&&(i.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o===null&&(i.charCodeAt(r)===38?(o="&",r++):(o=null,_('"&"')),o===null&&(i.charCodeAt(r)===61?(o="=",r++):(o=null,_('"="')),o===null&&(i.charCodeAt(r)===43?(o="+",r++):(o=null,_('"+"')))))))))));else e=null;return e}function Pn(){var e,o;for(e=[],o=Ds();o!==null;)e.push(o),o=Ds();return e}function Ln(){var e,o,u,f,p,m,v,y;if(v=r,y=r,i.substr(r,3).toLowerCase()==="sip"?(e=i.substr(r,3),r+=3):(e=null,_('"SIP"')),e!==null)if(i.charCodeAt(r)===47?(o="/",r++):(o=null,_('"/"')),o!==null){if(f=T(),f!==null)for(u=[];f!==null;)u.push(f),f=T();else u=null;if(u!==null)if(i.charCodeAt(r)===46?(f=".",r++):(f=null,_('"."')),f!==null){if(m=T(),m!==null)for(p=[];m!==null;)p.push(m),m=T();else p=null;p!==null?e=[e,o,u,f,p]:(e=null,r=y)}else e=null,r=y;else e=null,r=y}else e=null,r=y;else e=null,r=y;return e!==null&&(e=function(D){O.sip_version=i.substring(r,D)}(v)),e===null&&(r=v),e}function $r(){var e;return i.substr(r,6)==="INVITE"?(e="INVITE",r+=6):(e=null,_('"INVITE"')),e}function Hr(){var e;return i.substr(r,3)==="ACK"?(e="ACK",r+=3):(e=null,_('"ACK"')),e}function Fr(){var e;return i.substr(r,7)==="OPTIONS"?(e="OPTIONS",r+=7):(e=null,_('"OPTIONS"')),e}function Vr(){var e;return i.substr(r,3)==="BYE"?(e="BYE",r+=3):(e=null,_('"BYE"')),e}function jr(){var e;return i.substr(r,6)==="CANCEL"?(e="CANCEL",r+=6):(e=null,_('"CANCEL"')),e}function qr(){var e;return i.substr(r,8)==="REGISTER"?(e="REGISTER",r+=8):(e=null,_('"REGISTER"')),e}function Br(){var e;return i.substr(r,9)==="SUBSCRIBE"?(e="SUBSCRIBE",r+=9):(e=null,_('"SUBSCRIBE"')),e}function Gr(){var e;return i.substr(r,6)==="NOTIFY"?(e="NOTIFY",r+=6):(e=null,_('"NOTIFY"')),e}function rn(){var e;return i.substr(r,5)==="REFER"?(e="REFER",r+=5):(e=null,_('"REFER"')),e}function ln(){var e,o;return o=r,e=$r(),e===null&&(e=Hr(),e===null&&(e=Fr(),e===null&&(e=Vr(),e===null&&(e=jr(),e===null&&(e=qr(),e===null&&(e=Br(),e===null&&(e=Gr(),e===null&&(e=rn(),e===null&&(e=M()))))))))),e!==null&&(e=function(u){return O.method=i.substring(r,u),O.method}(o)),e===null&&(r=o),e}function Wr(){var e,o,u,f,p,m;return m=r,e=Ln(),e!==null?(o=F(),o!==null?(u=Kr(),u!==null?(f=F(),f!==null?(p=Tl(),p!==null?e=[e,o,u,f,p]:(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m),e}function Kr(){var e,o;return o=r,e=Yr(),e!==null&&(e=function(u,f){O.status_code=parseInt(f.join(""))}(o,e)),e===null&&(r=o),e}function Yr(){var e,o,u,f;return f=r,e=T(),e!==null?(o=T(),o!==null?(u=T(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Tl(){var e,o,u;for(u=r,e=[],o=N(),o===null&&(o=$(),o===null&&(o=_e(),o===null&&(o=V(),o===null&&(o=Q(),o===null&&(o=F(),o===null&&(o=I()))))));o!==null;)e.push(o),o=N(),o===null&&(o=$(),o===null&&(o=_e(),o===null&&(o=V(),o===null&&(o=Q(),o===null&&(o=F(),o===null&&(o=I()))))));return e!==null&&(e=function(f){O.reason_phrase=i.substring(r,f)}(u)),e===null&&(r=u),e}function Qo(){var e,o,u,f,p,m;if(p=r,e=cn(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=cn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=cn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Xo(){var e,o,u,f,p,m;return f=r,p=r,e=X(),e!==null?(m=r,i.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o!==null?(u=X(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){O=i.substring(r,v)}(f)),e===null&&(r=f),e}function $n(){var e,o,u,f,p,m,v;if(p=r,e=W(),e===null)if(m=r,e=Ht(),e!==null){for(o=[],v=r,u=oe(),u!==null?(f=Ht(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=oe(),u!==null?(f=Ht(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D,le;for(le=O.multi_header.length,D=0;D<le;D++)if(O.multi_header[D].parsed===null){O=null;break}O!==null?O=O.multi_header:O=-1}()),e===null&&(r=p),e}function Ht(){var e,o,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=Ft()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=Hn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=Hn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D;O.multi_header||(O.multi_header=[]);try{D=new w(O.uri,O.display_name,O.params),delete O.uri,delete O.display_name,delete O.params}catch{D=null}O.multi_header.push({possition:r,offset:y,parsed:D})}(p)),e===null&&(r=p),e}function Ft(){var e,o,u,f,p;return p=r,e=Us(),e=e!==null?e:"",e!==null?(o=Ae(),o!==null?(u=Ne(),u!==null?(f=ke(),f!==null?e=[e,o,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function Us(){var e,o,u,f,p,m,v;if(p=r,m=r,e=M(),e!==null){for(o=[],v=r,u=U(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=U(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e===null&&(e=ge()),e!==null&&(e=function(y,D){typeof D=="string"?O.display_name=D:O.display_name=D[1].reduce(function(le,xe){return le+xe[0]+xe[1]},D[0])}(p,e)),e===null&&(r=p),e}function Hn(){var e;return e=Jr(),e===null&&(e=ss(),e===null&&(e=Ye())),e}function Jr(){var e,o,u,f,p;return f=r,p=r,i.substr(r,1).toLowerCase()==="q"?(e=i.substr(r,1),r++):(e=null,_('"q"')),e!==null?(o=re(),o!==null?(u=Ke(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.params||(O.params={}),O.params.q=v}(f,e[2])),e===null&&(r=f),e}function ss(){var e,o,u,f,p;return f=r,p=r,i.substr(r,7).toLowerCase()==="expires"?(e=i.substr(r,7),r+=7):(e=null,_('"expires"')),e!==null?(o=re(),o!==null?(u=ns(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.params||(O.params={}),O.params.expires=v}(f,e[2])),e===null&&(r=f),e}function ns(){var e,o,u;if(u=r,o=T(),o!==null)for(e=[];o!==null;)e.push(o),o=T();else e=null;return e!==null&&(e=function(f,p){return parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function Ke(){var e,o,u,f,p,m,v,y;return m=r,v=r,i.charCodeAt(r)===48?(e="0",r++):(e=null,_('"0"')),e!==null?(y=r,i.charCodeAt(r)===46?(o=".",r++):(o=null,_('"."')),o!==null?(u=T(),u=u!==null?u:"",u!==null?(f=T(),f=f!==null?f:"",f!==null?(p=T(),p=p!==null?p:"",p!==null?o=[o,u,f,p]:(o=null,r=y)):(o=null,r=y)):(o=null,r=y)):(o=null,r=y),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(D){return parseFloat(i.substring(r,D))}(m)),e===null&&(r=m),e}function Ye(){var e,o,u,f,p,m;return f=r,p=r,e=M(),e!==null?(m=r,o=re(),o!==null?(u=vl(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v,y,D){O.params||(O.params={}),typeof D>"u"?D=void 0:D=D[1],O.params[y.toLowerCase()]=D}(f,e[0],e[1])),e===null&&(r=f),e}function vl(){var e;return e=M(),e===null&&(e=cs(),e===null&&(e=Oe())),e}function Sl(){var e,o,u,f,p,m;if(p=r,e=Fn(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=Vn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=Vn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Fn(){var e;return i.substr(r,6).toLowerCase()==="render"?(e=i.substr(r,6),r+=6):(e=null,_('"render"')),e===null&&(i.substr(r,7).toLowerCase()==="session"?(e=i.substr(r,7),r+=7):(e=null,_('"session"')),e===null&&(i.substr(r,4).toLowerCase()==="icon"?(e=i.substr(r,4),r+=4):(e=null,_('"icon"')),e===null&&(i.substr(r,5).toLowerCase()==="alert"?(e=i.substr(r,5),r+=5):(e=null,_('"alert"')),e===null&&(e=M())))),e}function Vn(){var e;return e=El(),e===null&&(e=Ye()),e}function El(){var e,o,u,f;return f=r,i.substr(r,8).toLowerCase()==="handling"?(e=i.substr(r,8),r+=8):(e=null,_('"handling"')),e!==null?(o=re(),o!==null?(i.substr(r,8).toLowerCase()==="optional"?(u=i.substr(r,8),r+=8):(u=null,_('"optional"')),u===null&&(i.substr(r,8).toLowerCase()==="required"?(u=i.substr(r,8),r+=8):(u=null,_('"required"')),u===null&&(u=M())),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Zo(){var e,o,u,f,p,m;if(p=r,e=M(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function ea(){var e,o,u;if(u=r,o=T(),o!==null)for(e=[];o!==null;)e.push(o),o=T();else e=null;return e!==null&&(e=function(f,p){O=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function yl(){var e,o;return o=r,e=zr(),e!==null&&(e=function(u){O=i.substring(r,u)}(o)),e===null&&(r=o),e}function zr(){var e,o,u,f,p,m,v,y;if(v=r,e=Qr(),e!==null)if(o=G(),o!==null)if(u=jn(),u!==null){for(f=[],y=r,p=ye(),p!==null?(m=qn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=ye(),p!==null?(m=qn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,o,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function Qr(){var e;return e=Xr(),e===null&&(e=on()),e}function Xr(){var e;return i.substr(r,4).toLowerCase()==="text"?(e=i.substr(r,4),r+=4):(e=null,_('"text"')),e===null&&(i.substr(r,5).toLowerCase()==="image"?(e=i.substr(r,5),r+=5):(e=null,_('"image"')),e===null&&(i.substr(r,5).toLowerCase()==="audio"?(e=i.substr(r,5),r+=5):(e=null,_('"audio"')),e===null&&(i.substr(r,5).toLowerCase()==="video"?(e=i.substr(r,5),r+=5):(e=null,_('"video"')),e===null&&(i.substr(r,11).toLowerCase()==="application"?(e=i.substr(r,11),r+=11):(e=null,_('"application"')),e===null&&(e=an()))))),e}function on(){var e;return i.substr(r,7).toLowerCase()==="message"?(e=i.substr(r,7),r+=7):(e=null,_('"message"')),e===null&&(i.substr(r,9).toLowerCase()==="multipart"?(e=i.substr(r,9),r+=9):(e=null,_('"multipart"')),e===null&&(e=an())),e}function an(){var e;return e=M(),e===null&&(e=Zr()),e}function Zr(){var e,o,u;return u=r,i.substr(r,2).toLowerCase()==="x-"?(e=i.substr(r,2),r+=2):(e=null,_('"x-"')),e!==null?(o=M(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function jn(){var e;return e=an(),e===null&&(e=M()),e}function qn(){var e,o,u,f;return f=r,e=M(),e!==null?(o=re(),o!==null?(u=Cl(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Cl(){var e;return e=M(),e===null&&(e=Oe()),e}function Al(){var e,o,u,f;return f=r,e=Rl(),e!==null?(o=U(),o!==null?(u=ln(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Rl(){var e,o,u;if(u=r,o=T(),o!==null)for(e=[];o!==null;)e.push(o),o=T();else e=null;return e!==null&&(e=function(f,p){O.value=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function ta(){var e,o;return o=r,e=ns(),e!==null&&(e=function(u,f){O=f}(o,e)),e===null&&(r=o),e}function un(){var e,o,u,f,p,m,v;if(p=r,m=r,e=cn(),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=Ye(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=Ye(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y,D){O.event=D.join("").toLowerCase()}(p,e[0])),e===null&&(r=p),e}function cn(){var e,o,u,f,p,m;if(p=r,e=B(),e!==null){for(o=[],m=r,i.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u!==null?(f=B(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,i.charCodeAt(r)===46?(u=".",r++):(u=null,_('"."')),u!==null?(f=B(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function ei(){var e,o,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=Ft()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=fn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=fn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D=O.tag;try{O=new w(O.uri,O.display_name,O.params),D&&O.setParam("tag",D)}catch{O=-1}}()),e===null&&(r=p),e}function fn(){var e;return e=ti(),e===null&&(e=Ye()),e}function ti(){var e,o,u,f,p;return f=r,p=r,i.substr(r,3).toLowerCase()==="tag"?(e=i.substr(r,3),r+=3):(e=null,_('"tag"')),e!==null?(o=re(),o!==null?(u=M(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.tag=v}(f,e[2])),e===null&&(r=f),e}function sa(){var e,o,u;if(u=r,o=T(),o!==null)for(e=[];o!==null;)e.push(o),o=T();else e=null;return e!==null&&(e=function(f,p){O=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function na(){var e,o;return o=r,e=ns(),e!==null&&(e=function(u,f){O=f}(o,e)),e===null&&(r=o),e}function ra(){var e,o,u,f,p,m,v,y,D,le;for(y=r,D=r,e=[],o=Us();o!==null;)e.push(o),o=Us();if(e!==null)if(o=Ae(),o!==null)if(u=Ne(),u!==null)if(f=ke(),f!==null){for(p=[],le=r,m=ye(),m!==null?(v=Ye(),v!==null?m=[m,v]:(m=null,r=le)):(m=null,r=le);m!==null;)p.push(m),le=r,m=ye(),m!==null?(v=Ye(),v!==null?m=[m,v]:(m=null,r=le)):(m=null,r=le);p!==null?e=[e,o,u,f,p]:(e=null,r=D)}else e=null,r=D;else e=null,r=D;else e=null,r=D;else e=null,r=D;return e!==null&&(e=function(xe){try{O=new w(O.uri,O.display_name,O.params)}catch{O=-1}}()),e===null&&(r=y),e}function si(){var e;return e=Bn(),e}function Bn(){var e,o,u,f,p,m,v,y;if(v=r,i.substr(r,6).toLowerCase()==="digest"?(e=i.substr(r,6),r+=6):(e=null,_('"Digest"')),e!==null)if(o=U(),o!==null)if(u=dn(),u!==null){for(f=[],y=r,p=oe(),p!==null?(m=dn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=oe(),p!==null?(m=dn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,o,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e===null&&(e=ks()),e}function ks(){var e,o,u,f,p,m,v,y;if(v=r,e=M(),e!==null)if(o=U(),o!==null)if(u=rs(),u!==null){for(f=[],y=r,p=oe(),p!==null?(m=rs(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=oe(),p!==null?(m=rs(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,o,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function rs(){var e,o,u,f;return f=r,e=M(),e!==null?(o=re(),o!==null?(u=M(),u===null&&(u=Oe()),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function dn(){var e;return e=ni(),e===null&&(e=hn(),e===null&&(e=ii(),e===null&&(e=oi(),e===null&&(e=ai(),e===null&&(e=ui(),e===null&&(e=pn(),e===null&&(e=rs()))))))),e}function ni(){var e,o,u,f;return f=r,i.substr(r,5).toLowerCase()==="realm"?(e=i.substr(r,5),r+=5):(e=null,_('"realm"')),e!==null?(o=re(),o!==null?(u=ri(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function ri(){var e,o;return o=r,e=ge(),e!==null&&(e=function(u,f){O.realm=f}(o,e)),e===null&&(r=o),e}function hn(){var e,o,u,f,p,m,v,y,D;if(y=r,i.substr(r,6).toLowerCase()==="domain"?(e=i.substr(r,6),r+=6):(e=null,_('"domain"')),e!==null)if(o=re(),o!==null)if(u=at(),u!==null)if(f=_n(),f!==null){if(p=[],D=r,v=F(),v!==null)for(m=[];v!==null;)m.push(v),v=F();else m=null;for(m!==null?(v=_n(),v!==null?m=[m,v]:(m=null,r=D)):(m=null,r=D);m!==null;){if(p.push(m),D=r,v=F(),v!==null)for(m=[];v!==null;)m.push(v),v=F();else m=null;m!==null?(v=_n(),v!==null?m=[m,v]:(m=null,r=D)):(m=null,r=D)}p!==null?(m=Ee(),m!==null?e=[e,o,u,f,p,m]:(e=null,r=y)):(e=null,r=y)}else e=null,r=y;else e=null,r=y;else e=null,r=y;else e=null,r=y;return e}function _n(){var e;return e=Mn(),e===null&&(e=sn()),e}function ii(){var e,o,u,f;return f=r,i.substr(r,5).toLowerCase()==="nonce"?(e=i.substr(r,5),r+=5):(e=null,_('"nonce"')),e!==null?(o=re(),o!==null?(u=li(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function li(){var e,o;return o=r,e=ge(),e!==null&&(e=function(u,f){O.nonce=f}(o,e)),e===null&&(r=o),e}function oi(){var e,o,u,f,p;return f=r,p=r,i.substr(r,6).toLowerCase()==="opaque"?(e=i.substr(r,6),r+=6):(e=null,_('"opaque"')),e!==null?(o=re(),o!==null?(u=ge(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.opaque=v}(f,e[2])),e===null&&(r=f),e}function ai(){var e,o,u,f,p;return f=r,i.substr(r,5).toLowerCase()==="stale"?(e=i.substr(r,5),r+=5):(e=null,_('"stale"')),e!==null?(o=re(),o!==null?(p=r,i.substr(r,4).toLowerCase()==="true"?(u=i.substr(r,4),r+=4):(u=null,_('"true"')),u!==null&&(u=function(m){O.stale=!0}()),u===null&&(r=p),u===null&&(p=r,i.substr(r,5).toLowerCase()==="false"?(u=i.substr(r,5),r+=5):(u=null,_('"false"')),u!==null&&(u=function(m){O.stale=!1}()),u===null&&(r=p)),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function ui(){var e,o,u,f,p;return f=r,p=r,i.substr(r,9).toLowerCase()==="algorithm"?(e=i.substr(r,9),r+=9):(e=null,_('"algorithm"')),e!==null?(o=re(),o!==null?(i.substr(r,3).toLowerCase()==="md5"?(u=i.substr(r,3),r+=3):(u=null,_('"MD5"')),u===null&&(i.substr(r,8).toLowerCase()==="md5-sess"?(u=i.substr(r,8),r+=8):(u=null,_('"MD5-sess"')),u===null&&(u=M())),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.algorithm=v.toUpperCase()}(f,e[2])),e===null&&(r=f),e}function pn(){var e,o,u,f,p,m,v,y,D,le;if(y=r,i.substr(r,3).toLowerCase()==="qop"?(e=i.substr(r,3),r+=3):(e=null,_('"qop"')),e!==null)if(o=re(),o!==null)if(u=at(),u!==null){if(D=r,f=Gn(),f!==null){for(p=[],le=r,i.charCodeAt(r)===44?(m=",",r++):(m=null,_('","')),m!==null?(v=Gn(),v!==null?m=[m,v]:(m=null,r=le)):(m=null,r=le);m!==null;)p.push(m),le=r,i.charCodeAt(r)===44?(m=",",r++):(m=null,_('","')),m!==null?(v=Gn(),v!==null?m=[m,v]:(m=null,r=le)):(m=null,r=le);p!==null?f=[f,p]:(f=null,r=D)}else f=null,r=D;f!==null?(p=Ee(),p!==null?e=[e,o,u,f,p]:(e=null,r=y)):(e=null,r=y)}else e=null,r=y;else e=null,r=y;else e=null,r=y;return e}function Gn(){var e,o;return o=r,i.substr(r,8).toLowerCase()==="auth-int"?(e=i.substr(r,8),r+=8):(e=null,_('"auth-int"')),e===null&&(i.substr(r,4).toLowerCase()==="auth"?(e=i.substr(r,4),r+=4):(e=null,_('"auth"')),e===null&&(e=M())),e!==null&&(e=function(u,f){O.qop||(O.qop=[]),O.qop.push(f.toLowerCase())}(o,e)),e===null&&(r=o),e}function ia(){var e,o,u,f,p,m;if(p=r,e=M(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Wn(){var e,o,u,f,p,m,v;if(p=r,m=r,e=Kn(),e!==null){for(o=[],v=r,u=oe(),u!==null?(f=Kn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=oe(),u!==null?(f=Kn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D,le;for(le=O.multi_header.length,D=0;D<le;D++)if(O.multi_header[D].parsed===null){O=null;break}O!==null?O=O.multi_header:O=-1}()),e===null&&(r=p),e}function Kn(){var e,o,u,f,p,m,v;if(p=r,m=r,e=Ft(),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=Ye(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=Ye(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D;O.multi_header||(O.multi_header=[]);try{D=new w(O.uri,O.display_name,O.params),delete O.uri,delete O.display_name,delete O.params}catch{D=null}O.multi_header.push({possition:r,offset:y,parsed:D})}(p)),e===null&&(r=p),e}function ci(){var e,o,u,f,p,m,v;if(p=r,m=r,i.substr(r,3).toLowerCase()==="sip"?(e=i.substr(r,3),r+=3):(e=null,_('"SIP"')),e===null&&(e=M()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=Yn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=Yn(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y,D){if(O.protocol=D.toLowerCase(),O.params||(O.params={}),O.params.text&&O.params.text[0]==='"'){var le=O.params.text;O.text=le.substring(1,le.length-1),delete O.params.text}}(p,e[0])),e===null&&(r=p),e}function Yn(){var e;return e=Il(),e===null&&(e=Ye()),e}function Il(){var e,o,u,f,p,m;if(p=r,m=r,i.substr(r,5).toLowerCase()==="cause"?(e=i.substr(r,5),r+=5):(e=null,_('"cause"')),e!==null)if(o=re(),o!==null){if(f=T(),f!==null)for(u=[];f!==null;)u.push(f),f=T();else u=null;u!==null?e=[e,o,u]:(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e!==null&&(e=function(v,y){O.cause=parseInt(y.join(""))}(p,e[2])),e===null&&(r=p),e}function la(){var e,o,u,f,p,m;if(p=r,e=M(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Jn(){var e,o,u,f,p,m;if(p=r,e=zn(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=zn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=zn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function zn(){var e,o,u,f,p,m;if(p=r,e=Ft(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=Ye(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=Ye(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function bl(){var e,o,u,f,p,m;if(p=r,e=Qn(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=Xn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=Xn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Qn(){var e,o;return o=r,i.substr(r,6).toLowerCase()==="active"?(e=i.substr(r,6),r+=6):(e=null,_('"active"')),e===null&&(i.substr(r,7).toLowerCase()==="pending"?(e=i.substr(r,7),r+=7):(e=null,_('"pending"')),e===null&&(i.substr(r,10).toLowerCase()==="terminated"?(e=i.substr(r,10),r+=10):(e=null,_('"terminated"')),e===null&&(e=M()))),e!==null&&(e=function(u){O.state=i.substring(r,u)}(o)),e===null&&(r=o),e}function Xn(){var e,o,u,f,p;return f=r,p=r,i.substr(r,6).toLowerCase()==="reason"?(e=i.substr(r,6),r+=6):(e=null,_('"reason"')),e!==null?(o=re(),o!==null?(u=wl(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){typeof v<"u"&&(O.reason=v)}(f,e[2])),e===null&&(r=f),e===null&&(f=r,p=r,i.substr(r,7).toLowerCase()==="expires"?(e=i.substr(r,7),r+=7):(e=null,_('"expires"')),e!==null?(o=re(),o!==null?(u=ns(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){typeof v<"u"&&(O.expires=v)}(f,e[2])),e===null&&(r=f),e===null&&(f=r,p=r,i.substr(r,11).toLowerCase()==="retry_after"?(e=i.substr(r,11),r+=11):(e=null,_('"retry_after"')),e!==null?(o=re(),o!==null?(u=ns(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){typeof v<"u"&&(O.retry_after=v)}(f,e[2])),e===null&&(r=f),e===null&&(e=Ye()))),e}function wl(){var e;return i.substr(r,11).toLowerCase()==="deactivated"?(e=i.substr(r,11),r+=11):(e=null,_('"deactivated"')),e===null&&(i.substr(r,9).toLowerCase()==="probation"?(e=i.substr(r,9),r+=9):(e=null,_('"probation"')),e===null&&(i.substr(r,8).toLowerCase()==="rejected"?(e=i.substr(r,8),r+=8):(e=null,_('"rejected"')),e===null&&(i.substr(r,7).toLowerCase()==="timeout"?(e=i.substr(r,7),r+=7):(e=null,_('"timeout"')),e===null&&(i.substr(r,6).toLowerCase()==="giveup"?(e=i.substr(r,6),r+=6):(e=null,_('"giveup"')),e===null&&(i.substr(r,10).toLowerCase()==="noresource"?(e=i.substr(r,10),r+=10):(e=null,_('"noresource"')),e===null&&(i.substr(r,9).toLowerCase()==="invariant"?(e=i.substr(r,9),r+=9):(e=null,_('"invariant"')),e===null&&(e=M()))))))),e}function oa(){var e;return e=j(),e=e!==null?e:"",e}function aa(){var e,o,u,f,p,m;if(p=r,e=M(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=M(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e=e!==null?e:"",e}function fi(){var e,o,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=Ft()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=di(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=di(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var D=O.tag;try{O=new w(O.uri,O.display_name,O.params),D&&O.setParam("tag",D)}catch{O=-1}}()),e===null&&(r=p),e}function di(){var e;return e=ti(),e===null&&(e=Ye()),e}function Zn(){var e,o,u,f,p,m;if(p=r,e=Ms(),e!==null){for(o=[],m=r,u=oe(),u!==null?(f=Ms(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=oe(),u!==null?(f=Ms(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function Ms(){var e,o,u,f,p,m,v,y;if(v=r,e=vi(),e!==null)if(o=U(),o!==null)if(u=yi(),u!==null){for(f=[],y=r,p=ye(),p!==null?(m=er(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=ye(),p!==null?(m=er(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,o,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function er(){var e;return e=hi(),e===null&&(e=_i(),e===null&&(e=pi(),e===null&&(e=mi(),e===null&&(e=gi(),e===null&&(e=Ye()))))),e}function hi(){var e,o,u,f,p;return f=r,p=r,i.substr(r,3).toLowerCase()==="ttl"?(e=i.substr(r,3),r+=3):(e=null,_('"ttl"')),e!==null?(o=re(),o!==null?(u=Ai(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.ttl=v}(f,e[2])),e===null&&(r=f),e}function _i(){var e,o,u,f,p;return f=r,p=r,i.substr(r,5).toLowerCase()==="maddr"?(e=i.substr(r,5),r+=5):(e=null,_('"maddr"')),e!==null?(o=re(),o!==null?(u=cs(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.maddr=v}(f,e[2])),e===null&&(r=f),e}function pi(){var e,o,u,f,p;return f=r,p=r,i.substr(r,8).toLowerCase()==="received"?(e=i.substr(r,8),r+=8):(e=null,_('"received"')),e!==null?(o=re(),o!==null?(u=Kt(),u===null&&(u=Te()),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.received=v}(f,e[2])),e===null&&(r=f),e}function mi(){var e,o,u,f,p;return f=r,p=r,i.substr(r,6).toLowerCase()==="branch"?(e=i.substr(r,6),r+=6):(e=null,_('"branch"')),e!==null?(o=re(),o!==null?(u=M(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.branch=v}(f,e[2])),e===null&&(r=f),e}function gi(){var e,o,u,f,p;return f=r,i.substr(r,5).toLowerCase()==="rport"?(e=i.substr(r,5),r+=5):(e=null,_('"rport"')),e!==null?(p=r,o=re(),o!==null?(u=Ti(),u!==null?o=[o,u]:(o=null,r=p)):(o=null,r=p),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e}function Ti(){var e,o,u,f,p,m,v;return m=r,v=r,e=T(),e=e!==null?e:"",e!==null?(o=T(),o=o!==null?o:"",o!==null?(u=T(),u=u!==null?u:"",u!==null?(f=T(),f=f!==null?f:"",f!==null?(p=T(),p=p!==null?p:"",p!==null?e=[e,o,u,f,p]:(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(y,D){O.rport=parseInt(D.join(""))}(m,e)),e===null&&(r=m),e}function vi(){var e,o,u,f,p,m;return m=r,e=Si(),e!==null?(o=G(),o!==null?(u=M(),u!==null?(f=G(),f!==null?(p=Ei(),p!==null?e=[e,o,u,f,p]:(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m),e}function Si(){var e,o;return o=r,i.substr(r,3).toLowerCase()==="sip"?(e=i.substr(r,3),r+=3):(e=null,_('"SIP"')),e===null&&(e=M()),e!==null&&(e=function(u,f){O.protocol=f}(o,e)),e===null&&(r=o),e}function Ei(){var e,o;return o=r,i.substr(r,3).toLowerCase()==="udp"?(e=i.substr(r,3),r+=3):(e=null,_('"UDP"')),e===null&&(i.substr(r,3).toLowerCase()==="tcp"?(e=i.substr(r,3),r+=3):(e=null,_('"TCP"')),e===null&&(i.substr(r,3).toLowerCase()==="tls"?(e=i.substr(r,3),r+=3):(e=null,_('"TLS"')),e===null&&(i.substr(r,4).toLowerCase()==="sctp"?(e=i.substr(r,4),r+=4):(e=null,_('"SCTP"')),e===null&&(e=M())))),e!==null&&(e=function(u,f){O.transport=f}(o,e)),e===null&&(r=o),e}function yi(){var e,o,u,f,p;return f=r,e=Ci(),e!==null?(p=r,o=rt(),o!==null?(u=tr(),u!==null?o=[o,u]:(o=null,r=p)):(o=null,r=p),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=f)):(e=null,r=f),e}function Ci(){var e,o;return o=r,e=Kt(),e===null&&(e=Qs(),e===null&&(e=zs())),e!==null&&(e=function(u){O.host=i.substring(r,u)}(o)),e===null&&(r=o),e}function tr(){var e,o,u,f,p,m,v;return m=r,v=r,e=T(),e=e!==null?e:"",e!==null?(o=T(),o=o!==null?o:"",o!==null?(u=T(),u=u!==null?u:"",u!==null?(f=T(),f=f!==null?f:"",f!==null?(p=T(),p=p!==null?p:"",p!==null?e=[e,o,u,f,p]:(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(y,D){O.port=parseInt(D.join(""))}(m,e)),e===null&&(r=m),e}function Ai(){var e,o,u,f,p;return f=r,p=r,e=T(),e!==null?(o=T(),o=o!==null?o:"",o!==null?(u=T(),u=u!==null?u:"",u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){return parseInt(v.join(""))}(f,e)),e===null&&(r=f),e}function ua(){var e;return e=Bn(),e}function Ol(){var e,o,u,f,p,m;if(p=r,e=sr(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=nr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=nr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function sr(){var e,o;return o=r,e=ns(),e!==null&&(e=function(u,f){O.expires=f}(o,e)),e===null&&(r=o),e}function nr(){var e;return e=Dl(),e===null&&(e=Ye()),e}function Dl(){var e,o,u,f,p;return f=r,p=r,i.substr(r,9).toLowerCase()==="refresher"?(e=i.substr(r,9),r+=9):(e=null,_('"refresher"')),e!==null?(o=re(),o!==null?(i.substr(r,3).toLowerCase()==="uac"?(u=i.substr(r,3),r+=3):(u=null,_('"uac"')),u===null&&(i.substr(r,3).toLowerCase()==="uas"?(u=i.substr(r,3),r+=3):(u=null,_('"uas"'))),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.refresher=v.toLowerCase()}(f,e[2])),e===null&&(r=f),e}function Nl(){var e,o,u,f;return f=r,e=M(),e!==null?(o=q(),o!==null?(u=xl(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function xl(){var e,o;for(e=[],o=Y(),o===null&&(o=Q(),o===null&&(o=U()));o!==null;)e.push(o),o=Y(),o===null&&(o=Q(),o===null&&(o=U()));return e}function ca(){var e,o;for(e=[],o=A();o!==null;)e.push(o),o=A();return e}function Ul(){var e,o,u;return u=r,i.substr(r,5)==="uuid:"?(e="uuid:",r+=5):(e=null,_('"uuid:"')),e!==null?(o=Vt(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function Vt(){var e,o,u,f,p,m,v,y,D,le,xe;return le=r,xe=r,e=Ri(),e!==null?(i.charCodeAt(r)===45?(o="-",r++):(o=null,_('"-"')),o!==null?(u=jt(),u!==null?(i.charCodeAt(r)===45?(f="-",r++):(f=null,_('"-"')),f!==null?(p=jt(),p!==null?(i.charCodeAt(r)===45?(m="-",r++):(m=null,_('"-"')),m!==null?(v=jt(),v!==null?(i.charCodeAt(r)===45?(y="-",r++):(y=null,_('"-"')),y!==null?(D=kl(),D!==null?e=[e,o,u,f,p,m,v,y,D]:(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe)):(e=null,r=xe),e!==null&&(e=function(Ot,Ps){O=i.substring(r+5,Ot)}(le,e[0])),e===null&&(r=le),e}function jt(){var e,o,u,f,p;return p=r,e=E(),e!==null?(o=E(),o!==null?(u=E(),u!==null?(f=E(),f!==null?e=[e,o,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function Ri(){var e,o,u;return u=r,e=jt(),e!==null?(o=jt(),o!==null?e=[e,o]:(e=null,r=u)):(e=null,r=u),e}function kl(){var e,o,u,f;return f=r,e=jt(),e!==null?(o=jt(),o!==null?(u=jt(),u!==null?e=[e,o,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function fa(){var e,o,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=Ft()),e!==null){for(o=[],v=r,u=ye(),u!==null?(f=Ye(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)o.push(u),v=r,u=ye(),u!==null?(f=Ye(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);o!==null?e=[e,o]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){try{O=new w(O.uri,O.display_name,O.params)}catch{O=-1}}()),e===null&&(r=p),e}function Ml(){var e,o,u,f,p,m;if(p=r,e=rr(),e!==null){for(o=[],m=r,u=ye(),u!==null?(f=ir(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)o.push(u),m=r,u=ye(),u!==null?(f=ir(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);o!==null?e=[e,o]:(e=null,r=p)}else e=null,r=p;return e}function rr(){var e,o,u,f,p,m;return f=r,p=r,e=X(),e!==null?(m=r,i.charCodeAt(r)===64?(o="@",r++):(o=null,_('"@"')),o!==null?(u=X(),u!==null?o=[o,u]:(o=null,r=m)):(o=null,r=m),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){O.call_id=i.substring(r,v)}(f)),e===null&&(r=f),e}function ir(){var e;return e=Ii(),e===null&&(e=bi(),e===null&&(e=Pl(),e===null&&(e=Ye()))),e}function Ii(){var e,o,u,f,p;return f=r,p=r,i.substr(r,6)==="to-tag"?(e="to-tag",r+=6):(e=null,_('"to-tag"')),e!==null?(o=re(),o!==null?(u=M(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.to_tag=v}(f,e[2])),e===null&&(r=f),e}function bi(){var e,o,u,f,p;return f=r,p=r,i.substr(r,8)==="from-tag"?(e="from-tag",r+=8):(e=null,_('"from-tag"')),e!==null?(o=re(),o!==null?(u=M(),u!==null?e=[e,o,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){O.from_tag=v}(f,e[2])),e===null&&(r=f),e}function Pl(){var e,o;return o=r,i.substr(r,10)==="early-only"?(e="early-only",r+=10):(e=null,_('"early-only"')),e!==null&&(e=function(u){O.early_only=!0}()),e===null&&(r=o),e}function da(e){e.sort();for(var o=null,u=[],f=0;f<e.length;f++)e[f]!==o&&(u.push(e[f]),o=e[f]);return u}function Ll(){for(var e=1,o=1,u=!1,f=0;f<Math.max(r,h);f++){var p=i.charAt(f);p===`
|
|
4
|
+
`?(u||e++,o=1,u=!1):p==="\r"||p==="\u2028"||p==="\u2029"?(e++,o=1,u=!0):(o++,u=!1)}return{line:e,column:o}}var ds=Ys(),w=Uu(),O={},wi=n[a]();if(wi===null||r!==i.length){var Oi=Math.max(r,h),$l=Oi<i.length?i.charAt(Oi):null,l=Ll();return new this.SyntaxError(da(d),$l,Oi,l.line,l.column),-1}return O},toSource:function(){return this._source}};return t.SyntaxError=function(s,i,a,n,r){function h(d,_){var g,T;switch(d.length){case 0:g="end of input";break;case 1:g=d[0];break;default:g=d.slice(0,d.length-1).join(", ")+" or "+d[d.length-1]}return T=_?c(_):"end of input","Expected "+g+" but "+T+" found."}this.name="SyntaxError",this.expected=s,this.found=i,this.message=h(s,i),this.offset=a,this.line=n,this.column=r},t.SyntaxError.prototype=Error.prototype,t}()),_a}var pa,Xu;function Ys(){if(Xu)return pa;Xu=1;function c(_,g){var T;if(typeof Symbol>"u"||_[Symbol.iterator]==null){if(Array.isArray(_)||(T=t(_))||g&&_&&typeof _.length=="number"){T&&(_=T);var S=0,E=function(){};return{s:E,n:function(){return S>=_.length?{done:!0}:{done:!1,value:_[S++]}},e:function(I){throw I},f:E}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
5
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var C=!0,A=!1,R;return{s:function(){T=_[Symbol.iterator]()},n:function(){var I=T.next();return C=I.done,I},e:function(I){A=!0,R=I},f:function(){try{!C&&T.return!=null&&T.return()}finally{if(A)throw R}}}}function t(_,g){if(_){if(typeof _=="string")return s(_,g);var T=Object.prototype.toString.call(_).slice(8,-1);if(T==="Object"&&_.constructor&&(T=_.constructor.name),T==="Map"||T==="Set")return Array.from(_);if(T==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(T))return s(_,g)}}function s(_,g){(g==null||g>_.length)&&(g=_.length);for(var T=0,S=new Array(g);T<g;T++)S[T]=_[T];return S}function i(_,g){if(!(_ instanceof g))throw new TypeError("Cannot call a class as a function")}function a(_,g){for(var T=0;T<g.length;T++){var S=g[T];S.enumerable=S.enumerable||!1,S.configurable=!0,"value"in S&&(S.writable=!0),Object.defineProperty(_,S.key,S)}}function n(_,g,T){return g&&a(_.prototype,g),T&&a(_,T),_}var r=ot,h=wt(),d=us();return pa=function(){n(_,null,[{key:"parse",value:function(T){if(T=d.parse(T,"SIP_URI"),T!==-1)return T}}]);function _(g,T,S,E){var C=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},A=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{};if(i(this,_),!S)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=g||r.SIP,this._user=T,this._host=S,this._port=E;for(var R in C)Object.prototype.hasOwnProperty.call(C,R)&&this.setParam(R,C[R]);for(var F in A)Object.prototype.hasOwnProperty.call(A,F)&&this.setHeader(F,A[F])}return n(_,[{key:"setParam",value:function(T,S){T&&(this._parameters[T.toLowerCase()]=typeof S>"u"||S===null?null:S.toString())}},{key:"getParam",value:function(T){if(T)return this._parameters[T.toLowerCase()]}},{key:"hasParam",value:function(T){if(T)return this._parameters.hasOwnProperty(T.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(T){if(T=T.toLowerCase(),this._parameters.hasOwnProperty(T)){var S=this._parameters[T];return delete this._parameters[T],S}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"setHeader",value:function(T,S){this._headers[h.headerize(T)]=Array.isArray(S)?S:[S]}},{key:"getHeader",value:function(T){if(T)return this._headers[h.headerize(T)]}},{key:"hasHeader",value:function(T){if(T)return this._headers.hasOwnProperty(h.headerize(T))&&!0||!1}},{key:"deleteHeader",value:function(T){if(T=h.headerize(T),this._headers.hasOwnProperty(T)){var S=this._headers[T];return delete this._headers[T],S}}},{key:"clearHeaders",value:function(){this._headers={}}},{key:"clone",value:function(){return new _(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}},{key:"toString",value:function(){var T=[],S="".concat(this._scheme,":");this._user&&(S+="".concat(h.escapeUser(this._user),"@")),S+=this._host,(this._port||this._port===0)&&(S+=":".concat(this._port));for(var E in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,E)&&(S+=";".concat(E),this._parameters[E]!==null&&(S+="=".concat(this._parameters[E])));for(var C in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,C)){var A=c(this._headers[C]),R;try{for(A.s();!(R=A.n()).done;){var F=R.value;T.push("".concat(C,"=").concat(F))}}catch(I){A.e(I)}finally{A.f()}}return T.length>0&&(S+="?".concat(T.join("&"))),S}},{key:"toAor",value:function(T){var S="".concat(this._scheme,":");return this._user&&(S+="".concat(h.escapeUser(this._user),"@")),S+=this._host,T&&(this._port||this._port===0)&&(S+=":".concat(this._port)),S}},{key:"scheme",get:function(){return this._scheme},set:function(T){this._scheme=T.toLowerCase()}},{key:"user",get:function(){return this._user},set:function(T){this._user=T}},{key:"host",get:function(){return this._host},set:function(T){this._host=T.toLowerCase()}},{key:"port",get:function(){return this._port},set:function(T){this._port=T===0?T:parseInt(T,10)||null}}]),_}(),pa}var Zu;function wt(){if(Zu)return tt;Zu=1;function c(g){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?c=function(S){return typeof S}:c=function(S){return S&&typeof Symbol=="function"&&S.constructor===Symbol&&S!==Symbol.prototype?"symbol":typeof S},c(g)}function t(g,T){var S;if(typeof Symbol>"u"||g[Symbol.iterator]==null){if(Array.isArray(g)||(S=s(g))||T&&g&&typeof g.length=="number"){S&&(g=S);var E=0,C=function(){};return{s:C,n:function(){return E>=g.length?{done:!0}:{done:!1,value:g[E++]}},e:function(ie){throw ie},f:C}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
6
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var A=!0,R=!1,F;return{s:function(){S=g[Symbol.iterator]()},n:function(){var ie=S.next();return A=ie.done,ie},e:function(ie){R=!0,F=ie},f:function(){try{!A&&S.return!=null&&S.return()}finally{if(R)throw F}}}}function s(g,T){if(g){if(typeof g=="string")return i(g,T);var S=Object.prototype.toString.call(g).slice(8,-1);if(S==="Object"&&g.constructor&&(S=g.constructor.name),S==="Map"||S==="Set")return Array.from(g);if(S==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(S))return i(g,T)}}function i(g,T){(T==null||T>g.length)&&(T=g.length);for(var S=0,E=new Array(T);S<T;S++)E[S]=g[S];return E}var a=ot,n=Ys(),r=us();tt.str_utf8_length=function(g){return unescape(encodeURIComponent(g)).length};var h=tt.isFunction=function(g){return g!==void 0?Object.prototype.toString.call(g)==="[object Function]":!1};tt.isString=function(g){return g!==void 0?Object.prototype.toString.call(g)==="[object String]":!1},tt.isDecimal=function(g){return!isNaN(g)&&parseFloat(g)===parseInt(g,10)},tt.isEmpty=function(g){return g===null||g===""||g===void 0||Array.isArray(g)&&g.length===0||typeof g=="number"&&isNaN(g)},tt.hasMethods=function(g){for(var T=arguments.length,S=new Array(T>1?T-1:0),E=1;E<T;E++)S[E-1]=arguments[E];for(var C=0,A=S;C<A.length;C++){var R=A[C];if(h(g[R]))return!1}return!0};var d=tt.createRandomToken=function(g){var T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:32,S,E,C="";for(S=0;S<g;S++)E=Math.random()*T|0,C+=E.toString(T);return C};tt.newTag=function(){return d(10)},tt.newUUID=function(){var g="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(T){var S=Math.random()*16|0,E=T==="x"?S:S&3|8;return E.toString(16)});return g},tt.hostType=function(g){if(g){if(g=r.parse(g,"host"),g!==-1)return g.host_type}else return};var _=tt.escapeUser=function(g){return encodeURIComponent(decodeURIComponent(g)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/")};return tt.normalizeTarget=function(g,T){if(g){if(g instanceof n)return g;if(typeof g=="string"){var S=g.split("@"),E,C;switch(S.length){case 1:if(!T)return;E=g,C=T;break;case 2:E=S[0],C=S[1];break;default:E=S.slice(0,S.length-1).join("@"),C=S[S.length-1]}E=E.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(E)&&(E=E.replace(/[-.()]/g,"")),g="".concat(a.SIP,":").concat(_(E),"@").concat(C);var A;return(A=n.parse(g))?A:void 0}else return}else return},tt.headerize=function(g){var T={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},S=g.toLowerCase().replace(/_/g,"-").split("-"),E="",C=S.length,A;for(A=0;A<C;A++)A!==0&&(E+="-"),E+=S[A].charAt(0).toUpperCase()+S[A].substring(1);return T[E]&&(E=T[E]),E},tt.sipErrorCause=function(g){for(var T in a.SIP_ERROR_CAUSES)if(a.SIP_ERROR_CAUSES[T].indexOf(g)!==-1)return a.causes[T];return a.causes.SIP_FAILURE_CODE},tt.getRandomTestNetIP=function(){function g(T,S){return Math.floor(Math.random()*(S-T+1)+T)}return"192.0.2.".concat(g(1,254))},tt.calculateMD5=function(g){function T(ge,ue){return ge<<ue|ge>>>32-ue}function S(ge,ue){var me=ge&2147483648,we=ue&2147483648,Ne=ge&1073741824,et=ue&1073741824,$e=(ge&1073741823)+(ue&1073741823);return Ne&et?$e^2147483648^me^we:Ne|et?$e&1073741824?$e^3221225472^me^we:$e^1073741824^me^we:$e^me^we}function E(ge,ue,me){return ge&ue|~ge&me}function C(ge,ue,me){return ge&me|ue&~me}function A(ge,ue,me){return ge^ue^me}function R(ge,ue,me){return ue^(ge|~me)}function F(ge,ue,me,we,Ne,et,$e){return ge=S(ge,S(S(E(ue,me,we),Ne),$e)),S(T(ge,et),ue)}function I(ge,ue,me,we,Ne,et,$e){return ge=S(ge,S(S(C(ue,me,we),Ne),$e)),S(T(ge,et),ue)}function ie(ge,ue,me,we,Ne,et,$e){return ge=S(ge,S(S(A(ue,me,we),Ne),$e)),S(T(ge,et),ue)}function N(ge,ue,me,we,Ne,et,$e){return ge=S(ge,S(S(R(ue,me,we),Ne),$e)),S(T(ge,et),ue)}function $(ge){for(var ue,me=ge.length,we=me+8,Ne=(we-we%64)/64,et=(Ne+1)*16,$e=new Array(et-1),$t=0,_t=0;_t<me;)ue=(_t-_t%4)/4,$t=_t%4*8,$e[ue]=$e[ue]|ge.charCodeAt(_t)<<$t,_t++;return ue=(_t-_t%4)/4,$t=_t%4*8,$e[ue]=$e[ue]|128<<$t,$e[et-2]=me<<3,$e[et-1]=me>>>29,$e}function ve(ge){var ue="",me="",we,Ne;for(Ne=0;Ne<=3;Ne++)we=ge>>>Ne*8&255,me="0".concat(we.toString(16)),ue=ue+me.substr(me.length-2,2);return ue}function _e(ge){for(var ue="",me=0;me<ge.length;me++){var we=ge.charCodeAt(me);we<128?ue+=String.fromCharCode(we):we>127&&we<2048?(ue+=String.fromCharCode(we>>6|192),ue+=String.fromCharCode(we&63|128)):(ue+=String.fromCharCode(we>>12|224),ue+=String.fromCharCode(we>>6&63|128),ue+=String.fromCharCode(we&63|128))}return ue}var U=[],x,q,j,Y,V,Q,k,M,B,Fe=7,X=12,W=17,G=22,re=5,pe=9,Ie=14,ke=20,Ae=4,oe=11,ye=16,rt=23,at=6,Ee=10,Ce=15,be=21;for(g=_e(g),U=$(g),Q=1732584193,k=4023233417,M=2562383102,B=271733878,x=0;x<U.length;x+=16)q=Q,j=k,Y=M,V=B,Q=F(Q,k,M,B,U[x+0],Fe,3614090360),B=F(B,Q,k,M,U[x+1],X,3905402710),M=F(M,B,Q,k,U[x+2],W,606105819),k=F(k,M,B,Q,U[x+3],G,3250441966),Q=F(Q,k,M,B,U[x+4],Fe,4118548399),B=F(B,Q,k,M,U[x+5],X,1200080426),M=F(M,B,Q,k,U[x+6],W,2821735955),k=F(k,M,B,Q,U[x+7],G,4249261313),Q=F(Q,k,M,B,U[x+8],Fe,1770035416),B=F(B,Q,k,M,U[x+9],X,2336552879),M=F(M,B,Q,k,U[x+10],W,4294925233),k=F(k,M,B,Q,U[x+11],G,2304563134),Q=F(Q,k,M,B,U[x+12],Fe,1804603682),B=F(B,Q,k,M,U[x+13],X,4254626195),M=F(M,B,Q,k,U[x+14],W,2792965006),k=F(k,M,B,Q,U[x+15],G,1236535329),Q=I(Q,k,M,B,U[x+1],re,4129170786),B=I(B,Q,k,M,U[x+6],pe,3225465664),M=I(M,B,Q,k,U[x+11],Ie,643717713),k=I(k,M,B,Q,U[x+0],ke,3921069994),Q=I(Q,k,M,B,U[x+5],re,3593408605),B=I(B,Q,k,M,U[x+10],pe,38016083),M=I(M,B,Q,k,U[x+15],Ie,3634488961),k=I(k,M,B,Q,U[x+4],ke,3889429448),Q=I(Q,k,M,B,U[x+9],re,568446438),B=I(B,Q,k,M,U[x+14],pe,3275163606),M=I(M,B,Q,k,U[x+3],Ie,4107603335),k=I(k,M,B,Q,U[x+8],ke,1163531501),Q=I(Q,k,M,B,U[x+13],re,2850285829),B=I(B,Q,k,M,U[x+2],pe,4243563512),M=I(M,B,Q,k,U[x+7],Ie,1735328473),k=I(k,M,B,Q,U[x+12],ke,2368359562),Q=ie(Q,k,M,B,U[x+5],Ae,4294588738),B=ie(B,Q,k,M,U[x+8],oe,2272392833),M=ie(M,B,Q,k,U[x+11],ye,1839030562),k=ie(k,M,B,Q,U[x+14],rt,4259657740),Q=ie(Q,k,M,B,U[x+1],Ae,2763975236),B=ie(B,Q,k,M,U[x+4],oe,1272893353),M=ie(M,B,Q,k,U[x+7],ye,4139469664),k=ie(k,M,B,Q,U[x+10],rt,3200236656),Q=ie(Q,k,M,B,U[x+13],Ae,681279174),B=ie(B,Q,k,M,U[x+0],oe,3936430074),M=ie(M,B,Q,k,U[x+3],ye,3572445317),k=ie(k,M,B,Q,U[x+6],rt,76029189),Q=ie(Q,k,M,B,U[x+9],Ae,3654602809),B=ie(B,Q,k,M,U[x+12],oe,3873151461),M=ie(M,B,Q,k,U[x+15],ye,530742520),k=ie(k,M,B,Q,U[x+2],rt,3299628645),Q=N(Q,k,M,B,U[x+0],at,4096336452),B=N(B,Q,k,M,U[x+7],Ee,1126891415),M=N(M,B,Q,k,U[x+14],Ce,2878612391),k=N(k,M,B,Q,U[x+5],be,4237533241),Q=N(Q,k,M,B,U[x+12],at,1700485571),B=N(B,Q,k,M,U[x+3],Ee,2399980690),M=N(M,B,Q,k,U[x+10],Ce,4293915773),k=N(k,M,B,Q,U[x+1],be,2240044497),Q=N(Q,k,M,B,U[x+8],at,1873313359),B=N(B,Q,k,M,U[x+15],Ee,4264355552),M=N(M,B,Q,k,U[x+6],Ce,2734768916),k=N(k,M,B,Q,U[x+13],be,1309151649),Q=N(Q,k,M,B,U[x+4],at,4149444226),B=N(B,Q,k,M,U[x+11],Ee,3174756917),M=N(M,B,Q,k,U[x+2],Ce,718787259),k=N(k,M,B,Q,U[x+9],be,3951481745),Q=S(Q,q),k=S(k,j),M=S(M,Y),B=S(B,V);var Oe=ve(Q)+ve(k)+ve(M)+ve(B);return Oe.toLowerCase()},tt.closeMediaStream=function(g){if(g)try{var T;if(g.getTracks){T=g.getTracks();var S=t(T),E;try{for(S.s();!(E=S.n()).done;){var C=E.value;C.stop()}}catch($){S.e($)}finally{S.f()}}else{T=g.getAudioTracks();var A=t(T),R;try{for(A.s();!(R=A.n()).done;){var F=R.value;F.stop()}}catch($){A.e($)}finally{A.f()}T=g.getVideoTracks();var I=t(T),ie;try{for(I.s();!(ie=I.n()).done;){var N=ie.value;N.stop()}}catch($){I.e($)}finally{I.f()}}}catch{(typeof g.stop=="function"||c(g.stop)==="object")&&g.stop()}},tt.cloneArray=function(g){return g&&g.slice()||[]},tt.cloneObject=function(g){var T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return g&&Object.assign({},g)||T},tt}var ku={exports:{}},_r=typeof Reflect=="object"?Reflect:null,ec=_r&&typeof _r.apply=="function"?_r.apply:function(t,s,i){return Function.prototype.apply.call(t,s,i)},So;_r&&typeof _r.ownKeys=="function"?So=_r.ownKeys:Object.getOwnPropertySymbols?So=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:So=function(t){return Object.getOwnPropertyNames(t)};function Sh(c){console&&console.warn&&console.warn(c)}var Xf=Number.isNaN||function(t){return t!==t};function Le(){Le.init.call(this)}ku.exports=Le;ku.exports.once=Ah;Le.EventEmitter=Le;Le.prototype._events=void 0;Le.prototype._eventsCount=0;Le.prototype._maxListeners=void 0;var tc=10;function Wo(c){if(typeof c!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof c)}Object.defineProperty(Le,"defaultMaxListeners",{enumerable:!0,get:function(){return tc},set:function(c){if(typeof c!="number"||c<0||Xf(c))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+c+".");tc=c}});Le.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Le.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Xf(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Zf(c){return c._maxListeners===void 0?Le.defaultMaxListeners:c._maxListeners}Le.prototype.getMaxListeners=function(){return Zf(this)};Le.prototype.emit=function(t){for(var s=[],i=1;i<arguments.length;i++)s.push(arguments[i]);var a=t==="error",n=this._events;if(n!==void 0)a=a&&n.error===void 0;else if(!a)return!1;if(a){var r;if(s.length>0&&(r=s[0]),r instanceof Error)throw r;var h=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw h.context=r,h}var d=n[t];if(d===void 0)return!1;if(typeof d=="function")ec(d,this,s);else for(var _=d.length,g=rd(d,_),i=0;i<_;++i)ec(g[i],this,s);return!0};function ed(c,t,s,i){var a,n,r;if(Wo(s),n=c._events,n===void 0?(n=c._events=Object.create(null),c._eventsCount=0):(n.newListener!==void 0&&(c.emit("newListener",t,s.listener?s.listener:s),n=c._events),r=n[t]),r===void 0)r=n[t]=s,++c._eventsCount;else if(typeof r=="function"?r=n[t]=i?[s,r]:[r,s]:i?r.unshift(s):r.push(s),a=Zf(c),a>0&&r.length>a&&!r.warned){r.warned=!0;var h=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");h.name="MaxListenersExceededWarning",h.emitter=c,h.type=t,h.count=r.length,Sh(h)}return c}Le.prototype.addListener=function(t,s){return ed(this,t,s,!1)};Le.prototype.on=Le.prototype.addListener;Le.prototype.prependListener=function(t,s){return ed(this,t,s,!0)};function Eh(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function td(c,t,s){var i={fired:!1,wrapFn:void 0,target:c,type:t,listener:s},a=Eh.bind(i);return a.listener=s,i.wrapFn=a,a}Le.prototype.once=function(t,s){return Wo(s),this.on(t,td(this,t,s)),this};Le.prototype.prependOnceListener=function(t,s){return Wo(s),this.prependListener(t,td(this,t,s)),this};Le.prototype.removeListener=function(t,s){var i,a,n,r,h;if(Wo(s),a=this._events,a===void 0)return this;if(i=a[t],i===void 0)return this;if(i===s||i.listener===s)--this._eventsCount===0?this._events=Object.create(null):(delete a[t],a.removeListener&&this.emit("removeListener",t,i.listener||s));else if(typeof i!="function"){for(n=-1,r=i.length-1;r>=0;r--)if(i[r]===s||i[r].listener===s){h=i[r].listener,n=r;break}if(n<0)return this;n===0?i.shift():yh(i,n),i.length===1&&(a[t]=i[0]),a.removeListener!==void 0&&this.emit("removeListener",t,h||s)}return this};Le.prototype.off=Le.prototype.removeListener;Le.prototype.removeAllListeners=function(t){var s,i,a;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[t]),this;if(arguments.length===0){var n=Object.keys(i),r;for(a=0;a<n.length;++a)r=n[a],r!=="removeListener"&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(s=i[t],typeof s=="function")this.removeListener(t,s);else if(s!==void 0)for(a=s.length-1;a>=0;a--)this.removeListener(t,s[a]);return this};function sd(c,t,s){var i=c._events;if(i===void 0)return[];var a=i[t];return a===void 0?[]:typeof a=="function"?s?[a.listener||a]:[a]:s?Ch(a):rd(a,a.length)}Le.prototype.listeners=function(t){return sd(this,t,!0)};Le.prototype.rawListeners=function(t){return sd(this,t,!1)};Le.listenerCount=function(c,t){return typeof c.listenerCount=="function"?c.listenerCount(t):nd.call(c,t)};Le.prototype.listenerCount=nd;function nd(c){var t=this._events;if(t!==void 0){var s=t[c];if(typeof s=="function")return 1;if(s!==void 0)return s.length}return 0}Le.prototype.eventNames=function(){return this._eventsCount>0?So(this._events):[]};function rd(c,t){for(var s=new Array(t),i=0;i<t;++i)s[i]=c[i];return s}function yh(c,t){for(;t+1<c.length;t++)c[t]=c[t+1];c.pop()}function Ch(c){for(var t=new Array(c.length),s=0;s<t.length;++s)t[s]=c[s].listener||c[s];return t}function Ah(c,t){return new Promise(function(s,i){function a(r){c.removeListener(t,n),i(r)}function n(){typeof c.removeListener=="function"&&c.removeListener("error",a),s([].slice.call(arguments))}id(c,t,n,{once:!0}),t!=="error"&&Rh(c,a,{once:!0})})}function Rh(c,t,s){typeof c.on=="function"&&id(c,"error",t,s)}function id(c,t,s,i){if(typeof c.on=="function")i.once?c.once(t,s):c.on(t,s);else if(typeof c.addEventListener=="function")c.addEventListener(t,function a(n){i.once&&c.removeEventListener(t,a),s(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof c)}var dt=ku.exports,hu={exports:{}},ma,sc;function Ih(){if(sc)return ma;sc=1;var c=1e3,t=c*60,s=t*60,i=s*24,a=i*7,n=i*365.25;ma=function(g,T){T=T||{};var S=typeof g;if(S==="string"&&g.length>0)return r(g);if(S==="number"&&isFinite(g))return T.long?d(g):h(g);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(g))};function r(g){if(g=String(g),!(g.length>100)){var T=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(g);if(T){var S=parseFloat(T[1]),E=(T[2]||"ms").toLowerCase();switch(E){case"years":case"year":case"yrs":case"yr":case"y":return S*n;case"weeks":case"week":case"w":return S*a;case"days":case"day":case"d":return S*i;case"hours":case"hour":case"hrs":case"hr":case"h":return S*s;case"minutes":case"minute":case"mins":case"min":case"m":return S*t;case"seconds":case"second":case"secs":case"sec":case"s":return S*c;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return S;default:return}}}}function h(g){var T=Math.abs(g);return T>=i?Math.round(g/i)+"d":T>=s?Math.round(g/s)+"h":T>=t?Math.round(g/t)+"m":T>=c?Math.round(g/c)+"s":g+"ms"}function d(g){var T=Math.abs(g);return T>=i?_(g,T,i,"day"):T>=s?_(g,T,s,"hour"):T>=t?_(g,T,t,"minute"):T>=c?_(g,T,c,"second"):g+" ms"}function _(g,T,S,E){var C=T>=S*1.5;return Math.round(g/S)+" "+E+(C?"s":"")}return ma}function bh(c){s.debug=s,s.default=s,s.coerce=d,s.disable=n,s.enable=a,s.enabled=r,s.humanize=Ih(),s.destroy=_,Object.keys(c).forEach(g=>{s[g]=c[g]}),s.names=[],s.skips=[],s.formatters={};function t(g){let T=0;for(let S=0;S<g.length;S++)T=(T<<5)-T+g.charCodeAt(S),T|=0;return s.colors[Math.abs(T)%s.colors.length]}s.selectColor=t;function s(g){let T,S=null,E,C;function A(...R){if(!A.enabled)return;const F=A,I=Number(new Date),ie=I-(T||I);F.diff=ie,F.prev=T,F.curr=I,T=I,R[0]=s.coerce(R[0]),typeof R[0]!="string"&&R.unshift("%O");let N=0;R[0]=R[0].replace(/%([a-zA-Z%])/g,(ve,_e)=>{if(ve==="%%")return"%";N++;const U=s.formatters[_e];if(typeof U=="function"){const x=R[N];ve=U.call(F,x),R.splice(N,1),N--}return ve}),s.formatArgs.call(F,R),(F.log||s.log).apply(F,R)}return A.namespace=g,A.useColors=s.useColors(),A.color=s.selectColor(g),A.extend=i,A.destroy=s.destroy,Object.defineProperty(A,"enabled",{enumerable:!0,configurable:!1,get:()=>S!==null?S:(E!==s.namespaces&&(E=s.namespaces,C=s.enabled(g)),C),set:R=>{S=R}}),typeof s.init=="function"&&s.init(A),A}function i(g,T){const S=s(this.namespace+(typeof T>"u"?":":T)+g);return S.log=this.log,S}function a(g){s.save(g),s.namespaces=g,s.names=[],s.skips=[];let T;const S=(typeof g=="string"?g:"").split(/[\s,]+/),E=S.length;for(T=0;T<E;T++)S[T]&&(g=S[T].replace(/\*/g,".*?"),g[0]==="-"?s.skips.push(new RegExp("^"+g.slice(1)+"$")):s.names.push(new RegExp("^"+g+"$")))}function n(){const g=[...s.names.map(h),...s.skips.map(h).map(T=>"-"+T)].join(",");return s.enable(""),g}function r(g){if(g[g.length-1]==="*")return!0;let T,S;for(T=0,S=s.skips.length;T<S;T++)if(s.skips[T].test(g))return!1;for(T=0,S=s.names.length;T<S;T++)if(s.names[T].test(g))return!0;return!1}function h(g){return g.toString().substring(2,g.toString().length-2).replace(/\.\*\?$/,"*")}function d(g){return g instanceof Error?g.stack||g.message:g}function _(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return s.enable(s.load()),s}var wh=bh;(function(c,t){t.formatArgs=i,t.save=a,t.load=n,t.useColors=s,t.storage=r(),t.destroy=(()=>{let d=!1;return()=>{d||(d=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function s(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function i(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+c.exports.humanize(this.diff),!this.useColors)return;const _="color: "+this.color;d.splice(1,0,_,"color: inherit");let g=0,T=0;d[0].replace(/%[a-zA-Z%]/g,S=>{S!=="%%"&&(g++,S==="%c"&&(T=g))}),d.splice(T,0,_)}t.log=console.debug||console.log||(()=>{});function a(d){try{d?t.storage.setItem("debug",d):t.storage.removeItem("debug")}catch{}}function n(){let d;try{d=t.storage.getItem("debug")}catch{}return!d&&typeof process<"u"&&"env"in process&&(d=process.env.DEBUG),d}function r(){try{return localStorage}catch{}}c.exports=wh(t);const{formatters:h}=c.exports;h.j=function(d){try{return JSON.stringify(d)}catch(_){return"[UnexpectedJSONParseError]: "+_.message}}})(hu,hu.exports);var gr=hu.exports;function Oh(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function nc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function Dh(c,t,s){return t&&nc(c.prototype,t),s&&nc(c,s),c}var lr=gr,or="JsSIP",ht=function(){function c(t){Oh(this,c),t?(this._debug=lr.default("".concat(or,":").concat(t)),this._warn=lr.default("".concat(or,":WARN:").concat(t)),this._error=lr.default("".concat(or,":ERROR:").concat(t))):(this._debug=lr.default(or),this._warn=lr.default("".concat(or,":WARN")),this._error=lr.default("".concat(or,":ERROR"))),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}return Dh(c,[{key:"debug",get:function(){return this._debug}},{key:"warn",get:function(){return this._warn}},{key:"error",get:function(){return this._error}}]),c}(),Mt={},ld={},od={exports:{}},rc=od.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(c){return c.encoding?"rtpmap:%d %s/%s/%s":c.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(c){return c.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(c){return c.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(c){return"extmap:%d"+(c.direction?"/%s":"%v")+(c["encrypt-uri"]?" %s":"%v")+" %s"+(c.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(c){return c.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(c){var t="candidate:%s %d %s %d %s %d typ %s";return t+=c.raddr!=null?" raddr %s rport %d":"%v%v",t+=c.tcptype!=null?" tcptype %s":"%v",c.generation!=null&&(t+=" generation %d"),t+=c["network-id"]!=null?" network-id %d":"%v",t+=c["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(c){var t="ssrc:%d";return c.attribute!=null&&(t+=" %s",c.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(c){return c.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(c){return c.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(c){return"imageattr:%s %s %s"+(c.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(c){return"simulcast:%s %s"+(c.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(c){return"ts-refclk:%s"+(c.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(c){var t="mediaclk:";return t+=c.id!=null?"id=%s %s":"%v%s",t+=c.mediaClockValue!=null?"=%s":"",t+=c.rateNumerator!=null?" rate=%s":"",t+=c.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(rc).forEach(function(c){var t=rc[c];t.forEach(function(s){s.reg||(s.reg=/(.*)/),s.format||(s.format="%s")})});var ad=od.exports;(function(c){var t=function(h){return String(Number(h))===h?Number(h):h},s=function(h,d,_,g){if(g&&!_)d[g]=t(h[1]);else for(var T=0;T<_.length;T+=1)h[T+1]!=null&&(d[_[T]]=t(h[T+1]))},i=function(h,d,_){var g=h.name&&h.names;h.push&&!d[h.push]?d[h.push]=[]:g&&!d[h.name]&&(d[h.name]={});var T=h.push?{}:g?d[h.name]:d;s(_.match(h.reg),T,h.names,h.name),h.push&&d[h.push].push(T)},a=ad,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);c.parse=function(h){var d={},_=[],g=d;return h.split(/(\r\n|\r|\n)/).filter(n).forEach(function(T){var S=T[0],E=T.slice(2);S==="m"&&(_.push({rtp:[],fmtp:[]}),g=_[_.length-1]);for(var C=0;C<(a[S]||[]).length;C+=1){var A=a[S][C];if(A.reg.test(E))return i(A,g,E)}}),d.media=_,d};var r=function(h,d){var _=d.split(/=(.+)/,2);return _.length===2?h[_[0]]=t(_[1]):_.length===1&&d.length>1&&(h[_[0]]=void 0),h};c.parseParams=function(h){return h.split(/;\s?/).reduce(r,{})},c.parseFmtpConfig=c.parseParams,c.parsePayloads=function(h){return h.toString().split(" ").map(Number)},c.parseRemoteCandidates=function(h){for(var d=[],_=h.split(" ").map(t),g=0;g<_.length;g+=3)d.push({component:_[g],ip:_[g+1],port:_[g+2]});return d},c.parseImageAttributes=function(h){return h.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(r,{})})},c.parseSimulcastStreamList=function(h){return h.split(";").map(function(d){return d.split(",").map(function(_){var g,T=!1;return _[0]!=="~"?g=t(_):(g=t(_.substring(1,_.length)),T=!0),{scid:g,paused:T}})})}})(ld);var ga=ad,Nh=/%[sdv%]/g,xh=function(c){var t=1,s=arguments,i=s.length;return c.replace(Nh,function(a){if(t>=i)return a;var n=s[t];switch(t+=1,a){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Di=function(c,t,s){var i=t.format instanceof Function?t.format(t.push?s:s[t.name]):t.format,a=[c+"="+i];if(t.names)for(var n=0;n<t.names.length;n+=1){var r=t.names[n];t.name?a.push(s[t.name][r]):a.push(s[t.names[n]])}else a.push(s[t.name]);return xh.apply(null,a)},Uh=["v","o","s","i","u","e","p","c","b","t","r","z","a"],kh=["i","c","b","a"],Mh=function(c,t){t=t||{},c.version==null&&(c.version=0),c.name==null&&(c.name=" "),c.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var s=t.outerOrder||Uh,i=t.innerOrder||kh,a=[];return s.forEach(function(n){ga[n].forEach(function(r){r.name in c&&c[r.name]!=null?a.push(Di(n,r,c)):r.push in c&&c[r.push]!=null&&c[r.push].forEach(function(h){a.push(Di(n,r,h))})})}),c.media.forEach(function(n){a.push(Di("m",ga.m[0],n)),i.forEach(function(r){ga[r].forEach(function(h){h.name in n&&n[h.name]!=null?a.push(Di(r,h,n)):h.push in n&&n[h.push]!=null&&n[h.push].forEach(function(d){a.push(Di(r,h,d))})})})}),a.join(`\r
|
|
7
7
|
`)+`\r
|
|
8
|
-
`},
|
|
9
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var
|
|
10
|
-
`);for(var
|
|
11
|
-
`)}}catch(E){a.e(E)}finally{a.f()}}var h=
|
|
12
|
-
`)}}catch(E){h.e(E)}finally{h.f()}var g=[];switch(this.method){case
|
|
13
|
-
`),
|
|
14
|
-
`),
|
|
15
|
-
`),this.body){var S=
|
|
8
|
+
`},bn=ld,Ph=Mh;Mt.write=Ph;Mt.parse=bn.parse;Mt.parseParams=bn.parseParams;Mt.parseFmtpConfig=bn.parseFmtpConfig;Mt.parsePayloads=bn.parsePayloads;Mt.parseRemoteCandidates=bn.parseRemoteCandidates;Mt.parseImageAttributes=bn.parseImageAttributes;Mt.parseSimulcastStreamList=bn.parseSimulcastStreamList;function Eo(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Eo=function(s){return typeof s}:Eo=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},Eo(c)}function Mu(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&_u(c,t)}function _u(c,t){return _u=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},_u(c,t)}function Pu(c){var t=Hh();return function(){var i=xo(c),a;if(t){var n=xo(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return Lh(this,a)}}function Lh(c,t){return t&&(Eo(t)==="object"||typeof t=="function")?t:$h(c)}function $h(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Hh(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function xo(c){return xo=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},xo(c)}function Gt(c,t){var s;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(s=Fh(c))||t&&c&&typeof c.length=="number"){s&&(c=s);var i=0,a=function(){};return{s:a,n:function(){return i>=c.length?{done:!0}:{done:!1,value:c[i++]}},e:function(_){throw _},f:a}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
9
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var n=!0,r=!1,h;return{s:function(){s=c[Symbol.iterator]()},n:function(){var _=s.next();return n=_.done,_},e:function(_){r=!0,h=_},f:function(){try{!n&&s.return!=null&&s.return()}finally{if(r)throw h}}}}function Fh(c,t){if(c){if(typeof c=="string")return ic(c,t);var s=Object.prototype.toString.call(c).slice(8,-1);if(s==="Object"&&c.constructor&&(s=c.constructor.name),s==="Map"||s==="Set")return Array.from(c);if(s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s))return ic(c,t)}}function ic(c,t){(t==null||t>c.length)&&(t=c.length);for(var s=0,i=new Array(t);s<t;s++)i[s]=c[s];return i}function il(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function lc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function Ko(c,t,s){return t&&lc(c.prototype,t),s&&lc(c,s),c}var ud=Mt,Vh=ht,Et=ot,it=wt(),oc=Uu(),jh=us(),Ta=new Vh("SIPMessage"),cd=function(){function c(t,s,i,a,n,r){if(il(this,c),!t||!s||!i)return null;a=a||{},this.ua=i,this.headers={},this.method=t,this.ruri=s,this.body=r,this.extraHeaders=it.cloneArray(n),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),a.route_set?this.setHeader("route",a.route_set):i.configuration.use_preloaded_route&&this.setHeader("route","<".concat(i.transport.sip_uri,";lr>")),this.setHeader("via",""),this.setHeader("max-forwards",Et.MAX_FORWARDS);var h=a.to_uri||s,d=a.to_tag?{tag:a.to_tag}:null,_=typeof a.to_display_name<"u"?a.to_display_name:null;this.to=new oc(h,_,d),this.setHeader("to",this.to.toString());var g=a.from_uri||i.configuration.uri,T={tag:a.from_tag||it.newTag()},S;typeof a.from_display_name<"u"?S=a.from_display_name:i.configuration.display_name?S=i.configuration.display_name:S=null,this.from=new oc(g,S,T),this.setHeader("from",this.from.toString());var E=a.call_id||i.configuration.jssip_id+it.createRandomToken(15);this.call_id=E,this.setHeader("call-id",E);var C=a.cseq||Math.floor(Math.random()*1e4);this.cseq=C,this.setHeader("cseq","".concat(C," ").concat(t))}return Ko(c,[{key:"setHeader",value:function(s,i){for(var a=new RegExp("^\\s*".concat(s,"\\s*:"),"i"),n=0;n<this.extraHeaders.length;n++)a.test(this.extraHeaders[n])&&this.extraHeaders.splice(n,1);this.headers[it.headerize(s)]=Array.isArray(i)?i:[i]}},{key:"getHeader",value:function(s){var i=this.headers[it.headerize(s)];if(i){if(i[0])return i[0]}else{var a=new RegExp("^\\s*".concat(s,"\\s*:"),"i"),n=Gt(this.extraHeaders),r;try{for(n.s();!(r=n.n()).done;){var h=r.value;if(a.test(h))return h.substring(h.indexOf(":")+1).trim()}}catch(d){n.e(d)}finally{n.f()}}}},{key:"getHeaders",value:function(s){var i=this.headers[it.headerize(s)],a=[];if(i){var n=Gt(i),r;try{for(n.s();!(r=n.n()).done;){var h=r.value;a.push(h)}}catch(S){n.e(S)}finally{n.f()}return a}else{var d=new RegExp("^\\s*".concat(s,"\\s*:"),"i"),_=Gt(this.extraHeaders),g;try{for(_.s();!(g=_.n()).done;){var T=g.value;d.test(T)&&a.push(T.substring(T.indexOf(":")+1).trim())}}catch(S){_.e(S)}finally{_.f()}return a}}},{key:"hasHeader",value:function(s){if(this.headers[it.headerize(s)])return!0;var i=new RegExp("^\\s*".concat(s,"\\s*:"),"i"),a=Gt(this.extraHeaders),n;try{for(a.s();!(n=a.n()).done;){var r=n.value;if(i.test(r))return!0}}catch(h){a.e(h)}finally{a.f()}return!1}},{key:"parseSDP",value:function(s){return!s&&this.sdp?this.sdp:(this.sdp=ud.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){var s="".concat(this.method," ").concat(this.ruri,` SIP/2.0\r
|
|
10
|
+
`);for(var i in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,i)){var a=Gt(this.headers[i]),n;try{for(a.s();!(n=a.n()).done;){var r=n.value;s+="".concat(i,": ").concat(r,`\r
|
|
11
|
+
`)}}catch(E){a.e(E)}finally{a.f()}}var h=Gt(this.extraHeaders),d;try{for(h.s();!(d=h.n()).done;){var _=d.value;s+="".concat(_.trim(),`\r
|
|
12
|
+
`)}}catch(E){h.e(E)}finally{h.f()}var g=[];switch(this.method){case Et.REGISTER:g.push("path","gruu");break;case Et.INVITE:this.ua.configuration.session_timers&&g.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&g.push("gruu"),g.push("ice","replaces");break;case Et.UPDATE:this.ua.configuration.session_timers&&g.push("timer"),g.push("ice");break}g.push("outbound");var T=this.ua.configuration.user_agent||Et.USER_AGENT;if(s+="Allow: ".concat(Et.ALLOWED_METHODS,`\r
|
|
13
|
+
`),s+="Supported: ".concat(g,`\r
|
|
14
|
+
`),s+="User-Agent: ".concat(T,`\r
|
|
15
|
+
`),this.body){var S=it.str_utf8_length(this.body);s+="Content-Length: ".concat(S,`\r
|
|
16
16
|
\r
|
|
17
|
-
`),
|
|
17
|
+
`),s+=this.body}else s+=`Content-Length: 0\r
|
|
18
18
|
\r
|
|
19
|
-
`;return
|
|
20
|
-
`);if(this.method===
|
|
21
|
-
`)}}catch(
|
|
22
|
-
`)}}catch(
|
|
19
|
+
`;return s}},{key:"clone",value:function(){var s=new c(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(i){s.headers[i]=this.headers[i].slice()},this),s.body=this.body,s.extraHeaders=it.cloneArray(this.extraHeaders),s.to=this.to,s.from=this.from,s.call_id=this.call_id,s.cseq=this.cseq,s}}]),c}(),qh=function(c){Mu(s,c);var t=Pu(s);function s(i,a,n,r,h){var d;return il(this,s),d=t.call(this,Et.INVITE,i,a,n,r,h),d.transaction=null,d}return Ko(s,[{key:"cancel",value:function(a){this.transaction.cancel(a)}},{key:"clone",value:function(){var a=new s(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(n){a.headers[n]=this.headers[n].slice()},this),a.body=this.body,a.extraHeaders=it.cloneArray(this.extraHeaders),a.to=this.to,a.from=this.from,a.call_id=this.call_id,a.cseq=this.cseq,a.transaction=this.transaction,a}}]),s}(cd),fd=function(){function c(){il(this,c),this.data=null,this.headers=null,this.method=null,this.via=null,this.via_branch=null,this.call_id=null,this.cseq=null,this.from=null,this.from_tag=null,this.to=null,this.to_tag=null,this.body=null,this.sdp=null}return Ko(c,[{key:"addHeader",value:function(s,i){var a={raw:i};s=it.headerize(s),this.headers[s]?this.headers[s].push(a):this.headers[s]=[a]}},{key:"getHeader",value:function(s){var i=this.headers[it.headerize(s)];if(i){if(i[0])return i[0].raw}else return}},{key:"getHeaders",value:function(s){var i=this.headers[it.headerize(s)],a=[];if(!i)return[];var n=Gt(i),r;try{for(n.s();!(r=n.n()).done;){var h=r.value;a.push(h.raw)}}catch(d){n.e(d)}finally{n.f()}return a}},{key:"hasHeader",value:function(s){return!!this.headers[it.headerize(s)]}},{key:"parseHeader",value:function(s){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(s=it.headerize(s),this.headers[s]){if(i>=this.headers[s].length){Ta.debug('not so many "'.concat(s,'" headers present'));return}}else{Ta.debug('header "'.concat(s,'" not present'));return}var a=this.headers[s][i],n=a.raw;if(a.parsed)return a.parsed;var r=jh.parse(n,s.replace(/-/g,"_"));if(r===-1){this.headers[s].splice(i,1),Ta.debug('error parsing "'.concat(s,'" header field with value "').concat(n,'"'));return}else return a.parsed=r,r}},{key:"s",value:function(s,i){return this.parseHeader(s,i)}},{key:"setHeader",value:function(s,i){var a={raw:i};this.headers[it.headerize(s)]=[a]}},{key:"parseSDP",value:function(s){return!s&&this.sdp?this.sdp:(this.sdp=ud.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){return this.data}}]),c}(),Bh=function(c){Mu(s,c);var t=Pu(s);function s(i){var a;return il(this,s),a=t.call(this),a.ua=i,a.headers={},a.ruri=null,a.transport=null,a.server_transaction=null,a}return Ko(s,[{key:"reply",value:function(a,n,r,h,d,_){var g=[],T=this.getHeader("To");if(a=a||null,n=n||null,!a||a<100||a>699)throw new TypeError("Invalid status_code: ".concat(a));if(n&&typeof n!="string"&&!(n instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(n));n=n||Et.REASON_PHRASE[a]||"",r=it.cloneArray(r),this.ua.configuration.extra_headers&&(r=r.concat(this.ua.configuration.extra_headers));var S="SIP/2.0 ".concat(a," ").concat(n,`\r
|
|
20
|
+
`);if(this.method===Et.INVITE&&a>100&&a<=200){var E=this.getHeaders("record-route"),C=Gt(E),A;try{for(C.s();!(A=C.n()).done;){var R=A.value;S+="Record-Route: ".concat(R,`\r
|
|
21
|
+
`)}}catch(x){C.e(x)}finally{C.f()}}var F=this.getHeaders("via"),I=Gt(F),ie;try{for(I.s();!(ie=I.n()).done;){var N=ie.value;S+="Via: ".concat(N,`\r
|
|
22
|
+
`)}}catch(x){I.e(x)}finally{I.f()}!this.to_tag&&a>100?T+=";tag=".concat(it.newTag()):this.to_tag&&!this.s("to").hasParam("tag")&&(T+=";tag=".concat(this.to_tag)),S+="To: ".concat(T,`\r
|
|
23
23
|
`),S+="From: ".concat(this.getHeader("From"),`\r
|
|
24
24
|
`),S+="Call-ID: ".concat(this.call_id,`\r
|
|
25
25
|
`),S+="CSeq: ".concat(this.cseq," ").concat(this.method,`\r
|
|
26
|
-
`);var
|
|
27
|
-
`)}}catch(
|
|
28
|
-
`),S+="Accept: ".concat(
|
|
29
|
-
`)):a===405?S+="Allow: ".concat(
|
|
30
|
-
`):a===415&&(S+="Accept: ".concat(
|
|
26
|
+
`);var $=Gt(r),ve;try{for($.s();!(ve=$.n()).done;){var _e=ve.value;S+="".concat(_e.trim(),`\r
|
|
27
|
+
`)}}catch(x){$.e(x)}finally{$.f()}switch(this.method){case Et.INVITE:this.ua.configuration.session_timers&&g.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&g.push("gruu"),g.push("ice","replaces");break;case Et.UPDATE:this.ua.configuration.session_timers&&g.push("timer"),h&&g.push("ice"),g.push("replaces")}if(g.push("outbound"),this.method===Et.OPTIONS?(S+="Allow: ".concat(Et.ALLOWED_METHODS,`\r
|
|
28
|
+
`),S+="Accept: ".concat(Et.ACCEPTED_BODY_TYPES,`\r
|
|
29
|
+
`)):a===405?S+="Allow: ".concat(Et.ALLOWED_METHODS,`\r
|
|
30
|
+
`):a===415&&(S+="Accept: ".concat(Et.ACCEPTED_BODY_TYPES,`\r
|
|
31
31
|
`)),S+="Supported: ".concat(g,`\r
|
|
32
|
-
`),h){var
|
|
33
|
-
`,S+="Content-Length: ".concat(
|
|
32
|
+
`),h){var U=it.str_utf8_length(h);S+=`Content-Type: application/sdp\r
|
|
33
|
+
`,S+="Content-Length: ".concat(U,`\r
|
|
34
34
|
\r
|
|
35
35
|
`),S+=h}else S+="Content-Length: ".concat(0,`\r
|
|
36
36
|
\r
|
|
37
|
-
`);this.server_transaction.receiveResponse(a,S,d,_)}},{key:"reply_sl",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,
|
|
38
|
-
`),d=
|
|
39
|
-
`)}}catch(A){d.e(A)}finally{d.f()}var T=this.getHeader("To");if(!this.to_tag&&a>100?T+=";tag=".concat(
|
|
37
|
+
`);this.server_transaction.receiveResponse(a,S,d,_)}},{key:"reply_sl",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,r=this.getHeaders("via");if(!a||a<100||a>699)throw new TypeError("Invalid status_code: ".concat(a));if(n&&typeof n!="string"&&!(n instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(n));n=n||Et.REASON_PHRASE[a]||"";var h="SIP/2.0 ".concat(a," ").concat(n,`\r
|
|
38
|
+
`),d=Gt(r),_;try{for(d.s();!(_=d.n()).done;){var g=_.value;h+="Via: ".concat(g,`\r
|
|
39
|
+
`)}}catch(A){d.e(A)}finally{d.f()}var T=this.getHeader("To");if(!this.to_tag&&a>100?T+=";tag=".concat(it.newTag()):this.to_tag&&!this.s("to").hasParam("tag")&&(T+=";tag=".concat(this.to_tag)),h+="To: ".concat(T,`\r
|
|
40
40
|
`),h+="From: ".concat(this.getHeader("From"),`\r
|
|
41
41
|
`),h+="Call-ID: ".concat(this.call_id,`\r
|
|
42
42
|
`),h+="CSeq: ".concat(this.cseq," ").concat(this.method,`\r
|
|
43
|
-
`),this.ua.configuration.extra_headers){var S=
|
|
43
|
+
`),this.ua.configuration.extra_headers){var S=Gt(this.ua.configuration.extra_headers),E;try{for(S.s();!(E=S.n()).done;){var C=E.value;h+="".concat(C.trim(),`\r
|
|
44
44
|
`)}}catch(A){S.e(A)}finally{S.f()}}h+="Content-Length: ".concat(0,`\r
|
|
45
45
|
\r
|
|
46
|
-
`),this.transport.send(h)}}]),n}(id),$h=function(c){Uu(n,c);var t=ku(n);function n(){var l;return rl(this,n),l=t.call(this),l.headers={},l.status_code=null,l.reason_phrase=null,l}return n}(id),Es={OutgoingRequest:rd,InitialOutgoingInviteRequest:Mh,IncomingRequest:Lh,IncomingResponse:$h};function Hh(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function lc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function Fh(c,t,n){return t&&lc(c.prototype,t),n&&lc(c,n),c}var Vh=dt,ds=bt(),Yt=new Vh("DigestAuthentication"),jh=function(){function c(t){Hh(this,c),this._credentials=t,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}return Fh(c,[{key:"get",value:function(n){switch(n){case"realm":return this._realm;case"ha1":return this._ha1;default:Yt.warn('get() | cannot get "%s" parameter',n);return}}},{key:"authenticate",value:function(n,l){var a=n.method,s=n.ruri,r=n.body,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this._algorithm=l.algorithm,this._realm=l.realm,this._nonce=l.nonce,this._opaque=l.opaque,this._stale=l.stale,this._algorithm){if(this._algorithm!=="MD5")return Yt.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return Yt.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return Yt.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return Yt.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return Yt.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(l.qop)if(l.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(l.qop.indexOf("auth")>-1)this._qop="auth";else return Yt.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=a,this._uri=s,this._cnonce=h||ds.createRandomToken(12),this._nc+=1;var d=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-d.length)+d,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=ds.calculateMD5("".concat(this._credentials.username,":").concat(this._realm,":").concat(this._credentials.password)):this._ha1=this._credentials.ha1;var _,g;return this._qop==="auth"?(_="".concat(this._method,":").concat(this._uri),g=ds.calculateMD5(_),Yt.debug('authenticate() | using qop=auth [a2:"%s"]',_),this._response=ds.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth:").concat(g))):this._qop==="auth-int"?(_="".concat(this._method,":").concat(this._uri,":").concat(ds.calculateMD5(r||"")),g=ds.calculateMD5(_),Yt.debug('authenticate() | using qop=auth-int [a2:"%s"]',_),this._response=ds.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth-int:").concat(g))):this._qop===null&&(_="".concat(this._method,":").concat(this._uri),g=ds.calculateMD5(_),Yt.debug('authenticate() | using qop=null [a2:"%s"]',_),this._response=ds.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(g))),Yt.debug("authenticate() | response generated"),!0}},{key:"toString",value:function(){var n=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return n.push("algorithm=".concat(this._algorithm)),n.push('username="'.concat(this._credentials.username,'"')),n.push('realm="'.concat(this._realm,'"')),n.push('nonce="'.concat(this._nonce,'"')),n.push('uri="'.concat(this._uri,'"')),n.push('response="'.concat(this._response,'"')),this._opaque&&n.push('opaque="'.concat(this._opaque,'"')),this._qop&&(n.push("qop=".concat(this._qop)),n.push('cnonce="'.concat(this._cnonce,'"')),n.push("nc=".concat(this._ncHex))),"Digest ".concat(n.join(", "))}}]),c}(),hs=500,qh=4e3,oc=5e3,ld={T1:hs,T2:qh,T4:oc,TIMER_B:64*hs,TIMER_D:0*hs,TIMER_F:64*hs,TIMER_H:64*hs,TIMER_I:0*hs,TIMER_J:0*hs,TIMER_K:0*oc,TIMER_L:64*hs,TIMER_M:64*hs,PROVISIONAL_RESPONSE_INTERVAL:6e4};function So(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?So=function(n){return typeof n}:So=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},So(c)}function il(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function ac(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function ll(c,t,n){return t&&ac(c.prototype,t),n&&ac(c,n),c}function ol(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&hu(c,t)}function hu(c,t){return hu=Object.setPrototypeOf||function(l,a){return l.__proto__=a,l},hu(c,t)}function al(c){var t=Gh();return function(){var l=No(c),a;if(t){var s=No(this).constructor;a=Reflect.construct(l,arguments,s)}else a=l.apply(this,arguments);return Bh(this,a)}}function Bh(c,t){return t&&(So(t)==="object"||typeof t=="function")?t:Bs(c)}function Bs(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Gh(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function No(c){return No=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},No(c)}var ul=ft.EventEmitter,cl=dt,Ji=lt,uc=Es,ls=ld,cc=new cl("NonInviteClientTransaction"),$l=new cl("InviteClientTransaction"),Wh=new cl("AckClientTransaction"),fc=new cl("NonInviteServerTransaction"),Hl=new cl("InviteServerTransaction"),de={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"},Kh=function(c){ol(n,c);var t=al(n);function n(l,a,s,r){var h;il(this,n),h=t.call(this),h.type=de.NON_INVITE_CLIENT,h.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),h.ua=l,h.transport=a,h.request=s,h.eventHandlers=r;var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(l.configuration.via_host,";branch=").concat(h.id),h.request.setHeader("via",d),h.ua.newTransaction(Bs(h)),h}return ll(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(de.STATUS_TRYING),this.F=setTimeout(function(){a.timer_F()},ls.TIMER_F),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){cc.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}},{key:"timer_F",value:function(){cc.debug("Timer F expired for transaction ".concat(this.id)),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}},{key:"timer_K",value:function(){this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"receiveResponse",value:function(a){var s=this,r=a.status_code;if(r<200)switch(this.state){case de.STATUS_TRYING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break}else switch(this.state){case de.STATUS_TRYING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_COMPLETED),clearTimeout(this.F),r===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(a),this.K=setTimeout(function(){s.timer_K()},ls.TIMER_K);break;case de.STATUS_COMPLETED:break}}},{key:"C",get:function(){return de}}]),n}(ul),Yh=function(c){ol(n,c);var t=al(n);function n(l,a,s,r){var h;il(this,n),h=t.call(this),h.type=de.INVITE_CLIENT,h.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),h.ua=l,h.transport=a,h.request=s,h.eventHandlers=r,s.transaction=Bs(h);var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(l.configuration.via_host,";branch=").concat(h.id),h.request.setHeader("via",d),h.ua.newTransaction(Bs(h)),h}return ll(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(de.STATUS_CALLING),this.B=setTimeout(function(){a.timer_B()},ls.TIMER_B),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==de.STATUS_ACCEPTED&&($l.debug("transport error occurred, deleting transaction ".concat(this.id)),this.eventHandlers.onTransportError()),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_M",value:function(){$l.debug("Timer M expired for transaction ".concat(this.id)),this.state===de.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"timer_B",value:function(){$l.debug("Timer B expired for transaction ".concat(this.id)),this.state===de.STATUS_CALLING&&(this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}},{key:"timer_D",value:function(){$l.debug("Timer D expired for transaction ".concat(this.id)),clearTimeout(this.B),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"sendACK",value:function(a){var s=this,r=new uc.OutgoingRequest(Ji.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});r.setHeader("from",this.request.getHeader("from")),r.setHeader("via",this.request.getHeader("via")),r.setHeader("to",a.getHeader("to")),this.D=setTimeout(function(){s.timer_D()},ls.TIMER_D),this.transport.send(r)}},{key:"cancel",value:function(a){if(this.state===de.STATUS_PROCEEDING){var s=new uc.OutgoingRequest(Ji.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});s.setHeader("from",this.request.getHeader("from")),s.setHeader("via",this.request.getHeader("via")),s.setHeader("to",this.request.getHeader("to")),a&&s.setHeader("reason",a),this.transport.send(s)}}},{key:"receiveResponse",value:function(a){var s=this,r=a.status_code;if(r>=100&&r<=199)switch(this.state){case de.STATUS_CALLING:this.stateChanged(de.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break;case de.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(a);break}else if(r>=200&&r<=299)switch(this.state){case de.STATUS_CALLING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_ACCEPTED),this.M=setTimeout(function(){s.timer_M()},ls.TIMER_M),this.eventHandlers.onReceiveResponse(a);break;case de.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(a);break}else if(r>=300&&r<=699)switch(this.state){case de.STATUS_CALLING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_COMPLETED),this.sendACK(a),this.eventHandlers.onReceiveResponse(a);break;case de.STATUS_COMPLETED:this.sendACK(a);break}}},{key:"C",get:function(){return de}}]),n}(ul),Jh=function(c){ol(n,c);var t=al(n);function n(l,a,s,r){var h;il(this,n),h=t.call(this),h.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),h.transport=a,h.request=s,h.eventHandlers=r;var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(l.configuration.via_host,";branch=").concat(h.id),h.request.setHeader("via",d),h}return ll(n,[{key:"send",value:function(){this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){Wh.debug("transport error occurred for transaction ".concat(this.id)),this.eventHandlers.onTransportError()}},{key:"C",get:function(){return de}}]),n}(ul),zh=function(c){ol(n,c);var t=al(n);function n(l,a,s){var r;return il(this,n),r=t.call(this),r.type=de.NON_INVITE_SERVER,r.id=s.via_branch,r.ua=l,r.transport=a,r.request=s,r.last_response="",s.server_transaction=Bs(r),r.state=de.STATUS_TRYING,l.newTransaction(Bs(r)),r}return ll(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_J",value:function(){fc.debug("Timer J expired for transaction ".concat(this.id)),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,fc.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.J),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"receiveResponse",value:function(a,s,r,h){var d=this;if(a===100)switch(this.state){case de.STATUS_TRYING:this.stateChanged(de.STATUS_PROCEEDING),this.transport.send(s)||this.onTransportError();break;case de.STATUS_PROCEEDING:this.last_response=s,this.transport.send(s)?r&&r():(this.onTransportError(),h&&h());break}else if(a>=200&&a<=699)switch(this.state){case de.STATUS_TRYING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_COMPLETED),this.last_response=s,this.J=setTimeout(function(){d.timer_J()},ls.TIMER_J),this.transport.send(s)?r&&r():(this.onTransportError(),h&&h());break;case de.STATUS_COMPLETED:break}}},{key:"C",get:function(){return de}}]),n}(ul),Xh=function(c){ol(n,c);var t=al(n);function n(l,a,s){var r;return il(this,n),r=t.call(this),r.type=de.INVITE_SERVER,r.id=s.via_branch,r.ua=l,r.transport=a,r.request=s,r.last_response="",s.server_transaction=Bs(r),r.state=de.STATUS_PROCEEDING,l.newTransaction(Bs(r)),r.resendProvisionalTimer=null,s.reply(100),r}return ll(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_H",value:function(){Hl.debug("Timer H expired for transaction ".concat(this.id)),this.state===de.STATUS_COMPLETED&&Hl.debug("ACK not received, dialog will be terminated"),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_I",value:function(){this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_L",value:function(){Hl.debug("Timer L expired for transaction ".concat(this.id)),this.state===de.STATUS_ACCEPTED&&(this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,Hl.debug("transport error occurred, deleting transaction ".concat(this.id)),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"resend_provisional",value:function(){this.transport.send(this.last_response)||this.onTransportError()}},{key:"receiveResponse",value:function(a,s,r,h){var d=this;if(a>=100&&a<=199)switch(this.state){case de.STATUS_PROCEEDING:this.transport.send(s)||this.onTransportError(),this.last_response=s;break}if(a>100&&a<=199&&this.state===de.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(function(){d.resend_provisional()},ls.PROVISIONAL_RESPONSE_INTERVAL));else if(a>=200&&a<=299)switch(this.state){case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_ACCEPTED),this.last_response=s,this.L=setTimeout(function(){d.timer_L()},ls.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case de.STATUS_ACCEPTED:this.transport.send(s)?r&&r():(this.onTransportError(),h&&h());break}else if(a>=300&&a<=699)switch(this.state){case de.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(s)?(this.stateChanged(de.STATUS_COMPLETED),this.H=setTimeout(function(){d.timer_H()},ls.TIMER_H),r&&r()):(this.onTransportError(),h&&h());break}}},{key:"C",get:function(){return de}}]),n}(ul);function Qh(c,t){var n=c._transactions,l;switch(t.method){case Ji.INVITE:if(l=n.ist[t.via_branch],l){switch(l.state){case de.STATUS_PROCEEDING:l.transport.send(l.last_response);break;case de.STATUS_ACCEPTED:break}return!0}break;case Ji.ACK:if(l=n.ist[t.via_branch],l){if(l.state===de.STATUS_ACCEPTED)return!1;if(l.state===de.STATUS_COMPLETED)return l.state=de.STATUS_CONFIRMED,l.I=setTimeout(function(){l.timer_I()},ls.TIMER_I),!0}else return!1;break;case Ji.CANCEL:return l=n.ist[t.via_branch],l?(t.reply_sl(200),l.state!==de.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(l=n.nist[t.via_branch],l){switch(l.state){case de.STATUS_TRYING:break;case de.STATUS_PROCEEDING:case de.STATUS_COMPLETED:l.transport.send(l.last_response);break}return!0}break}}var fl={C:de,NonInviteClientTransaction:Kh,InviteClientTransaction:Yh,AckClientTransaction:Jh,NonInviteServerTransaction:zh,InviteServerTransaction:Xh,checkTransaction:Qh};function Zh(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function dc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function e_(c,t,n){return t&&dc(c.prototype,t),n&&dc(c,n),c}var t_=dt,hc=lt,s_=jh,ga=fl,n_=new t_("RequestSender"),Ta={onRequestTimeout:function(){},onTransportError:function(){},onReceiveResponse:function(){},onAuthenticated:function(){}},dl=function(){function c(t,n,l){Zh(this,c),this._ua=t,this._eventHandlers=l,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(var a in Ta)Object.prototype.hasOwnProperty.call(Ta,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Ta[a]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==hc.BYE||this._method!==hc.ACK)&&this._eventHandlers.onTransportError()}return e_(c,[{key:"send",value:function(){var n=this,l={onRequestTimeout:function(){n._eventHandlers.onRequestTimeout()},onTransportError:function(){n._eventHandlers.onTransportError()},onReceiveResponse:function(s){n._receiveResponse(s)}};switch(this._method){case"INVITE":this.clientTransaction=new ga.InviteClientTransaction(this._ua,this._ua.transport,this._request,l);break;case"ACK":this.clientTransaction=new ga.AckClientTransaction(this._ua,this._ua.transport,this._request,l);break;default:this.clientTransaction=new ga.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,l)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}},{key:"_receiveResponse",value:function(n){var l,a,s=n.status_code;if((s===401||s===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(n.status_code===401?(l=n.parseHeader("www-authenticate"),a="authorization"):(l=n.parseHeader("proxy-authenticate"),a="proxy-authorization"),!l){n_.debug("".concat(n.status_code," with wrong or missing challenge, cannot authenticate")),this._eventHandlers.onReceiveResponse(n);return}if(!this._challenged||!this._staled&&l.stale===!0){if(this._auth||(this._auth=new s_({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,l)){this._eventHandlers.onReceiveResponse(n);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),l.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq","".concat(this._request.cseq," ").concat(this._method)),this._request.setHeader(a,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(n)}else this._eventHandlers.onReceiveResponse(n)}}]),c}();function r_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function _c(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function i_(c,t,n){return t&&_c(c.prototype,t),n&&_c(c,n),c}var l_=dt,va=bt(),pn=lt,pc=Es,mc=dl,Di=new l_("Registrator"),Fl=10,o_=function(){function c(t,n){r_(this,c),this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=va.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance='"<urn:uuid:'.concat(this._ua.configuration.instance_id,'>"'),this._contact+=";reg-id=".concat(this._reg_id),this._contact+=";+sip.instance=".concat(this._sipInstance)}return i_(c,[{key:"setExtraHeaders",value:function(n){Array.isArray(n)||(n=[]),this._extraHeaders=n.slice()}},{key:"setExtraContactParams",value:function(n){n instanceof Object||(n={}),this._extraContactParams="";for(var l in n)if(Object.prototype.hasOwnProperty.call(n,l)){var a=n[l];this._extraContactParams+=";".concat(l),a&&(this._extraContactParams+="=".concat(a))}}},{key:"register",value:function(){var n=this;if(this._registering){Di.debug("Register request in progress...");return}var l=this._extraHeaders.slice();l.push("Contact: ".concat(this._contact,";expires=").concat(this._expires).concat(this._extraContactParams)),l.push("Expires: ".concat(this._expires));var a=new pc.OutgoingRequest(pn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},l),s=new mc(this._ua,a,{onRequestTimeout:function(){n._registrationFailure(null,pn.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._registrationFailure(null,pn.causes.CONNECTION_ERROR)},onAuthenticated:function(){n._cseq+=1},onReceiveResponse:function(h){if(h.cseq===n._cseq)switch(n._registrationTimer!==null&&(clearTimeout(n._registrationTimer),n._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(h.status_code):break;case/^2[0-9]{2}$/.test(h.status_code):{if(n._registering=!1,!h.hasHeader("Contact")){Di.debug("no Contact header in response to REGISTER, response ignored");break}var d=h.headers.Contact.reduce(function(E,C){return E.concat(C.parsed)},[]),_=d.find(function(E){return n._sipInstance===E.getParam("+sip.instance")&&n._reg_id===parseInt(E.getParam("reg-id"))});if(_||(_=d.find(function(E){return E.uri.user===n._ua.contact.uri.user})),!_){Di.debug("no Contact header pointing to us, response ignored");break}var g=_.getParam("expires");!g&&h.hasHeader("expires")&&(g=h.getHeader("expires")),g||(g=n._expires),g=Number(g),g<Fl&&(g=Fl);var T=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):g*1e3-5e3;n._registrationTimer=setTimeout(function(){n._registrationTimer=null,n._ua.listeners("registrationExpiring").length===0?n.register():n._ua.emit("registrationExpiring")},T),_.hasParam("temp-gruu")&&(n._ua.contact.temp_gruu=_.getParam("temp-gruu").replace(/"/g,"")),_.hasParam("pub-gruu")&&(n._ua.contact.pub_gruu=_.getParam("pub-gruu").replace(/"/g,"")),n._registered||(n._registered=!0,n._ua.registered({response:h}));break}case/^423$/.test(h.status_code):{h.hasHeader("min-expires")?(n._expires=Number(h.getHeader("min-expires")),n._expires<Fl&&(n._expires=Fl),n.register()):(Di.debug("423 response received for REGISTER without Min-Expires"),n._registrationFailure(h,pn.causes.SIP_FAILURE_CODE));break}default:{var S=va.sipErrorCause(h.status_code);n._registrationFailure(h,S)}}}});this._registering=!0,s.send()}},{key:"unregister",value:function(){var n=this,l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._registered){Di.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);var a=this._extraHeaders.slice();l.all?a.push("Contact: *".concat(this._extraContactParams)):a.push("Contact: ".concat(this._contact,";expires=0").concat(this._extraContactParams)),a.push("Expires: 0");var s=new pc.OutgoingRequest(pn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},a),r=new mc(this._ua,s,{onRequestTimeout:function(){n._unregistered(null,pn.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._unregistered(null,pn.causes.CONNECTION_ERROR)},onAuthenticated:function(){n._cseq+=1},onReceiveResponse:function(d){switch(!0){case/^1[0-9]{2}$/.test(d.status_code):break;case/^2[0-9]{2}$/.test(d.status_code):n._unregistered(d);break;default:{var _=va.sipErrorCause(d.status_code);n._unregistered(d,_)}}}});r.send()}},{key:"close",value:function(){this._registered&&this.unregister()}},{key:"onTransportClosed",value:function(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}},{key:"_registrationFailure",value:function(n,l){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:l}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:l}))}},{key:"_unregistered",value:function(n,l){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:l||null})}},{key:"registered",get:function(){return this._registered}}]),c}();function a_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function gc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function u_(c,t,n){return t&&gc(c.prototype,t),n&&gc(c,n),c}var Sa=lt,Vl=fl,c_=dl,Ea={onRequestTimeout:function(){},onTransportError:function(){},onSuccessResponse:function(){},onErrorResponse:function(){},onAuthenticated:function(){},onDialogError:function(){}},f_=function(){function c(t,n,l){a_(this,c),this._dialog=t,this._ua=t._ua,this._request=n,this._eventHandlers=l,this._reattempt=!1,this._reattemptTimer=null;for(var a in Ea)Object.prototype.hasOwnProperty.call(Ea,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Ea[a]))}return u_(c,[{key:"send",value:function(){var n=this,l=new c_(this._ua,this._request,{onRequestTimeout:function(){n._eventHandlers.onRequestTimeout()},onTransportError:function(){n._eventHandlers.onTransportError()},onAuthenticated:function(r){n._eventHandlers.onAuthenticated(r)},onReceiveResponse:function(r){n._receiveResponse(r)}});if(l.send(),(this._request.method===Sa.INVITE||this._request.method===Sa.UPDATE&&this._request.body)&&l.clientTransaction.state!==Vl.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;var a=function s(){(l.clientTransaction.state===Vl.C.STATUS_ACCEPTED||l.clientTransaction.state===Vl.C.STATUS_COMPLETED||l.clientTransaction.state===Vl.C.STATUS_TERMINATED)&&(l.clientTransaction.removeListener("stateChanged",s),n._dialog.uac_pending_reply=!1)};l.clientTransaction.on("stateChanged",a)}}},{key:"_receiveResponse",value:function(n){var l=this;n.status_code===408||n.status_code===481?this._eventHandlers.onDialogError(n):n.method===Sa.INVITE&&n.status_code===491?this._reattempt?n.status_code>=200&&n.status_code<300?this._eventHandlers.onSuccessResponse(n):n.status_code>=300&&this._eventHandlers.onErrorResponse(n):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(function(){l._dialog.isTerminated()||(l._reattempt=!0,l.send())},1e3)):n.status_code>=200&&n.status_code<300?this._eventHandlers.onSuccessResponse(n):n.status_code>=300&&this._eventHandlers.onErrorResponse(n)}},{key:"request",get:function(){return this._request}}]),c}();function d_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Tc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function vc(c,t,n){return t&&Tc(c.prototype,t),n&&Tc(c,n),c}var h_=dt,Sc=Es,Ms=lt,Ni=fl,__=f_,ya=bt(),Ca=new h_("Dialog"),Ls={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3},p_=function(){vc(c,null,[{key:"C",get:function(){return Ls}}]);function c(t,n,l){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:Ls.STATUS_CONFIRMED;if(d_(this,c),this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!n.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};n instanceof Sc.IncomingResponse&&(a=n.status_code<200?Ls.STATUS_EARLY:Ls.STATUS_CONFIRMED);var s=n.parseHeader("contact");l==="UAS"?(this._id={call_id:n.call_id,local_tag:n.to_tag,remote_tag:n.from_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=n.cseq,this._local_uri=n.parseHeader("to").uri,this._remote_uri=n.parseHeader("from").uri,this._remote_target=s.uri,this._route_set=n.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):l==="UAC"&&(this._id={call_id:n.call_id,local_tag:n.from_tag,remote_tag:n.to_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=n.cseq,this._local_uri=n.parseHeader("from").uri,this._remote_uri=n.parseHeader("to").uri,this._remote_target=s.uri,this._route_set=n.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),Ca.debug("new ".concat(l," dialog created with status ").concat(this._state===Ls.STATUS_EARLY?"EARLY":"CONFIRMED"))}return vc(c,[{key:"isTerminated",value:function(){return this._status===Ls.STATUS_TERMINATED}},{key:"update",value:function(n,l){this._state=Ls.STATUS_CONFIRMED,Ca.debug("dialog ".concat(this._id.toString()," changed to CONFIRMED state")),l==="UAC"&&(this._route_set=n.getHeaders("record-route").reverse())}},{key:"terminate",value:function(){Ca.debug("dialog ".concat(this._id.toString()," deleted")),this._ua.destroyDialog(this),this._state=Ls.STATUS_TERMINATED}},{key:"sendRequest",value:function(n){var l=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=ya.cloneArray(a.extraHeaders),r=ya.cloneObject(a.eventHandlers),h=a.body||null,d=this._createRequest(n,s,h);r.onAuthenticated=function(){l._local_seqnum+=1};var _=new __(this,d,r);return _.send(),d}},{key:"receiveRequest",value:function(n){this._checkInDialogRequest(n)&&(n.method===Ms.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:n.method===Ms.INVITE&&(this._ack_seqnum=n.cseq),this._owner.receiveRequest(n))}},{key:"_createRequest",value:function(n,l,a){l=ya.cloneArray(l),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));var s=n===Ms.CANCEL||n===Ms.ACK?this._local_seqnum:this._local_seqnum+=1,r=new Sc.OutgoingRequest(n,this._remote_target,this._ua,{cseq:s,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},l,a);return r}},{key:"_checkInDialogRequest",value:function(n){var l=this;if(!this._remote_seqnum)this._remote_seqnum=n.cseq;else if(n.cseq<this._remote_seqnum)if(n.method===Ms.ACK){if(this._ack_seqnum===null||n.cseq!==this._ack_seqnum)return!1}else return n.reply(500),!1;else n.cseq>this._remote_seqnum&&(this._remote_seqnum=n.cseq);if(n.method===Ms.INVITE||n.method===Ms.UPDATE&&n.body){if(this._uac_pending_reply===!0)n.reply(491);else if(this._uas_pending_reply===!0){var a=(Math.random()*10|0)+1;return n.reply(500,null,["Retry-After:".concat(a)]),!1}else{this._uas_pending_reply=!0;var s=function r(){(n.server_transaction.state===Ni.C.STATUS_ACCEPTED||n.server_transaction.state===Ni.C.STATUS_COMPLETED||n.server_transaction.state===Ni.C.STATUS_TERMINATED)&&(n.server_transaction.removeListener("stateChanged",r),l._uas_pending_reply=!1)};n.server_transaction.on("stateChanged",s)}n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Ni.C.STATUS_ACCEPTED&&(l._remote_target=n.parseHeader("contact").uri)})}else n.method===Ms.NOTIFY&&n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Ni.C.STATUS_COMPLETED&&(l._remote_target=n.parseHeader("contact").uri)});return!0}},{key:"id",get:function(){return this._id}},{key:"local_seqnum",get:function(){return this._local_seqnum},set:function(n){this._local_seqnum=n}},{key:"owner",get:function(){return this._owner}},{key:"uac_pending_reply",get:function(){return this._uac_pending_reply},set:function(n){this._uac_pending_reply=n}},{key:"uas_pending_reply",get:function(){return this._uas_pending_reply}}]),c}(),Pu={exports:{}};function Eo(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Eo=function(n){return typeof n}:Eo=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Eo(c)}function m_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Ec(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function g_(c,t,n){return t&&Ec(c.prototype,t),n&&Ec(c,n),c}function T_(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&_u(c,t)}function _u(c,t){return _u=Object.setPrototypeOf||function(l,a){return l.__proto__=a,l},_u(c,t)}function v_(c){var t=y_();return function(){var l=xo(c),a;if(t){var s=xo(this).constructor;a=Reflect.construct(l,arguments,s)}else a=l.apply(this,arguments);return S_(this,a)}}function S_(c,t){return t&&(Eo(t)==="object"||typeof t=="function")?t:E_(c)}function E_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function y_(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function xo(c){return xo=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},xo(c)}var C_=ft.EventEmitter,A_=dt,R_=lt,I_=Ws,yc=bt(),b_=new A_("RTCSession:DTMF"),od={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};Pu.exports=function(c){T_(n,c);var t=v_(n);function n(l){var a;return m_(this,n),a=t.call(this),a._session=l,a._direction=null,a._tone=null,a._duration=null,a._request=null,a}return g_(n,[{key:"send",value:function(a){var s=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(a===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new I_.InvalidStateError(this._session.status);var h=yc.cloneArray(r.extraHeaders);if(this.eventHandlers=yc.cloneObject(r.eventHandlers),typeof a=="string")a=a.toUpperCase();else if(typeof a=="number")a=a.toString();else throw new TypeError("Invalid tone: ".concat(a));if(a.match(/^[0-9A-DR#*]$/))this._tone=a;else throw new TypeError("Invalid tone: ".concat(a));this._duration=r.duration,h.push("Content-Type: application/dtmf-relay");var d="Signal=".concat(this._tone,`\r
|
|
47
|
-
`);d+="Duration=".concat(this._duration),this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(
|
|
48
|
-
`);h.length>=1&&
|
|
49
|
-
`,1)[0],"Status_Line");if(
|
|
50
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,h;return{s:function(){n=c[Symbol.iterator]()},n:function(){var _=n.next();return s=_.done,_},e:function(_){r=!0,h=_},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw h}}}}function np(c,t){if(c){if(typeof c=="string")return wc(c,t);var n=Object.prototype.toString.call(c).slice(8,-1);if(n==="Object"&&c.constructor&&(n=c.constructor.name),n==="Map"||n==="Set")return Array.from(c);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return wc(c,t)}}function wc(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,l=new Array(t);n<t;n++)l[n]=c[n];return l}function rp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Oc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function Dc(c,t,n){return t&&Oc(c.prototype,t),n&&Oc(c,n),c}function ip(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&gu(c,t)}function gu(c,t){return gu=Object.setPrototypeOf||function(l,a){return l.__proto__=a,l},gu(c,t)}function lp(c){var t=up();return function(){var l=Po(c),a;if(t){var s=Po(this).constructor;a=Reflect.construct(l,arguments,s)}else a=l.apply(this,arguments);return op(this,a)}}function op(c,t){return t&&(Ao(t)==="object"||typeof t=="function")?t:ap(c)}function ap(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function up(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Po(c){return Po=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Po(c)}var cp=ft.EventEmitter,Nc=kt,fp=dt,ce=lt,gn=Ws,xc=fl,Be=bt(),Ui=ld,dp=Es,jl=p_,hp=dl,Pt=w_,Uc=F_,_p=G_,pp=sp,kc=Ks(),J=new fp("RTCSession"),ee={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},ql=["audio","video"],mp=function(c){ip(n,c);var t=lp(n);Dc(n,null,[{key:"C",get:function(){return ee}}]);function n(l){var a;return rp(this,n),J.debug("new"),a=t.call(this),a._id=null,a._ua=l,a._status=ee.STATUS_NULL,a._dialog=null,a._earlyDialogs={},a._contact=null,a._from_tag=null,a._to_tag=null,a._connection=null,a._connectionPromiseQueue=Promise.resolve(),a._request=null,a._is_canceled=!1,a._cancel_reason="",a._is_confirmed=!1,a._late_sdp=!1,a._rtcOfferConstraints=null,a._rtcAnswerConstraints=null,a._localMediaStream=null,a._localMediaStreamLocallyGenerated=!1,a._rtcReady=!0,a._iceReady=!1,a._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},a._direction=null,a._local_identity=null,a._remote_identity=null,a._start_time=null,a._end_time=null,a._tones=null,a._audioMuted=!1,a._videoMuted=!1,a._localHold=!1,a._remoteHold=!1,a._sessionTimers={enabled:a._ua.configuration.session_timers,refreshMethod:a._ua.configuration.session_timers_refresh_method,defaultExpires:ce.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},a._referSubscribers={},a._data={},a}return Dc(n,[{key:"isInProgress",value:function(){switch(this._status){case ee.STATUS_NULL:case ee.STATUS_INVITE_SENT:case ee.STATUS_1XX_RECEIVED:case ee.STATUS_INVITE_RECEIVED:case ee.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}},{key:"isEstablished",value:function(){switch(this._status){case ee.STATUS_ANSWERED:case ee.STATUS_WAITING_FOR_ACK:case ee.STATUS_CONFIRMED:return!0;default:return!1}}},{key:"isEnded",value:function(){switch(this._status){case ee.STATUS_CANCELED:case ee.STATUS_TERMINATED:return!0;default:return!1}}},{key:"isMuted",value:function(){return{audio:this._audioMuted,video:this._videoMuted}}},{key:"isOnHold",value:function(){return{local:this._localHold,remote:this._remoteHold}}},{key:"connect",value:function(a){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;J.debug("connect()");var h=a,d=Be.cloneObject(s.eventHandlers),_=Be.cloneArray(s.extraHeaders),g=Be.cloneObject(s.mediaConstraints,{audio:!0,video:!0}),T=s.mediaStream||null,S=Be.cloneObject(s.pcConfig,{iceServers:[]}),E=s.rtcConstraints||null,C=s.rtcOfferConstraints||null;if(this._rtcOfferConstraints=C,this._rtcAnswerConstraints=s.rtcAnswerConstraints||null,this._data=s.data||this._data,a===void 0)throw new TypeError("Not enough arguments");if(this._status!==ee.STATUS_NULL)throw new gn.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new gn.NotSupportedError("WebRTC not supported");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(h));this._sessionTimers.enabled&&Be.isDecimal(s.sessionTimersExpires)&&(s.sessionTimersExpires>=ce.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=s.sessionTimersExpires:this._sessionTimers.defaultExpires=ce.SESSION_EXPIRES);for(var A in d)Object.prototype.hasOwnProperty.call(d,A)&&this.on(A,d[A]);this._from_tag=Be.newTag();var R=s.anonymous||!1,V={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:R,outbound:!0}),R?(V.from_display_name="Anonymous",V.from_uri=new kc("sip","anonymous","anonymous.invalid"),_.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),_.push("Privacy: id")):s.fromUserName&&(V.from_uri=new kc("sip",s.fromUserName,this._ua.configuration.uri.host),_.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),s.fromDisplayName&&(V.from_display_name=s.fromDisplayName),_.push("Contact: ".concat(this._contact)),_.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&_.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new dp.InitialOutgoingInviteRequest(a,this._ua,V,_),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(S,E),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,r&&r(this),this._newRTCSession("local",this._request),this._sendInitialRequest(g,C,T)}},{key:"init_incoming",value:function(a,s){var r=this;J.debug("init_incoming()");var h,d=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;if(a.body&&d!=="application/sdp"){a.reply(415);return}if(this._status=ee.STATUS_INVITE_RECEIVED,this._from_tag=a.from_tag,this._id=a.call_id+this._from_tag,this._request=a,this._contact=this._ua.contact.toString(),a.hasHeader("expires")&&(h=a.getHeader("expires")*1e3),a.to_tag=Be.newTag(),!this._createDialog(a,"UAS",!0)){a.reply(500,"Missing Contact header field");return}a.body?this._late_sdp=!1:this._late_sdp=!0,this._status=ee.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(function(){a.reply(408),r._failed("local",null,ce.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),h&&(this._timers.expiresTimer=setTimeout(function(){r._status===ee.STATUS_WAITING_FOR_ANSWER&&(a.reply(487),r._failed("system",null,ce.causes.EXPIRES))},h)),this._direction="incoming",this._local_identity=a.to,this._remote_identity=a.from,s&&s(this),this._newRTCSession("remote",a),this._status!==ee.STATUS_TERMINATED&&(a.reply(180,null,["Contact: ".concat(this._contact)]),this._progress("local",null))}},{key:"answer",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};J.debug("answer()");var r=this._request,h=Be.cloneArray(s.extraHeaders),d=Be.cloneObject(s.mediaConstraints),_=s.mediaStream||null,g=Be.cloneObject(s.pcConfig,{iceServers:[]}),T=s.rtcConstraints||null,S=s.rtcAnswerConstraints||null,E=Be.cloneObject(s.rtcOfferConstraints),C,A=!1,R=!1,V=!1,w=!1;if(this._rtcAnswerConstraints=S,this._rtcOfferConstraints=s.rtcOfferConstraints||null,this._data=s.data||this._data,this._direction!=="incoming")throw new gn.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==ee.STATUS_WAITING_FOR_ANSWER)throw new gn.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Be.isDecimal(s.sessionTimersExpires)&&(s.sessionTimersExpires>=ce.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=s.sessionTimersExpires:this._sessionTimers.defaultExpires=ce.SESSION_EXPIRES),this._status=ee.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),h.unshift("Contact: ".concat(this._contact));var le=r.parseSDP();Array.isArray(le.media)||(le.media=[le.media]);var x=_s(le.media),H;try{for(x.s();!(H=x.n()).done;){var ve=H.value;ve.type==="audio"&&(A=!0,(!ve.direction||ve.direction==="sendrecv")&&(V=!0)),ve.type==="video"&&(R=!0,(!ve.direction||ve.direction==="sendrecv")&&(w=!0))}}catch(F){x.e(F)}finally{x.f()}if(_&&d.audio===!1){C=_.getAudioTracks();var pe=_s(C),P;try{for(pe.s();!(P=pe.n()).done;){var N=P.value;_.removeTrack(N)}}catch(F){pe.e(F)}finally{pe.f()}}if(_&&d.video===!1){C=_.getVideoTracks();var q=_s(C),j;try{for(q.s();!(j=q.n()).done;){var Y=j.value;_.removeTrack(Y)}}catch(F){q.e(F)}finally{q.f()}}!_&&d.audio===void 0&&(d.audio=V),!_&&d.video===void 0&&(d.video=w),!_&&!A&&!E.offerToReceiveAudio&&(d.audio=!1),!_&&!R&&!E.offerToReceiveVideo&&(d.video=!1),this._createRTCConnection(g,T),Promise.resolve().then(function(){if(_)return _;if(d.audio||d.video)return a._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(d).catch(function(F){throw a._status===ee.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),a._failed("local",null,ce.causes.USER_DENIED_MEDIA_ACCESS),J.warn('emit "getusermediafailed" [error:%o]',F),a.emit("getusermediafailed",F),new Error("getUserMedia() failed"))})}).then(function(F){if(a._status===ee.STATUS_TERMINATED)throw new Error("terminated");a._localMediaStream=F,F&&F.getTracks().forEach(function(X){a._connection.addTrack(X,F)})}).then(function(){if(!a._late_sdp){var F={originator:"remote",type:"offer",sdp:r.body};J.debug('emit "sdp"'),a.emit("sdp",F);var X=new RTCSessionDescription({type:"offer",sdp:F.sdp});return a._connectionPromiseQueue=a._connectionPromiseQueue.then(function(){return a._connection.setRemoteDescription(X)}).catch(function(U){throw r.reply(488),a._failed("system",null,ce.causes.WEBRTC_ERROR),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',U),a.emit("peerconnection:setremotedescriptionfailed",U),new Error("peerconnection.setRemoteDescription() failed")}),a._connectionPromiseQueue}}).then(function(){if(a._status===ee.STATUS_TERMINATED)throw new Error("terminated");return a._connecting(r),a._late_sdp?a._createLocalDescription("offer",a._rtcOfferConstraints).catch(function(){throw r.reply(500),new Error("_createLocalDescription() failed")}):a._createLocalDescription("answer",S).catch(function(){throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(function(F){if(a._status===ee.STATUS_TERMINATED)throw new Error("terminated");a._handleSessionTimersInIncomingRequest(r,h),r.reply(200,null,h,F,function(){a._status=ee.STATUS_WAITING_FOR_ACK,a._setInvite2xxTimer(r,F),a._setACKTimer(),a._accepted("local")},function(){a._failed("system",null,ce.causes.CONNECTION_ERROR)})}).catch(function(F){a._status!==ee.STATUS_TERMINATED&&J.warn(F)})}},{key:"terminate",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};J.debug("terminate()");var r=s.cause||ce.causes.BYE,h=Be.cloneArray(s.extraHeaders),d=s.body,_,g=s.status_code,T=s.reason_phrase;if(this._status===ee.STATUS_TERMINATED)throw new gn.InvalidStateError(this._status);switch(this._status){case ee.STATUS_NULL:case ee.STATUS_INVITE_SENT:case ee.STATUS_1XX_RECEIVED:if(J.debug("canceling session"),g&&(g<200||g>=700))throw new TypeError("Invalid status_code: ".concat(g));g&&(T=T||ce.REASON_PHRASE[g]||"",_="SIP ;cause=".concat(g,' ;text="').concat(T,'"')),this._status===ee.STATUS_NULL||this._status===ee.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=_):this._status===ee.STATUS_1XX_RECEIVED&&this._request.cancel(_),this._status=ee.STATUS_CANCELED,this._failed("local",null,ce.causes.CANCELED);break;case ee.STATUS_WAITING_FOR_ANSWER:case ee.STATUS_ANSWERED:if(J.debug("rejecting session"),g=g||480,g<300||g>=700)throw new TypeError("Invalid status_code: ".concat(g));this._request.reply(g,T,h,d),this._failed("local",null,ce.causes.REJECTED);break;case ee.STATUS_WAITING_FOR_ACK:case ee.STATUS_CONFIRMED:if(J.debug("terminating session"),T=s.reason_phrase||ce.REASON_PHRASE[g]||"",g&&(g<200||g>=700))throw new TypeError("Invalid status_code: ".concat(g));if(g&&h.push("Reason: SIP ;cause=".concat(g,'; text="').concat(T,'"')),this._status===ee.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==xc.C.STATUS_TERMINATED){var S=this._dialog;this.receiveRequest=function(E){var C=E.method;C===ce.ACK&&(a.sendRequest(ce.BYE,{extraHeaders:h,body:d}),S.terminate())},this._request.server_transaction.on("stateChanged",function(){a._request.server_transaction.state===xc.C.STATUS_TERMINATED&&(a.sendRequest(ce.BYE,{extraHeaders:h,body:d}),S.terminate())}),this._ended("local",null,r),this._dialog=S,this._ua.newDialog(S)}else this.sendRequest(ce.BYE,{extraHeaders:h,body:d}),this._ended("local",null,r)}}},{key:"sendDTMF",value:function(a){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};J.debug("sendDTMF() | tones: %s",a);var r=0,h=s.duration||null,d=s.interToneGap||null,_=s.transportType||ce.DTMF_TRANSPORT.INFO;if(a===void 0)throw new TypeError("Not enough arguments");if(this._status!==ee.STATUS_CONFIRMED&&this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_1XX_RECEIVED)throw new gn.InvalidStateError(this._status);if(_!==ce.DTMF_TRANSPORT.INFO&&_!==ce.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(_));if(typeof a=="number"&&(a=a.toString()),!a||typeof a!="string"||!a.match(/^[0-9A-DR#*,]+$/i))throw new TypeError("Invalid tones: ".concat(a));if(h&&!Be.isDecimal(h))throw new TypeError("Invalid tone duration: ".concat(h));if(h?h<Pt.C.MIN_DURATION?(J.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(Pt.C.MIN_DURATION," milliseconds")),h=Pt.C.MIN_DURATION):h>Pt.C.MAX_DURATION?(J.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(Pt.C.MAX_DURATION," milliseconds")),h=Pt.C.MAX_DURATION):h=Math.abs(h):h=Pt.C.DEFAULT_DURATION,s.duration=h,d&&!Be.isDecimal(d))throw new TypeError("Invalid interToneGap: ".concat(d));if(d?d<Pt.C.MIN_INTER_TONE_GAP?(J.debug('"interToneGap" value is lower than the minimum allowed, setting it to '.concat(Pt.C.MIN_INTER_TONE_GAP," milliseconds")),d=Pt.C.MIN_INTER_TONE_GAP):d=Math.abs(d):d=Pt.C.DEFAULT_INTER_TONE_GAP,_===ce.DTMF_TRANSPORT.RFC2833){var g=this._getDTMFRTPSender();g&&(a=g.toneBuffer+a,g.insertDTMF(a,h,d));return}if(this._tones){this._tones+=a;return}this._tones=a,T.call(this);function T(){var S=this,E;if(this._status===ee.STATUS_TERMINATED||!this._tones||r>=this._tones.length){this._tones=null;return}var C=this._tones[r];if(r+=1,C===",")E=2e3;else{var A=new Pt(this);s.eventHandlers={onFailed:function(){S._tones=null}},A.send(C,s),E=h+d}setTimeout(T.bind(this),E)}}},{key:"sendInfo",value:function(a,s){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(J.debug("sendInfo()"),this._status!==ee.STATUS_CONFIRMED&&this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_1XX_RECEIVED)throw new gn.InvalidStateError(this._status);var h=new Uc(this);h.send(a,s,r)}},{key:"mute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};J.debug("mute()");var s=!1,r=!1;this._audioMuted===!1&&a.audio&&(s=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&a.video&&(r=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(s===!0||r===!0)&&this._onmute({audio:s,video:r})}},{key:"unmute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!0};J.debug("unmute()");var s=!1,r=!1;this._audioMuted===!0&&a.audio&&(s=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&a.video&&(r=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(s===!0||r===!0)&&this._onunmute({audio:s,video:r})}},{key:"hold",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;if(J.debug("hold()"),this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");var h={succeeded:function(){r&&r()},failed:function(){a.terminate({cause:ce.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return s.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:h,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:h,extraHeaders:s.extraHeaders}),!0}},{key:"unhold",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;if(J.debug("unhold()"),this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");var h={succeeded:function(){r&&r()},failed:function(){a.terminate({cause:ce.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return s.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:h,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:h,extraHeaders:s.extraHeaders}),!0}},{key:"renegotiate",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;J.debug("renegotiate()");var h=s.rtcOfferConstraints||null;if(this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;var d={succeeded:function(){r&&r()},failed:function(){a.terminate({cause:ce.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),s.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:d,rtcOfferConstraints:h,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:d,rtcOfferConstraints:h,extraHeaders:s.extraHeaders}),!0}},{key:"refer",value:function(a,s){var r=this;J.debug("refer()");var h=a;if(this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED)return!1;if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(h));var d=new pp(this);d.sendRefer(a,s);var _=d.id;return this._referSubscribers[_]=d,d.on("requestFailed",function(){delete r._referSubscribers[_]}),d.on("accepted",function(){delete r._referSubscribers[_]}),d.on("failed",function(){delete r._referSubscribers[_]}),d}},{key:"sendRequest",value:function(a,s){return J.debug("sendRequest()"),this._dialog.sendRequest(a,s)}},{key:"receiveRequest",value:function(a){var s=this;if(J.debug("receiveRequest()"),a.method===ce.CANCEL)(this._status===ee.STATUS_WAITING_FOR_ANSWER||this._status===ee.STATUS_ANSWERED)&&(this._status=ee.STATUS_CANCELED,this._request.reply(487),this._failed("remote",a,ce.causes.CANCELED));else switch(a.method){case ce.ACK:if(this._status!==ee.STATUS_WAITING_FOR_ACK)return;if(this._status=ee.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!a.body){this.terminate({cause:ce.causes.MISSING_SDP,status_code:400});break}var r={originator:"remote",type:"answer",sdp:a.body};J.debug('emit "sdp"'),this.emit("sdp",r);var h=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(h)}).then(function(){s._is_confirmed||s._confirmed("remote",a)}).catch(function(_){s.terminate({cause:ce.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',_),s.emit("peerconnection:setremotedescriptionfailed",_)})}else this._is_confirmed||this._confirmed("remote",a);break;case ce.BYE:this._status===ee.STATUS_CONFIRMED||this._status===ee.STATUS_WAITING_FOR_ACK?(a.reply(200),this._ended("remote",a,ce.causes.BYE)):this._status===ee.STATUS_INVITE_RECEIVED||this._status===ee.STATUS_WAITING_FOR_ANSWER?(a.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",a,ce.causes.BYE)):a.reply(403,"Wrong Status");break;case ce.INVITE:this._status===ee.STATUS_CONFIRMED?a.hasHeader("replaces")?this._receiveReplaces(a):this._receiveReinvite(a):a.reply(403,"Wrong Status");break;case ce.INFO:if(this._status===ee.STATUS_1XX_RECEIVED||this._status===ee.STATUS_WAITING_FOR_ANSWER||this._status===ee.STATUS_ANSWERED||this._status===ee.STATUS_WAITING_FOR_ACK||this._status===ee.STATUS_CONFIRMED){var d=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;d&&d.match(/^application\/dtmf-relay/i)?new Pt(this).init_incoming(a):d!==void 0?new Uc(this).init_incoming(a):a.reply(415)}else a.reply(403,"Wrong Status");break;case ce.UPDATE:this._status===ee.STATUS_CONFIRMED?this._receiveUpdate(a):a.reply(403,"Wrong Status");break;case ce.REFER:this._status===ee.STATUS_CONFIRMED?this._receiveRefer(a):a.reply(403,"Wrong Status");break;case ce.NOTIFY:this._status===ee.STATUS_CONFIRMED?this._receiveNotify(a):a.reply(403,"Wrong Status");break;default:a.reply(501)}}},{key:"onTransportError",value:function(){J.warn("onTransportError()"),this._status!==ee.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ce.causes.CONNECTION_ERROR,cause:ce.causes.CONNECTION_ERROR})}},{key:"onRequestTimeout",value:function(){J.warn("onRequestTimeout()"),this._status!==ee.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:ce.causes.REQUEST_TIMEOUT,cause:ce.causes.REQUEST_TIMEOUT})}},{key:"onDialogError",value:function(){J.warn("onDialogError()"),this._status!==ee.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ce.causes.DIALOG_ERROR,cause:ce.causes.DIALOG_ERROR})}},{key:"newDTMF",value:function(a){J.debug("newDTMF()"),this.emit("newDTMF",a)}},{key:"newInfo",value:function(a){J.debug("newInfo()"),this.emit("newInfo",a)}},{key:"_isReadyToReOffer",value:function(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(J.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(J.debug("_isReadyToReOffer() | session not established yet"),!1):(J.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(J.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(J.debug("close() | closing local MediaStream"),Be.closeMediaStream(this._localMediaStream)),this._status!==ee.STATUS_TERMINATED){if(this._status=ee.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(h){J.warn("close() | error closing the RTCPeerConnection: %o",h)}for(var a in this._timers)Object.prototype.hasOwnProperty.call(this._timers,a)&&clearTimeout(this._timers[a]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(var s in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,s)&&(this._earlyDialogs[s].terminate(),delete this._earlyDialogs[s]);for(var r in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,r)&&delete this._referSubscribers[r];this._ua.destroyRTCSession(this)}}},{key:"_setInvite2xxTimer",value:function(a,s){var r=Ui.T1;function h(){this._status===ee.STATUS_WAITING_FOR_ACK&&(a.reply(200,null,["Contact: ".concat(this._contact)],s),r<Ui.T2&&(r=r*2,r>Ui.T2&&(r=Ui.T2)),this._timers.invite2xxTimer=setTimeout(h.bind(this),r))}this._timers.invite2xxTimer=setTimeout(h.bind(this),r)}},{key:"_setACKTimer",value:function(){var a=this;this._timers.ackTimer=setTimeout(function(){a._status===ee.STATUS_WAITING_FOR_ACK&&(J.debug("no ACK received, terminating the session"),clearTimeout(a._timers.invite2xxTimer),a.sendRequest(ce.BYE),a._ended("remote",null,ce.causes.NO_ACK))},Ui.TIMER_H)}},{key:"_createRTCConnection",value:function(a,s){var r=this;this._connection=new RTCPeerConnection(a,s),this._connection.addEventListener("iceconnectionstatechange",function(){var h=r._connection.iceConnectionState;h==="failed"&&r.terminate({cause:ce.causes.RTP_TIMEOUT,status_code:408,reason_phrase:ce.causes.RTP_TIMEOUT})}),J.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(a,s){var r=this;if(J.debug("createLocalDescription()"),a!=="offer"&&a!=="answer")throw new Error('createLocalDescription() | invalid type "'.concat(a,'"'));var h=this._connection;return this._rtcReady=!1,Promise.resolve().then(function(){return a==="offer"?h.createOffer(s).catch(function(d){return J.warn('emit "peerconnection:createofferfailed" [error:%o]',d),r.emit("peerconnection:createofferfailed",d),Promise.reject(d)}):h.createAnswer(s).catch(function(d){return J.warn('emit "peerconnection:createanswerfailed" [error:%o]',d),r.emit("peerconnection:createanswerfailed",d),Promise.reject(d)})}).then(function(d){return h.setLocalDescription(d).catch(function(_){return r._rtcReady=!0,J.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',_),r.emit("peerconnection:setlocaldescriptionfailed",_),Promise.reject(_)})}).then(function(){var d=s&&s.iceRestart;if(h.iceGatheringState==="complete"&&!d||h.iceGatheringState==="gathering"&&r._iceReady){r._rtcReady=!0;var _={originator:"local",type:a,sdp:h.localDescription.sdp};return J.debug('emit "sdp"'),r.emit("sdp",_),Promise.resolve(_.sdp)}return new Promise(function(g){var T=!1,S,E;r._iceReady=!1;var C=function(){h.removeEventListener("icecandidate",S),h.removeEventListener("icegatheringstatechange",E),T=!0,r._rtcReady=!0,r._iceReady=!0;var R={originator:"local",type:a,sdp:h.localDescription.sdp};J.debug('emit "sdp"'),r.emit("sdp",R),g(R.sdp)};h.addEventListener("icecandidate",S=function(R){var V=R.candidate;V?r.emit("icecandidate",{candidate:V,ready:C}):T||C()}),h.addEventListener("icegatheringstatechange",E=function(){h.iceGatheringState==="complete"&&!T&&C()})})})}},{key:"_createDialog",value:function(a,s,r){var h=s==="UAS"?a.to_tag:a.from_tag,d=s==="UAS"?a.from_tag:a.to_tag,_=a.call_id+h+d,g=this._earlyDialogs[_];if(r)return g?!0:(g=new jl(this,a,s,jl.C.STATUS_EARLY),g.error?(J.debug(g.error),this._failed("remote",a,ce.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[_]=g,!0));if(this._from_tag=a.from_tag,this._to_tag=a.to_tag,g)return g.update(a,s),this._dialog=g,delete this._earlyDialogs[_],!0;var T=new jl(this,a,s);return T.error?(J.debug(T.error),this._failed("remote",a,ce.causes.INTERNAL_ERROR),!1):(this._dialog=T,!0)}},{key:"_receiveReinvite",value:function(a){var s=this;J.debug("receiveReinvite()");var r=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,h={request:a,callback:void 0,reject:_.bind(this)},d=!1;function _(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};d=!0;var S=T.status_code||403,E=T.reason_phrase||"",C=Be.cloneArray(T.extraHeaders);if(this._status!==ee.STATUS_CONFIRMED)return!1;if(S<300||S>=700)throw new TypeError("Invalid status_code: ".concat(S));a.reply(S,E,C)}if(this.emit("reinvite",h),d)return;if(this._late_sdp=!1,!a.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._createLocalDescription("offer",s._rtcOfferConstraints)}).then(function(T){g.call(s,T)}).catch(function(){a.reply(500)});return}if(r!=="application/sdp"){J.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(T){s._status!==ee.STATUS_TERMINATED&&g.call(s,T)}).catch(function(T){J.warn(T)});function g(T){var S=this,E=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,E),this._late_sdp&&(T=this._mangleOffer(T)),a.reply(200,null,E,T,function(){S._status=ee.STATUS_WAITING_FOR_ACK,S._setInvite2xxTimer(a,T),S._setACKTimer()}),typeof h.callback=="function"&&h.callback()}}},{key:"_receiveUpdate",value:function(a){var s=this;J.debug("receiveUpdate()");var r=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,h={request:a,callback:void 0,reject:_.bind(this)},d=!1;function _(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};d=!0;var S=T.status_code||403,E=T.reason_phrase||"",C=Be.cloneArray(T.extraHeaders);if(this._status!==ee.STATUS_CONFIRMED)return!1;if(S<300||S>=700)throw new TypeError("Invalid status_code: ".concat(S));a.reply(S,E,C)}if(this.emit("update",h),d)return;if(!a.body){g.call(this,null);return}if(r!=="application/sdp"){J.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(T){s._status!==ee.STATUS_TERMINATED&&g.call(s,T)}).catch(function(T){J.warn(T)});function g(T){var S=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,S),a.reply(200,null,S,T),typeof h.callback=="function"&&h.callback()}}},{key:"_processInDialogSdpOffer",value:function(a){var s=this;J.debug("_processInDialogSdpOffer()");var r=a.parseSDP(),h=!1,d=_s(r.media),_;try{for(d.s();!(_=d.n()).done;){var g=_.value;if(ql.indexOf(g.type)!==-1){var T=g.direction||r.direction||"sendrecv";if(T==="sendonly"||T==="inactive")h=!0;else{h=!1;break}}}}catch(C){d.e(C)}finally{d.f()}var S={originator:"remote",type:"offer",sdp:a.body};J.debug('emit "sdp"'),this.emit("sdp",S);var E=new RTCSessionDescription({type:"offer",sdp:S.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(s._status===ee.STATUS_TERMINATED)throw new Error("terminated");return s._connection.setRemoteDescription(E).catch(function(C){throw a.reply(488),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',C),s.emit("peerconnection:setremotedescriptionfailed",C),C})}).then(function(){if(s._status===ee.STATUS_TERMINATED)throw new Error("terminated");s._remoteHold===!0&&h===!1?(s._remoteHold=!1,s._onunhold("remote")):s._remoteHold===!1&&h===!0&&(s._remoteHold=!0,s._onhold("remote"))}).then(function(){if(s._status===ee.STATUS_TERMINATED)throw new Error("terminated");return s._createLocalDescription("answer",s._rtcAnswerConstraints).catch(function(C){throw a.reply(500),J.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',C),C})}).catch(function(C){J.warn("_processInDialogSdpOffer() failed [error: %o]",C)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(a){var s=this;if(J.debug("receiveRefer()"),!a.refer_to){J.debug("no Refer-To header field present in REFER"),a.reply(400);return}if(a.refer_to.uri.scheme!==ce.SIP){J.debug("Refer-To header field points to a non-SIP URI scheme"),a.reply(416);return}a.reply(202);var r=new _p(this,a.cseq);J.debug('emit "refer"'),this.emit("refer",{request:a,accept:function(g,T){h.call(s,g,T)},reject:function(){d.call(s)}});function h(_){var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(_=typeof _=="function"?_:null,this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED)return!1;var T=new n(this._ua);if(T.on("progress",function(E){var C=E.response;r.notify(C.status_code,C.reason_phrase)}),T.on("accepted",function(E){var C=E.response;r.notify(C.status_code,C.reason_phrase)}),T.on("_failed",function(E){var C=E.message,A=E.cause;C?r.notify(C.status_code,C.reason_phrase):r.notify(487,A)}),a.refer_to.uri.hasHeader("replaces")){var S=decodeURIComponent(a.refer_to.uri.getHeader("replaces"));g.extraHeaders=Be.cloneArray(g.extraHeaders),g.extraHeaders.push("Replaces: ".concat(S))}T.connect(a.refer_to.uri.toAor(),g,_)}function d(){r.notify(603)}}},{key:"_receiveNotify",value:function(a){switch(J.debug("receiveNotify()"),a.event||a.reply(400),a.event.event){case"refer":{var s,r;if(a.event.params&&a.event.params.id)s=a.event.params.id,r=this._referSubscribers[s];else if(Object.keys(this._referSubscribers).length===1)r=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{a.reply(400,"Missing event id parameter");return}if(!r){a.reply(481,"Subscription does not exist");return}r.receiveNotify(a),a.reply(200);break}default:a.reply(489)}}},{key:"_receiveReplaces",value:function(a){var s=this;J.debug("receiveReplaces()");function r(d){var _=this;if(this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED)return!1;var g=new n(this._ua);g.on("confirmed",function(){_.terminate()}),g.init_incoming(a,d)}function h(){J.debug("Replaced INVITE rejected by the user"),a.reply(486)}this.emit("replaces",{request:a,accept:function(_){r.call(s,_)},reject:function(){h.call(s)}})}},{key:"_sendInitialRequest",value:function(a,s,r){var h=this,d=new hp(this._ua,this._request,{onRequestTimeout:function(){h.onRequestTimeout()},onTransportError:function(){h.onTransportError()},onAuthenticated:function(g){h._request=g},onReceiveResponse:function(g){h._receiveInviteResponse(g)}});Promise.resolve().then(function(){if(r)return r;if(a.audio||a.video)return h._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(function(_){throw h._status===ee.STATUS_TERMINATED?new Error("terminated"):(h._failed("local",null,ce.causes.USER_DENIED_MEDIA_ACCESS),J.warn('emit "getusermediafailed" [error:%o]',_),h.emit("getusermediafailed",_),_)})}).then(function(_){if(h._status===ee.STATUS_TERMINATED)throw new Error("terminated");return h._localMediaStream=_,_&&_.getTracks().forEach(function(g){h._connection.addTrack(g,_)}),h._connecting(h._request),h._createLocalDescription("offer",s).catch(function(g){throw h._failed("local",null,ce.causes.WEBRTC_ERROR),g})}).then(function(_){if(h._is_canceled||h._status===ee.STATUS_TERMINATED)throw new Error("terminated");h._request.body=_,h._status=ee.STATUS_INVITE_SENT,J.debug('emit "sending" [request:%o]',h._request),h.emit("sending",{request:h._request}),d.send()}).catch(function(_){h._status!==ee.STATUS_TERMINATED&&J.warn(_)})}},{key:"_getDTMFRTPSender",value:function(){var a=this._connection.getSenders().find(function(s){return s.track&&s.track.kind==="audio"});if(!(a&&a.dtmf)){J.warn("sendDTMF() | no local audio track to send DTMF with");return}return a.dtmf}},{key:"_receiveInviteResponse",value:function(a){var s=this;if(J.debug("receiveInviteResponse()"),this._dialog&&a.status_code>=200&&a.status_code<=299)if(this._dialog.id.call_id===a.call_id&&this._dialog.id.local_tag===a.from_tag&&this._dialog.id.remote_tag===a.to_tag){this.sendRequest(ce.ACK);return}else{var r=new jl(this,a,"UAC");if(r.error!==void 0){J.debug(r.error);return}this.sendRequest(ce.ACK),this.sendRequest(ce.BYE);return}if(this._is_canceled){a.status_code>=100&&a.status_code<200?this._request.cancel(this._cancel_reason):a.status_code>=200&&a.status_code<299&&this._acceptAndTerminate(a);return}if(!(this._status!==ee.STATUS_INVITE_SENT&&this._status!==ee.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(a.status_code):this._status=ee.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(a.status_code):{if(!a.to_tag){J.debug("1xx response received without to tag");break}if(a.hasHeader("contact")&&!this._createDialog(a,"UAC",!0))break;if(this._status=ee.STATUS_1XX_RECEIVED,!a.body){this._progress("remote",a);break}var h={originator:"remote",type:"answer",sdp:a.body};J.debug('emit "sdp"'),this.emit("sdp",h);var d=new RTCSessionDescription({type:"answer",sdp:h.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(d)}).then(function(){return s._progress("remote",a)}).catch(function(S){J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),s.emit("peerconnection:setremotedescriptionfailed",S)});break}case/^2[0-9]{2}$/.test(a.status_code):{if(this._status=ee.STATUS_CONFIRMED,!a.body){this._acceptAndTerminate(a,400,ce.causes.MISSING_SDP),this._failed("remote",a,ce.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(a,"UAC"))break;var _={originator:"remote",type:"answer",sdp:a.body};J.debug('emit "sdp"'),this.emit("sdp",_);var g=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(s._connection.signalingState==="stable")return s._connection.createOffer(s._rtcOfferConstraints).then(function(S){return s._connection.setLocalDescription(S)}).catch(function(S){s._acceptAndTerminate(a,500,S.toString()),s._failed("local",a,ce.causes.WEBRTC_ERROR)})}).then(function(){s._connection.setRemoteDescription(g).then(function(){s._handleSessionTimersInIncomingResponse(a),s._accepted("remote",a),s.sendRequest(ce.ACK),s._confirmed("local",null)}).catch(function(S){s._acceptAndTerminate(a,488,"Not Acceptable Here"),s._failed("remote",a,ce.causes.BAD_MEDIA_DESCRIPTION),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),s.emit("peerconnection:setremotedescriptionfailed",S)})});break}default:{var T=Be.sipErrorCause(a.status_code);this._failed("remote",a,T)}}}},{key:"_sendReinvite",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};J.debug("sendReinvite()");var r=Be.cloneArray(s.extraHeaders),h=Be.cloneObject(s.eventHandlers),d=s.rtcOfferConstraints||this._rtcOfferConstraints||null,_=!1;r.push("Contact: ".concat(this._contact)),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",d)}).then(function(S){S=a._mangleOffer(S);var E={originator:"local",type:"offer",sdp:S};J.debug('emit "sdp"'),a.emit("sdp",E),a.sendRequest(ce.INVITE,{extraHeaders:r,body:S,eventHandlers:{onSuccessResponse:function(A){g.call(a,A),_=!0},onErrorResponse:function(A){T.call(a,A)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){T()});function g(S){var E=this;if(this._status!==ee.STATUS_TERMINATED&&(this.sendRequest(ce.ACK),!_)){if(this._handleSessionTimersInIncomingResponse(S),S.body){if(!S.hasHeader("Content-Type")||S.getHeader("Content-Type").toLowerCase()!=="application/sdp"){T.call(this);return}}else{T.call(this);return}var C={originator:"remote",type:"answer",sdp:S.body};J.debug('emit "sdp"'),this.emit("sdp",C);var A=new RTCSessionDescription({type:"answer",sdp:C.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return E._connection.setRemoteDescription(A)}).then(function(){h.succeeded&&h.succeeded(S)}).catch(function(R){T.call(E),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),E.emit("peerconnection:setremotedescriptionfailed",R)})}}function T(S){h.failed&&h.failed(S)}}},{key:"_sendUpdate",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};J.debug("sendUpdate()");var r=Be.cloneArray(s.extraHeaders),h=Be.cloneObject(s.eventHandlers),d=s.rtcOfferConstraints||this._rtcOfferConstraints||null,_=s.sdpOffer||!1,g=!1;r.push("Contact: ".concat(this._contact)),this._sessionTimers.running&&r.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),_?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",d)}).then(function(E){E=a._mangleOffer(E);var C={originator:"local",type:"offer",sdp:E};J.debug('emit "sdp"'),a.emit("sdp",C),a.sendRequest(ce.UPDATE,{extraHeaders:r,body:E,eventHandlers:{onSuccessResponse:function(R){T.call(a,R),g=!0},onErrorResponse:function(R){S.call(a,R)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){S.call(a)})):this.sendRequest(ce.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:function(C){T.call(a,C)},onErrorResponse:function(C){S.call(a,C)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}});function T(E){var C=this;if(this._status!==ee.STATUS_TERMINATED&&!g)if(this._handleSessionTimersInIncomingResponse(E),_){if(E.body){if(!E.hasHeader("Content-Type")||E.getHeader("Content-Type").toLowerCase()!=="application/sdp"){S.call(this);return}}else{S.call(this);return}var A={originator:"remote",type:"answer",sdp:E.body};J.debug('emit "sdp"'),this.emit("sdp",A);var R=new RTCSessionDescription({type:"answer",sdp:A.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return C._connection.setRemoteDescription(R)}).then(function(){h.succeeded&&h.succeeded(E)}).catch(function(V){S.call(C),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',V),C.emit("peerconnection:setremotedescriptionfailed",V)})}else h.succeeded&&h.succeeded(E)}function S(E){h.failed&&h.failed(E)}}},{key:"_acceptAndTerminate",value:function(a,s,r){J.debug("acceptAndTerminate()");var h=[];s&&(r=r||ce.REASON_PHRASE[s]||"",h.push("Reason: SIP ;cause=".concat(s,'; text="').concat(r,'"'))),(this._dialog||this._createDialog(a,"UAC"))&&(this.sendRequest(ce.ACK),this.sendRequest(ce.BYE,{extraHeaders:h})),this._status=ee.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(a){if(!this._localHold&&!this._remoteHold)return a;if(a=Nc.parse(a),this._localHold&&!this._remoteHold){J.debug("mangleOffer() | me on hold, mangling offer");var s=_s(a.media),r;try{for(s.s();!(r=s.n()).done;){var h=r.value;ql.indexOf(h.type)!==-1&&(h.direction?h.direction==="sendrecv"?h.direction="sendonly":h.direction==="recvonly"&&(h.direction="inactive"):h.direction="sendonly")}}catch(C){s.e(C)}finally{s.f()}}else if(this._localHold&&this._remoteHold){J.debug("mangleOffer() | both on hold, mangling offer");var d=_s(a.media),_;try{for(d.s();!(_=d.n()).done;){var g=_.value;ql.indexOf(g.type)!==-1&&(g.direction="inactive")}}catch(C){d.e(C)}finally{d.f()}}else if(this._remoteHold){J.debug("mangleOffer() | remote on hold, mangling offer");var T=_s(a.media),S;try{for(T.s();!(S=T.n()).done;){var E=S.value;ql.indexOf(E.type)!==-1&&(E.direction?E.direction==="sendrecv"?E.direction="recvonly":E.direction==="recvonly"&&(E.direction="inactive"):E.direction="recvonly")}}catch(C){T.e(C)}finally{T.f()}}return Nc.write(a)}},{key:"_setLocalMediaStatus",value:function(){var a=!0,s=!0;(this._localHold||this._remoteHold)&&(a=!1,s=!1),this._audioMuted&&(a=!1),this._videoMuted&&(s=!1),this._toggleMuteAudio(!a),this._toggleMuteVideo(!s)}},{key:"_handleSessionTimersInIncomingRequest",value:function(a,s){if(this._sessionTimers.enabled){var r;a.session_expires&&a.session_expires>=ce.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,r=a.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uas"),s.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(r)),this._sessionTimers.refresher=r==="uas",this._runSessionTimer()}}},{key:"_handleSessionTimersInIncomingResponse",value:function(a){if(this._sessionTimers.enabled){var s;a.session_expires&&a.session_expires>=ce.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,s=a.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,s="uac"),this._sessionTimers.refresher=s==="uac",this._runSessionTimer()}}},{key:"_runSessionTimer",value:function(){var a=this,s=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(function(){a._status!==ee.STATUS_TERMINATED&&a._isReadyToReOffer()&&(J.debug("runSessionTimer() | sending session refresh request"),a._sessionTimers.refreshMethod===ce.UPDATE?a._sendUpdate():a._sendReinvite())},s*500):this._sessionTimers.timer=setTimeout(function(){a._status!==ee.STATUS_TERMINATED&&(J.warn("runSessionTimer() | timer expired, terminating the session"),a.terminate({cause:ce.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},s*1100)}},{key:"_toggleMuteAudio",value:function(a){var s=this._connection.getSenders().filter(function(_){return _.track&&_.track.kind==="audio"}),r=_s(s),h;try{for(r.s();!(h=r.n()).done;){var d=h.value;d.track.enabled=!a}}catch(_){r.e(_)}finally{r.f()}}},{key:"_toggleMuteVideo",value:function(a){var s=this._connection.getSenders().filter(function(_){return _.track&&_.track.kind==="video"}),r=_s(s),h;try{for(r.s();!(h=r.n()).done;){var d=h.value;d.track.enabled=!a}}catch(_){r.e(_)}finally{r.f()}}},{key:"_newRTCSession",value:function(a,s){J.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:a,session:this,request:s})}},{key:"_connecting",value:function(a){J.debug("session connecting"),J.debug('emit "connecting"'),this.emit("connecting",{request:a})}},{key:"_progress",value:function(a,s){J.debug("session progress"),J.debug('emit "progress"'),this.emit("progress",{originator:a,response:s||null})}},{key:"_accepted",value:function(a,s){J.debug("session accepted"),this._start_time=new Date,J.debug('emit "accepted"'),this.emit("accepted",{originator:a,response:s||null})}},{key:"_confirmed",value:function(a,s){J.debug("session confirmed"),this._is_confirmed=!0,J.debug('emit "confirmed"'),this.emit("confirmed",{originator:a,ack:s||null})}},{key:"_ended",value:function(a,s,r){J.debug("session ended"),this._end_time=new Date,this._close(),J.debug('emit "ended"'),this.emit("ended",{originator:a,message:s||null,cause:r})}},{key:"_failed",value:function(a,s,r){J.debug("session failed"),J.debug('emit "_failed"'),this.emit("_failed",{originator:a,message:s||null,cause:r}),this._close(),J.debug('emit "failed"'),this.emit("failed",{originator:a,message:s||null,cause:r})}},{key:"_onhold",value:function(a){J.debug("session onhold"),this._setLocalMediaStatus(),J.debug('emit "hold"'),this.emit("hold",{originator:a})}},{key:"_onunhold",value:function(a){J.debug("session onunhold"),this._setLocalMediaStatus(),J.debug('emit "unhold"'),this.emit("unhold",{originator:a})}},{key:"_onmute",value:function(a){var s=a.audio,r=a.video;J.debug("session onmute"),this._setLocalMediaStatus(),J.debug('emit "muted"'),this.emit("muted",{audio:s,video:r})}},{key:"_onunmute",value:function(a){var s=a.audio,r=a.video;J.debug("session onunmute"),this._setLocalMediaStatus(),J.debug('emit "unmuted"'),this.emit("unmuted",{audio:s,video:r})}},{key:"C",get:function(){return ee}},{key:"causes",get:function(){return ce.causes}},{key:"id",get:function(){return this._id}},{key:"connection",get:function(){return this._connection}},{key:"contact",get:function(){return this._contact}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}},{key:"start_time",get:function(){return this._start_time}},{key:"end_time",get:function(){return this._end_time}},{key:"data",get:function(){return this._data},set:function(a){this._data=a}},{key:"status",get:function(){return this._status}}]),n}(cp);function Ro(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ro=function(n){return typeof n}:Ro=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Ro(c)}function gp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Pc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function Tp(c,t,n){return t&&Pc(c.prototype,t),n&&Pc(c,n),c}function vp(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&Tu(c,t)}function Tu(c,t){return Tu=Object.setPrototypeOf||function(l,a){return l.__proto__=a,l},Tu(c,t)}function Sp(c){var t=Cp();return function(){var l=Mo(c),a;if(t){var s=Mo(this).constructor;a=Reflect.construct(l,arguments,s)}else a=l.apply(this,arguments);return Ep(this,a)}}function Ep(c,t){return t&&(Ro(t)==="object"||typeof t=="function")?t:yp(c)}function yp(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Cp(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Mo(c){return Mo=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Mo(c)}var Ap=ft.EventEmitter,Rp=dt,Ra=lt,Ip=Es,ki=bt(),bp=dl,Mc=Ws,wp=Ks(),Bl=new Rp("Message"),Op=function(c){vp(n,c);var t=Sp(n);function n(l){var a;return gp(this,n),a=t.call(this),a._ua=l,a._request=null,a._closed=!1,a._direction=null,a._local_identity=null,a._remote_identity=null,a._is_replied=!1,a._data={},a}return Tp(n,[{key:"send",value:function(a,s){var r=this,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},d=a;if(a===void 0||s===void 0)throw new TypeError("Not enough arguments");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(d));var _=ki.cloneArray(h.extraHeaders),g=ki.cloneObject(h.eventHandlers),T=h.contentType||"text/plain",S={};h.fromUserName&&(S.from_uri=new wp("sip",h.fromUserName,this._ua.configuration.uri.host),_.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),h.fromDisplayName&&(S.from_display_name=h.fromDisplayName);for(var E in g)Object.prototype.hasOwnProperty.call(g,E)&&this.on(E,g[E]);_.push("Content-Type: ".concat(T)),this._request=new Ip.OutgoingRequest(Ra.MESSAGE,a,this._ua,S,_),s&&(this._request.body=s);var C=new bp(this._ua,this._request,{onRequestTimeout:function(){r._onRequestTimeout()},onTransportError:function(){r._onTransportError()},onReceiveResponse:function(R){r._receiveResponse(R)}});this._newMessage("local",this._request),C.send()}},{key:"init_incoming",value:function(a){this._request=a,this._newMessage("remote",a),this._is_replied||(this._is_replied=!0,a.reply(200)),this._close()}},{key:"accept",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=ki.cloneArray(a.extraHeaders),r=a.body;if(this._direction!=="incoming")throw new Mc.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,s,r)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=a.status_code||480,r=a.reason_phrase,h=ki.cloneArray(a.extraHeaders),d=a.body;if(this._direction!=="incoming")throw new Mc.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(s<300||s>=700)throw new TypeError("Invalid status_code: ".concat(s));this._is_replied=!0,this._request.reply(s,r,h,d)}},{key:"_receiveResponse",value:function(a){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._succeeded("remote",a);break;default:{var s=ki.sipErrorCause(a.status_code);this._failed("remote",a,s);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Ra.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Ra.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newMessage",value:function(a,s){a==="remote"?(this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from):a==="local"&&(this._direction="outgoing",this._local_identity=s.from,this._remote_identity=s.to),this._ua.newMessage(this,{originator:a,message:this,request:s})}},{key:"_failed",value:function(a,s,r){Bl.debug("MESSAGE failed"),this._close(),Bl.debug('emit "failed"'),this.emit("failed",{originator:a,response:s||null,cause:r})}},{key:"_succeeded",value:function(a,s){Bl.debug("MESSAGE succeeded"),this._close(),Bl.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:s})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),n}(Ap);function Io(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Io=function(n){return typeof n}:Io=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Io(c)}function Dp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Lc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function Np(c,t,n){return t&&Lc(c.prototype,t),n&&Lc(c,n),c}function xp(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&vu(c,t)}function vu(c,t){return vu=Object.setPrototypeOf||function(l,a){return l.__proto__=a,l},vu(c,t)}function Up(c){var t=Mp();return function(){var l=Lo(c),a;if(t){var s=Lo(this).constructor;a=Reflect.construct(l,arguments,s)}else a=l.apply(this,arguments);return kp(this,a)}}function kp(c,t){return t&&(Io(t)==="object"||typeof t=="function")?t:Pp(c)}function Pp(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Mp(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Lo(c){return Lo=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Lo(c)}var Lp=ft.EventEmitter,$p=dt,Ia=lt,Hp=Es,Pi=bt(),Fp=dl,$c=Ws,Gl=new $p("Options"),Vp=function(c){xp(n,c);var t=Up(n);function n(l){var a;return Dp(this,n),a=t.call(this),a._ua=l,a._request=null,a._closed=!1,a._direction=null,a._local_identity=null,a._remote_identity=null,a._is_replied=!1,a._data={},a}return Np(n,[{key:"send",value:function(a,s){var r=this,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},d=a;if(a===void 0)throw new TypeError("A target is required for OPTIONS");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(d));var _=Pi.cloneArray(h.extraHeaders),g=Pi.cloneObject(h.eventHandlers),T=h.contentType||"application/sdp";for(var S in g)Object.prototype.hasOwnProperty.call(g,S)&&this.on(S,g[S]);_.push("Content-Type: ".concat(T)),this._request=new Hp.OutgoingRequest(Ia.OPTIONS,a,this._ua,null,_),s&&(this._request.body=s);var E=new Fp(this._ua,this._request,{onRequestTimeout:function(){r._onRequestTimeout()},onTransportError:function(){r._onTransportError()},onReceiveResponse:function(A){r._receiveResponse(A)}});this._newOptions("local",this._request),E.send()}},{key:"init_incoming",value:function(a){this._request=a,this._newOptions("remote",a),this._is_replied||(this._is_replied=!0,a.reply(200)),this._close()}},{key:"accept",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=Pi.cloneArray(a.extraHeaders),r=a.body;if(this._direction!=="incoming")throw new $c.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,s,r)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=a.status_code||480,r=a.reason_phrase,h=Pi.cloneArray(a.extraHeaders),d=a.body;if(this._direction!=="incoming")throw new $c.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(s<300||s>=700)throw new TypeError("Invalid status_code: ".concat(s));this._is_replied=!0,this._request.reply(s,r,h,d)}},{key:"_receiveResponse",value:function(a){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._succeeded("remote",a);break;default:{var s=Pi.sipErrorCause(a.status_code);this._failed("remote",a,s);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Ia.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Ia.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newOptions",value:function(a,s){a==="remote"?(this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from):a==="local"&&(this._direction="outgoing",this._local_identity=s.from,this._remote_identity=s.to),this._ua.newOptions(this,{originator:a,message:this,request:s})}},{key:"_failed",value:function(a,s,r){Gl.debug("OPTIONS failed"),this._close(),Gl.debug('emit "failed"'),this.emit("failed",{originator:a,response:s||null,cause:r})}},{key:"_succeeded",value:function(a,s){Gl.debug("OPTIONS succeeded"),this._close(),Gl.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:s})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),n}(Lp),Mu={},jp=dt,ba=bt(),qp=as(),Mi=new jp("Socket");Mu.isSocket=function(c){if(Array.isArray(c))return!1;if(typeof c>"u")return Mi.warn("undefined JsSIP.Socket instance"),!1;try{if(!ba.isString(c.url))throw Mi.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!ba.isString(c.via_transport))throw Mi.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(qp.parse(c.sip_uri,"SIP_URI")===-1)throw Mi.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(function(t){if(!ba.isFunction(c[t]))throw Mi.warn("missing or invalid JsSIP.Socket method: ".concat(t)),new Error("Missing or invalid JsSIP.Socket method: ".concat(t))})}catch{return!1}return!0};function Bp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Hc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function Gp(c,t,n){return t&&Hc(c.prototype,t),n&&Hc(c,n),c}var Wp=dt,Kp=Mu,Fc=lt,Nt=new Wp("Transport"),jt={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:Fc.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:Fc.CONNECTION_RECOVERY_MAX_INTERVAL}},Yp=function(){function c(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:jt.recovery_options;Bp(this,c),Nt.debug("new()"),this.status=jt.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=n,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(l){Nt.warn("cannot use TextDecoder: ".concat(l))}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(l){if(!Kp.isSocket(l.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(l.weight&&!Number(l.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:l.socket,weight:l.weight||0,status:jt.SOCKET_STATUS_READY})},this),this._getSocket()}return Gp(c,[{key:"connect",value:function(){if(Nt.debug("connect()"),this.isConnected()){Nt.debug("Transport is already connected");return}else if(this.isConnecting()){Nt.debug("Transport is connecting");return}this.close_requested=!1,this.status=jt.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}},{key:"disconnect",value:function(){Nt.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=jt.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=function(){},this.socket.ondisconnect=function(){},this.socket.ondata=function(){},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}},{key:"send",value:function(n){if(Nt.debug("send()"),!this.isConnected())return Nt.warn("unable to send message, transport is not connected"),!1;var l=n.toString();return Nt.debug(`sending message:
|
|
46
|
+
`),this.transport.send(h)}}]),s}(fd),Gh=function(c){Mu(s,c);var t=Pu(s);function s(){var i;return il(this,s),i=t.call(this),i.headers={},i.status_code=null,i.reason_phrase=null,i}return s}(fd),ys={OutgoingRequest:cd,InitialOutgoingInviteRequest:qh,IncomingRequest:Bh,IncomingResponse:Gh};function Wh(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function ac(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function Kh(c,t,s){return t&&ac(c.prototype,t),s&&ac(c,s),c}var Yh=ht,hs=wt(),Jt=new Yh("DigestAuthentication"),Jh=function(){function c(t){Wh(this,c),this._credentials=t,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}return Kh(c,[{key:"get",value:function(s){switch(s){case"realm":return this._realm;case"ha1":return this._ha1;default:Jt.warn('get() | cannot get "%s" parameter',s);return}}},{key:"authenticate",value:function(s,i){var a=s.method,n=s.ruri,r=s.body,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this._algorithm=i.algorithm,this._realm=i.realm,this._nonce=i.nonce,this._opaque=i.opaque,this._stale=i.stale,this._algorithm){if(this._algorithm!=="MD5")return Jt.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return Jt.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return Jt.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return Jt.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return Jt.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(i.qop)if(i.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(i.qop.indexOf("auth")>-1)this._qop="auth";else return Jt.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=a,this._uri=n,this._cnonce=h||hs.createRandomToken(12),this._nc+=1;var d=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-d.length)+d,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=hs.calculateMD5("".concat(this._credentials.username,":").concat(this._realm,":").concat(this._credentials.password)):this._ha1=this._credentials.ha1;var _,g;return this._qop==="auth"?(_="".concat(this._method,":").concat(this._uri),g=hs.calculateMD5(_),Jt.debug('authenticate() | using qop=auth [a2:"%s"]',_),this._response=hs.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth:").concat(g))):this._qop==="auth-int"?(_="".concat(this._method,":").concat(this._uri,":").concat(hs.calculateMD5(r||"")),g=hs.calculateMD5(_),Jt.debug('authenticate() | using qop=auth-int [a2:"%s"]',_),this._response=hs.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth-int:").concat(g))):this._qop===null&&(_="".concat(this._method,":").concat(this._uri),g=hs.calculateMD5(_),Jt.debug('authenticate() | using qop=null [a2:"%s"]',_),this._response=hs.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(g))),Jt.debug("authenticate() | response generated"),!0}},{key:"toString",value:function(){var s=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return s.push("algorithm=".concat(this._algorithm)),s.push('username="'.concat(this._credentials.username,'"')),s.push('realm="'.concat(this._realm,'"')),s.push('nonce="'.concat(this._nonce,'"')),s.push('uri="'.concat(this._uri,'"')),s.push('response="'.concat(this._response,'"')),this._opaque&&s.push('opaque="'.concat(this._opaque,'"')),this._qop&&(s.push("qop=".concat(this._qop)),s.push('cnonce="'.concat(this._cnonce,'"')),s.push("nc=".concat(this._ncHex))),"Digest ".concat(s.join(", "))}}]),c}(),_s=500,zh=4e3,uc=5e3,dd={T1:_s,T2:zh,T4:uc,TIMER_B:64*_s,TIMER_D:0*_s,TIMER_F:64*_s,TIMER_H:64*_s,TIMER_I:0*_s,TIMER_J:0*_s,TIMER_K:0*uc,TIMER_L:64*_s,TIMER_M:64*_s,PROVISIONAL_RESPONSE_INTERVAL:6e4};function yo(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?yo=function(s){return typeof s}:yo=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},yo(c)}function ll(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function cc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function ol(c,t,s){return t&&cc(c.prototype,t),s&&cc(c,s),c}function al(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&pu(c,t)}function pu(c,t){return pu=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},pu(c,t)}function ul(c){var t=Xh();return function(){var i=Uo(c),a;if(t){var n=Uo(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return Qh(this,a)}}function Qh(c,t){return t&&(yo(t)==="object"||typeof t=="function")?t:Gs(c)}function Gs(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Xh(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Uo(c){return Uo=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},Uo(c)}var cl=dt.EventEmitter,fl=ht,zi=ot,fc=ys,os=dd,dc=new fl("NonInviteClientTransaction"),Hl=new fl("InviteClientTransaction"),Zh=new fl("AckClientTransaction"),hc=new fl("NonInviteServerTransaction"),Fl=new fl("InviteServerTransaction"),de={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"},e_=function(c){al(s,c);var t=ul(s);function s(i,a,n,r){var h;ll(this,s),h=t.call(this),h.type=de.NON_INVITE_CLIENT,h.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),h.ua=i,h.transport=a,h.request=n,h.eventHandlers=r;var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(i.configuration.via_host,";branch=").concat(h.id),h.request.setHeader("via",d),h.ua.newTransaction(Gs(h)),h}return ol(s,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(de.STATUS_TRYING),this.F=setTimeout(function(){a.timer_F()},os.TIMER_F),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){dc.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}},{key:"timer_F",value:function(){dc.debug("Timer F expired for transaction ".concat(this.id)),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}},{key:"timer_K",value:function(){this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"receiveResponse",value:function(a){var n=this,r=a.status_code;if(r<200)switch(this.state){case de.STATUS_TRYING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break}else switch(this.state){case de.STATUS_TRYING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_COMPLETED),clearTimeout(this.F),r===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(a),this.K=setTimeout(function(){n.timer_K()},os.TIMER_K);break;case de.STATUS_COMPLETED:break}}},{key:"C",get:function(){return de}}]),s}(cl),t_=function(c){al(s,c);var t=ul(s);function s(i,a,n,r){var h;ll(this,s),h=t.call(this),h.type=de.INVITE_CLIENT,h.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),h.ua=i,h.transport=a,h.request=n,h.eventHandlers=r,n.transaction=Gs(h);var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(i.configuration.via_host,";branch=").concat(h.id),h.request.setHeader("via",d),h.ua.newTransaction(Gs(h)),h}return ol(s,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(de.STATUS_CALLING),this.B=setTimeout(function(){a.timer_B()},os.TIMER_B),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==de.STATUS_ACCEPTED&&(Hl.debug("transport error occurred, deleting transaction ".concat(this.id)),this.eventHandlers.onTransportError()),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_M",value:function(){Hl.debug("Timer M expired for transaction ".concat(this.id)),this.state===de.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"timer_B",value:function(){Hl.debug("Timer B expired for transaction ".concat(this.id)),this.state===de.STATUS_CALLING&&(this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}},{key:"timer_D",value:function(){Hl.debug("Timer D expired for transaction ".concat(this.id)),clearTimeout(this.B),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"sendACK",value:function(a){var n=this,r=new fc.OutgoingRequest(zi.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});r.setHeader("from",this.request.getHeader("from")),r.setHeader("via",this.request.getHeader("via")),r.setHeader("to",a.getHeader("to")),this.D=setTimeout(function(){n.timer_D()},os.TIMER_D),this.transport.send(r)}},{key:"cancel",value:function(a){if(this.state===de.STATUS_PROCEEDING){var n=new fc.OutgoingRequest(zi.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});n.setHeader("from",this.request.getHeader("from")),n.setHeader("via",this.request.getHeader("via")),n.setHeader("to",this.request.getHeader("to")),a&&n.setHeader("reason",a),this.transport.send(n)}}},{key:"receiveResponse",value:function(a){var n=this,r=a.status_code;if(r>=100&&r<=199)switch(this.state){case de.STATUS_CALLING:this.stateChanged(de.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break;case de.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(a);break}else if(r>=200&&r<=299)switch(this.state){case de.STATUS_CALLING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_ACCEPTED),this.M=setTimeout(function(){n.timer_M()},os.TIMER_M),this.eventHandlers.onReceiveResponse(a);break;case de.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(a);break}else if(r>=300&&r<=699)switch(this.state){case de.STATUS_CALLING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_COMPLETED),this.sendACK(a),this.eventHandlers.onReceiveResponse(a);break;case de.STATUS_COMPLETED:this.sendACK(a);break}}},{key:"C",get:function(){return de}}]),s}(cl),s_=function(c){al(s,c);var t=ul(s);function s(i,a,n,r){var h;ll(this,s),h=t.call(this),h.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),h.transport=a,h.request=n,h.eventHandlers=r;var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(i.configuration.via_host,";branch=").concat(h.id),h.request.setHeader("via",d),h}return ol(s,[{key:"send",value:function(){this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){Zh.debug("transport error occurred for transaction ".concat(this.id)),this.eventHandlers.onTransportError()}},{key:"C",get:function(){return de}}]),s}(cl),n_=function(c){al(s,c);var t=ul(s);function s(i,a,n){var r;return ll(this,s),r=t.call(this),r.type=de.NON_INVITE_SERVER,r.id=n.via_branch,r.ua=i,r.transport=a,r.request=n,r.last_response="",n.server_transaction=Gs(r),r.state=de.STATUS_TRYING,i.newTransaction(Gs(r)),r}return ol(s,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_J",value:function(){hc.debug("Timer J expired for transaction ".concat(this.id)),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,hc.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.J),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"receiveResponse",value:function(a,n,r,h){var d=this;if(a===100)switch(this.state){case de.STATUS_TRYING:this.stateChanged(de.STATUS_PROCEEDING),this.transport.send(n)||this.onTransportError();break;case de.STATUS_PROCEEDING:this.last_response=n,this.transport.send(n)?r&&r():(this.onTransportError(),h&&h());break}else if(a>=200&&a<=699)switch(this.state){case de.STATUS_TRYING:case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_COMPLETED),this.last_response=n,this.J=setTimeout(function(){d.timer_J()},os.TIMER_J),this.transport.send(n)?r&&r():(this.onTransportError(),h&&h());break;case de.STATUS_COMPLETED:break}}},{key:"C",get:function(){return de}}]),s}(cl),r_=function(c){al(s,c);var t=ul(s);function s(i,a,n){var r;return ll(this,s),r=t.call(this),r.type=de.INVITE_SERVER,r.id=n.via_branch,r.ua=i,r.transport=a,r.request=n,r.last_response="",n.server_transaction=Gs(r),r.state=de.STATUS_PROCEEDING,i.newTransaction(Gs(r)),r.resendProvisionalTimer=null,n.reply(100),r}return ol(s,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_H",value:function(){Fl.debug("Timer H expired for transaction ".concat(this.id)),this.state===de.STATUS_COMPLETED&&Fl.debug("ACK not received, dialog will be terminated"),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_I",value:function(){this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_L",value:function(){Fl.debug("Timer L expired for transaction ".concat(this.id)),this.state===de.STATUS_ACCEPTED&&(this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,Fl.debug("transport error occurred, deleting transaction ".concat(this.id)),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(de.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"resend_provisional",value:function(){this.transport.send(this.last_response)||this.onTransportError()}},{key:"receiveResponse",value:function(a,n,r,h){var d=this;if(a>=100&&a<=199)switch(this.state){case de.STATUS_PROCEEDING:this.transport.send(n)||this.onTransportError(),this.last_response=n;break}if(a>100&&a<=199&&this.state===de.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(function(){d.resend_provisional()},os.PROVISIONAL_RESPONSE_INTERVAL));else if(a>=200&&a<=299)switch(this.state){case de.STATUS_PROCEEDING:this.stateChanged(de.STATUS_ACCEPTED),this.last_response=n,this.L=setTimeout(function(){d.timer_L()},os.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case de.STATUS_ACCEPTED:this.transport.send(n)?r&&r():(this.onTransportError(),h&&h());break}else if(a>=300&&a<=699)switch(this.state){case de.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(n)?(this.stateChanged(de.STATUS_COMPLETED),this.H=setTimeout(function(){d.timer_H()},os.TIMER_H),r&&r()):(this.onTransportError(),h&&h());break}}},{key:"C",get:function(){return de}}]),s}(cl);function i_(c,t){var s=c._transactions,i;switch(t.method){case zi.INVITE:if(i=s.ist[t.via_branch],i){switch(i.state){case de.STATUS_PROCEEDING:i.transport.send(i.last_response);break;case de.STATUS_ACCEPTED:break}return!0}break;case zi.ACK:if(i=s.ist[t.via_branch],i){if(i.state===de.STATUS_ACCEPTED)return!1;if(i.state===de.STATUS_COMPLETED)return i.state=de.STATUS_CONFIRMED,i.I=setTimeout(function(){i.timer_I()},os.TIMER_I),!0}else return!1;break;case zi.CANCEL:return i=s.ist[t.via_branch],i?(t.reply_sl(200),i.state!==de.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(i=s.nist[t.via_branch],i){switch(i.state){case de.STATUS_TRYING:break;case de.STATUS_PROCEEDING:case de.STATUS_COMPLETED:i.transport.send(i.last_response);break}return!0}break}}var dl={C:de,NonInviteClientTransaction:e_,InviteClientTransaction:t_,AckClientTransaction:s_,NonInviteServerTransaction:n_,InviteServerTransaction:r_,checkTransaction:i_};function l_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function _c(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function o_(c,t,s){return t&&_c(c.prototype,t),s&&_c(c,s),c}var a_=ht,pc=ot,u_=Jh,va=dl,c_=new a_("RequestSender"),Sa={onRequestTimeout:function(){},onTransportError:function(){},onReceiveResponse:function(){},onAuthenticated:function(){}},hl=function(){function c(t,s,i){l_(this,c),this._ua=t,this._eventHandlers=i,this._method=s.method,this._request=s,this._auth=null,this._challenged=!1,this._staled=!1;for(var a in Sa)Object.prototype.hasOwnProperty.call(Sa,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Sa[a]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==pc.BYE||this._method!==pc.ACK)&&this._eventHandlers.onTransportError()}return o_(c,[{key:"send",value:function(){var s=this,i={onRequestTimeout:function(){s._eventHandlers.onRequestTimeout()},onTransportError:function(){s._eventHandlers.onTransportError()},onReceiveResponse:function(n){s._receiveResponse(n)}};switch(this._method){case"INVITE":this.clientTransaction=new va.InviteClientTransaction(this._ua,this._ua.transport,this._request,i);break;case"ACK":this.clientTransaction=new va.AckClientTransaction(this._ua,this._ua.transport,this._request,i);break;default:this.clientTransaction=new va.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,i)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}},{key:"_receiveResponse",value:function(s){var i,a,n=s.status_code;if((n===401||n===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(s.status_code===401?(i=s.parseHeader("www-authenticate"),a="authorization"):(i=s.parseHeader("proxy-authenticate"),a="proxy-authorization"),!i){c_.debug("".concat(s.status_code," with wrong or missing challenge, cannot authenticate")),this._eventHandlers.onReceiveResponse(s);return}if(!this._challenged||!this._staled&&i.stale===!0){if(this._auth||(this._auth=new u_({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,i)){this._eventHandlers.onReceiveResponse(s);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),i.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq","".concat(this._request.cseq," ").concat(this._method)),this._request.setHeader(a,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(s)}else this._eventHandlers.onReceiveResponse(s)}}]),c}();function f_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function mc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function d_(c,t,s){return t&&mc(c.prototype,t),s&&mc(c,s),c}var h_=ht,Ea=wt(),mn=ot,gc=ys,Tc=hl,Ni=new h_("Registrator"),Vl=10,__=function(){function c(t,s){f_(this,c),this._reg_id=1,this._ua=t,this._transport=s,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=Ea.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance='"<urn:uuid:'.concat(this._ua.configuration.instance_id,'>"'),this._contact+=";reg-id=".concat(this._reg_id),this._contact+=";+sip.instance=".concat(this._sipInstance)}return d_(c,[{key:"setExtraHeaders",value:function(s){Array.isArray(s)||(s=[]),this._extraHeaders=s.slice()}},{key:"setExtraContactParams",value:function(s){s instanceof Object||(s={}),this._extraContactParams="";for(var i in s)if(Object.prototype.hasOwnProperty.call(s,i)){var a=s[i];this._extraContactParams+=";".concat(i),a&&(this._extraContactParams+="=".concat(a))}}},{key:"register",value:function(){var s=this;if(this._registering){Ni.debug("Register request in progress...");return}var i=this._extraHeaders.slice();i.push("Contact: ".concat(this._contact,";expires=").concat(this._expires).concat(this._extraContactParams)),i.push("Expires: ".concat(this._expires));var a=new gc.OutgoingRequest(mn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},i),n=new Tc(this._ua,a,{onRequestTimeout:function(){s._registrationFailure(null,mn.causes.REQUEST_TIMEOUT)},onTransportError:function(){s._registrationFailure(null,mn.causes.CONNECTION_ERROR)},onAuthenticated:function(){s._cseq+=1},onReceiveResponse:function(h){if(h.cseq===s._cseq)switch(s._registrationTimer!==null&&(clearTimeout(s._registrationTimer),s._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(h.status_code):break;case/^2[0-9]{2}$/.test(h.status_code):{if(s._registering=!1,!h.hasHeader("Contact")){Ni.debug("no Contact header in response to REGISTER, response ignored");break}var d=h.headers.Contact.reduce(function(E,C){return E.concat(C.parsed)},[]),_=d.find(function(E){return s._sipInstance===E.getParam("+sip.instance")&&s._reg_id===parseInt(E.getParam("reg-id"))});if(_||(_=d.find(function(E){return E.uri.user===s._ua.contact.uri.user})),!_){Ni.debug("no Contact header pointing to us, response ignored");break}var g=_.getParam("expires");!g&&h.hasHeader("expires")&&(g=h.getHeader("expires")),g||(g=s._expires),g=Number(g),g<Vl&&(g=Vl);var T=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):g*1e3-5e3;s._registrationTimer=setTimeout(function(){s._registrationTimer=null,s._ua.listeners("registrationExpiring").length===0?s.register():s._ua.emit("registrationExpiring")},T),_.hasParam("temp-gruu")&&(s._ua.contact.temp_gruu=_.getParam("temp-gruu").replace(/"/g,"")),_.hasParam("pub-gruu")&&(s._ua.contact.pub_gruu=_.getParam("pub-gruu").replace(/"/g,"")),s._registered||(s._registered=!0,s._ua.registered({response:h}));break}case/^423$/.test(h.status_code):{h.hasHeader("min-expires")?(s._expires=Number(h.getHeader("min-expires")),s._expires<Vl&&(s._expires=Vl),s.register()):(Ni.debug("423 response received for REGISTER without Min-Expires"),s._registrationFailure(h,mn.causes.SIP_FAILURE_CODE));break}default:{var S=Ea.sipErrorCause(h.status_code);s._registrationFailure(h,S)}}}});this._registering=!0,n.send()}},{key:"unregister",value:function(){var s=this,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._registered){Ni.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);var a=this._extraHeaders.slice();i.all?a.push("Contact: *".concat(this._extraContactParams)):a.push("Contact: ".concat(this._contact,";expires=0").concat(this._extraContactParams)),a.push("Expires: 0");var n=new gc.OutgoingRequest(mn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},a),r=new Tc(this._ua,n,{onRequestTimeout:function(){s._unregistered(null,mn.causes.REQUEST_TIMEOUT)},onTransportError:function(){s._unregistered(null,mn.causes.CONNECTION_ERROR)},onAuthenticated:function(){s._cseq+=1},onReceiveResponse:function(d){switch(!0){case/^1[0-9]{2}$/.test(d.status_code):break;case/^2[0-9]{2}$/.test(d.status_code):s._unregistered(d);break;default:{var _=Ea.sipErrorCause(d.status_code);s._unregistered(d,_)}}}});r.send()}},{key:"close",value:function(){this._registered&&this.unregister()}},{key:"onTransportClosed",value:function(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}},{key:"_registrationFailure",value:function(s,i){this._registering=!1,this._ua.registrationFailed({response:s||null,cause:i}),this._registered&&(this._registered=!1,this._ua.unregistered({response:s||null,cause:i}))}},{key:"_unregistered",value:function(s,i){this._registering=!1,this._registered=!1,this._ua.unregistered({response:s||null,cause:i||null})}},{key:"registered",get:function(){return this._registered}}]),c}();function p_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function vc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function m_(c,t,s){return t&&vc(c.prototype,t),s&&vc(c,s),c}var ya=ot,jl=dl,g_=hl,Ca={onRequestTimeout:function(){},onTransportError:function(){},onSuccessResponse:function(){},onErrorResponse:function(){},onAuthenticated:function(){},onDialogError:function(){}},T_=function(){function c(t,s,i){p_(this,c),this._dialog=t,this._ua=t._ua,this._request=s,this._eventHandlers=i,this._reattempt=!1,this._reattemptTimer=null;for(var a in Ca)Object.prototype.hasOwnProperty.call(Ca,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Ca[a]))}return m_(c,[{key:"send",value:function(){var s=this,i=new g_(this._ua,this._request,{onRequestTimeout:function(){s._eventHandlers.onRequestTimeout()},onTransportError:function(){s._eventHandlers.onTransportError()},onAuthenticated:function(r){s._eventHandlers.onAuthenticated(r)},onReceiveResponse:function(r){s._receiveResponse(r)}});if(i.send(),(this._request.method===ya.INVITE||this._request.method===ya.UPDATE&&this._request.body)&&i.clientTransaction.state!==jl.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;var a=function n(){(i.clientTransaction.state===jl.C.STATUS_ACCEPTED||i.clientTransaction.state===jl.C.STATUS_COMPLETED||i.clientTransaction.state===jl.C.STATUS_TERMINATED)&&(i.clientTransaction.removeListener("stateChanged",n),s._dialog.uac_pending_reply=!1)};i.clientTransaction.on("stateChanged",a)}}},{key:"_receiveResponse",value:function(s){var i=this;s.status_code===408||s.status_code===481?this._eventHandlers.onDialogError(s):s.method===ya.INVITE&&s.status_code===491?this._reattempt?s.status_code>=200&&s.status_code<300?this._eventHandlers.onSuccessResponse(s):s.status_code>=300&&this._eventHandlers.onErrorResponse(s):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(function(){i._dialog.isTerminated()||(i._reattempt=!0,i.send())},1e3)):s.status_code>=200&&s.status_code<300?this._eventHandlers.onSuccessResponse(s):s.status_code>=300&&this._eventHandlers.onErrorResponse(s)}},{key:"request",get:function(){return this._request}}]),c}();function v_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Sc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function Ec(c,t,s){return t&&Sc(c.prototype,t),s&&Sc(c,s),c}var S_=ht,yc=ys,Ls=ot,xi=dl,E_=T_,Aa=wt(),Ra=new S_("Dialog"),$s={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3},y_=function(){Ec(c,null,[{key:"C",get:function(){return $s}}]);function c(t,s,i){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:$s.STATUS_CONFIRMED;if(v_(this,c),this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!s.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};s instanceof yc.IncomingResponse&&(a=s.status_code<200?$s.STATUS_EARLY:$s.STATUS_CONFIRMED);var n=s.parseHeader("contact");i==="UAS"?(this._id={call_id:s.call_id,local_tag:s.to_tag,remote_tag:s.from_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=s.cseq,this._local_uri=s.parseHeader("to").uri,this._remote_uri=s.parseHeader("from").uri,this._remote_target=n.uri,this._route_set=s.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):i==="UAC"&&(this._id={call_id:s.call_id,local_tag:s.from_tag,remote_tag:s.to_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=s.cseq,this._local_uri=s.parseHeader("from").uri,this._remote_uri=s.parseHeader("to").uri,this._remote_target=n.uri,this._route_set=s.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),Ra.debug("new ".concat(i," dialog created with status ").concat(this._state===$s.STATUS_EARLY?"EARLY":"CONFIRMED"))}return Ec(c,[{key:"isTerminated",value:function(){return this._status===$s.STATUS_TERMINATED}},{key:"update",value:function(s,i){this._state=$s.STATUS_CONFIRMED,Ra.debug("dialog ".concat(this._id.toString()," changed to CONFIRMED state")),i==="UAC"&&(this._route_set=s.getHeaders("record-route").reverse())}},{key:"terminate",value:function(){Ra.debug("dialog ".concat(this._id.toString()," deleted")),this._ua.destroyDialog(this),this._state=$s.STATUS_TERMINATED}},{key:"sendRequest",value:function(s){var i=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=Aa.cloneArray(a.extraHeaders),r=Aa.cloneObject(a.eventHandlers),h=a.body||null,d=this._createRequest(s,n,h);r.onAuthenticated=function(){i._local_seqnum+=1};var _=new E_(this,d,r);return _.send(),d}},{key:"receiveRequest",value:function(s){this._checkInDialogRequest(s)&&(s.method===Ls.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:s.method===Ls.INVITE&&(this._ack_seqnum=s.cseq),this._owner.receiveRequest(s))}},{key:"_createRequest",value:function(s,i,a){i=Aa.cloneArray(i),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));var n=s===Ls.CANCEL||s===Ls.ACK?this._local_seqnum:this._local_seqnum+=1,r=new yc.OutgoingRequest(s,this._remote_target,this._ua,{cseq:n,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},i,a);return r}},{key:"_checkInDialogRequest",value:function(s){var i=this;if(!this._remote_seqnum)this._remote_seqnum=s.cseq;else if(s.cseq<this._remote_seqnum)if(s.method===Ls.ACK){if(this._ack_seqnum===null||s.cseq!==this._ack_seqnum)return!1}else return s.reply(500),!1;else s.cseq>this._remote_seqnum&&(this._remote_seqnum=s.cseq);if(s.method===Ls.INVITE||s.method===Ls.UPDATE&&s.body){if(this._uac_pending_reply===!0)s.reply(491);else if(this._uas_pending_reply===!0){var a=(Math.random()*10|0)+1;return s.reply(500,null,["Retry-After:".concat(a)]),!1}else{this._uas_pending_reply=!0;var n=function r(){(s.server_transaction.state===xi.C.STATUS_ACCEPTED||s.server_transaction.state===xi.C.STATUS_COMPLETED||s.server_transaction.state===xi.C.STATUS_TERMINATED)&&(s.server_transaction.removeListener("stateChanged",r),i._uas_pending_reply=!1)};s.server_transaction.on("stateChanged",n)}s.hasHeader("contact")&&s.server_transaction.on("stateChanged",function(){s.server_transaction.state===xi.C.STATUS_ACCEPTED&&(i._remote_target=s.parseHeader("contact").uri)})}else s.method===Ls.NOTIFY&&s.hasHeader("contact")&&s.server_transaction.on("stateChanged",function(){s.server_transaction.state===xi.C.STATUS_COMPLETED&&(i._remote_target=s.parseHeader("contact").uri)});return!0}},{key:"id",get:function(){return this._id}},{key:"local_seqnum",get:function(){return this._local_seqnum},set:function(s){this._local_seqnum=s}},{key:"owner",get:function(){return this._owner}},{key:"uac_pending_reply",get:function(){return this._uac_pending_reply},set:function(s){this._uac_pending_reply=s}},{key:"uas_pending_reply",get:function(){return this._uas_pending_reply}}]),c}(),Lu={exports:{}};function Co(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Co=function(s){return typeof s}:Co=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},Co(c)}function C_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Cc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function A_(c,t,s){return t&&Cc(c.prototype,t),s&&Cc(c,s),c}function R_(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&mu(c,t)}function mu(c,t){return mu=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},mu(c,t)}function I_(c){var t=O_();return function(){var i=ko(c),a;if(t){var n=ko(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return b_(this,a)}}function b_(c,t){return t&&(Co(t)==="object"||typeof t=="function")?t:w_(c)}function w_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function O_(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function ko(c){return ko=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},ko(c)}var D_=dt.EventEmitter,N_=ht,x_=ot,U_=Ks,Ac=wt(),k_=new N_("RTCSession:DTMF"),hd={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};Lu.exports=function(c){R_(s,c);var t=I_(s);function s(i){var a;return C_(this,s),a=t.call(this),a._session=i,a._direction=null,a._tone=null,a._duration=null,a._request=null,a}return A_(s,[{key:"send",value:function(a){var n=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(a===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new U_.InvalidStateError(this._session.status);var h=Ac.cloneArray(r.extraHeaders);if(this.eventHandlers=Ac.cloneObject(r.eventHandlers),typeof a=="string")a=a.toUpperCase();else if(typeof a=="number")a=a.toString();else throw new TypeError("Invalid tone: ".concat(a));if(a.match(/^[0-9A-DR#*]$/))this._tone=a;else throw new TypeError("Invalid tone: ".concat(a));this._duration=r.duration,h.push("Content-Type: application/dtmf-relay");var d="Signal=".concat(this._tone,`\r
|
|
47
|
+
`);d+="Duration=".concat(this._duration),this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(x_.INFO,{extraHeaders:h,eventHandlers:{onSuccessResponse:function(g){n.emit("succeeded",{originator:"remote",response:g})},onErrorResponse:function(g){n.eventHandlers.onFailed&&n.eventHandlers.onFailed(),n.emit("failed",{originator:"remote",response:g})},onRequestTimeout:function(){n._session.onRequestTimeout()},onTransportError:function(){n._session.onTransportError()},onDialogError:function(){n._session.onDialogError()}},body:d})}},{key:"init_incoming",value:function(a){var n=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,r=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;if(this._direction="incoming",this._request=a,a.reply(200),a.body){var h=a.body.split(`
|
|
48
|
+
`);h.length>=1&&n.test(h[0])&&(this._tone=h[0].replace(n,"$2")),h.length>=2&&r.test(h[1])&&(this._duration=parseInt(h[1].replace(r,"$2"),10))}this._duration||(this._duration=hd.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:a}):k_.debug("invalid INFO DTMF received, discarded")}},{key:"tone",get:function(){return this._tone}},{key:"duration",get:function(){return this._duration}}]),s}(D_);Lu.exports.C=hd;var M_=Lu.exports;function Ao(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ao=function(s){return typeof s}:Ao=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},Ao(c)}function P_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Rc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function L_(c,t,s){return t&&Rc(c.prototype,t),s&&Rc(c,s),c}function $_(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&gu(c,t)}function gu(c,t){return gu=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},gu(c,t)}function H_(c){var t=j_();return function(){var i=Mo(c),a;if(t){var n=Mo(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return F_(this,a)}}function F_(c,t){return t&&(Ao(t)==="object"||typeof t=="function")?t:V_(c)}function V_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function j_(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Mo(c){return Mo=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},Mo(c)}var q_=dt.EventEmitter,B_=ot,G_=Ks,W_=wt(),K_=function(c){$_(s,c);var t=H_(s);function s(i){var a;return P_(this,s),a=t.call(this),a._session=i,a._direction=null,a._contentType=null,a._body=null,a}return L_(s,[{key:"send",value:function(a,n){var r=this,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this._direction="outgoing",a===void 0)throw new TypeError("Not enough arguments");if(this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new G_.InvalidStateError(this._session.status);this._contentType=a,this._body=n;var d=W_.cloneArray(h.extraHeaders);d.push("Content-Type: ".concat(a)),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(B_.INFO,{extraHeaders:d,eventHandlers:{onSuccessResponse:function(g){r.emit("succeeded",{originator:"remote",response:g})},onErrorResponse:function(g){r.emit("failed",{originator:"remote",response:g})},onTransportError:function(){r._session.onTransportError()},onRequestTimeout:function(){r._session.onRequestTimeout()},onDialogError:function(){r._session.onDialogError()}},body:n})}},{key:"init_incoming",value:function(a){this._direction="incoming",this.request=a,a.reply(200),this._contentType=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,this._body=a.body,this._session.newInfo({originator:"remote",info:this,request:a})}},{key:"contentType",get:function(){return this._contentType}},{key:"body",get:function(){return this._body}}]),s}(q_);function Y_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Ic(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function J_(c,t,s){return t&&Ic(c.prototype,t),s&&Ic(c,s),c}var z_=ht,bc=ot,Q_=new z_("RTCSession:ReferNotifier"),Ia={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300},X_=function(){function c(t,s,i){Y_(this,c),this._session=t,this._id=s,this._expires=i||Ia.expires,this._active=!0,this.notify(100)}return J_(c,[{key:"notify",value:function(s,i){if(Q_.debug("notify()"),this._active!==!1){i=i||bc.REASON_PHRASE[s]||"";var a;s>=200?a="terminated;reason=noresource":a="active;expires=".concat(this._expires),this._session.sendRequest(bc.NOTIFY,{extraHeaders:["Event: ".concat(Ia.event_type,";id=").concat(this._id),"Subscription-State: ".concat(a),"Content-Type: ".concat(Ia.body_type)],body:"SIP/2.0 ".concat(s," ").concat(i),eventHandlers:{onErrorResponse:function(){this._active=!1}}})}}}]),c}();function Ro(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ro=function(s){return typeof s}:Ro=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},Ro(c)}function Z_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function wc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function ep(c,t,s){return t&&wc(c.prototype,t),s&&wc(c,s),c}function tp(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&Tu(c,t)}function Tu(c,t){return Tu=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},Tu(c,t)}function sp(c){var t=ip();return function(){var i=Po(c),a;if(t){var n=Po(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return np(this,a)}}function np(c,t){return t&&(Ro(t)==="object"||typeof t=="function")?t:rp(c)}function rp(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function ip(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Po(c){return Po=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},Po(c)}var lp=dt.EventEmitter,op=ht,Ui=ot,ap=us(),Oc=wt(),gn=new op("RTCSession:ReferSubscriber"),up=function(c){tp(s,c);var t=sp(s);function s(i){var a;return Z_(this,s),a=t.call(this),a._id=null,a._session=i,a}return ep(s,[{key:"sendRefer",value:function(a){var n=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};gn.debug("sendRefer()");var h=Oc.cloneArray(r.extraHeaders),d=Oc.cloneObject(r.eventHandlers);for(var _ in d)Object.prototype.hasOwnProperty.call(d,_)&&this.on(_,d[_]);var g=null;r.replaces&&(g=r.replaces._request.call_id,g+=";to-tag=".concat(r.replaces._to_tag),g+=";from-tag=".concat(r.replaces._from_tag),g=encodeURIComponent(g));var T="Refer-To: <".concat(a).concat(g?"?Replaces=".concat(g):"",">");if(h.push(T),!h.some(function(C){return C.toLowerCase().startsWith("referred-by:")})){var S="Referred-By: <".concat(this._session._ua._configuration.uri._scheme,":").concat(this._session._ua._configuration.uri._user,"@").concat(this._session._ua._configuration.uri._host,">");h.push(S)}h.push("Contact: ".concat(this._session.contact));var E=this._session.sendRequest(Ui.REFER,{extraHeaders:h,eventHandlers:{onSuccessResponse:function(A){n._requestSucceeded(A)},onErrorResponse:function(A){n._requestFailed(A,Ui.causes.REJECTED)},onTransportError:function(){n._requestFailed(null,Ui.causes.CONNECTION_ERROR)},onRequestTimeout:function(){n._requestFailed(null,Ui.causes.REQUEST_TIMEOUT)},onDialogError:function(){n._requestFailed(null,Ui.causes.DIALOG_ERROR)}}});this._id=E.cseq}},{key:"receiveNotify",value:function(a){if(gn.debug("receiveNotify()"),!!a.body){var n=ap.parse(a.body.trim().split(`\r
|
|
49
|
+
`,1)[0],"Status_Line");if(n===-1){gn.debug('receiveNotify() | error parsing NOTIFY body: "'.concat(a.body,'"'));return}switch(!0){case/^100$/.test(n.status_code):this.emit("trying",{request:a,status_line:n});break;case/^1[0-9]{2}$/.test(n.status_code):this.emit("progress",{request:a,status_line:n});break;case/^2[0-9]{2}$/.test(n.status_code):this.emit("accepted",{request:a,status_line:n});break;default:this.emit("failed",{request:a,status_line:n});break}}}},{key:"_requestSucceeded",value:function(a){gn.debug("REFER succeeded"),gn.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:a})}},{key:"_requestFailed",value:function(a,n){gn.debug("REFER failed"),gn.debug('emit "requestFailed"'),this.emit("requestFailed",{response:a||null,cause:n})}},{key:"id",get:function(){return this._id}}]),s}(lp);function Io(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Io=function(s){return typeof s}:Io=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},Io(c)}function ps(c,t){var s;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(s=cp(c))||t&&c&&typeof c.length=="number"){s&&(c=s);var i=0,a=function(){};return{s:a,n:function(){return i>=c.length?{done:!0}:{done:!1,value:c[i++]}},e:function(_){throw _},f:a}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
50
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var n=!0,r=!1,h;return{s:function(){s=c[Symbol.iterator]()},n:function(){var _=s.next();return n=_.done,_},e:function(_){r=!0,h=_},f:function(){try{!n&&s.return!=null&&s.return()}finally{if(r)throw h}}}}function cp(c,t){if(c){if(typeof c=="string")return Dc(c,t);var s=Object.prototype.toString.call(c).slice(8,-1);if(s==="Object"&&c.constructor&&(s=c.constructor.name),s==="Map"||s==="Set")return Array.from(c);if(s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s))return Dc(c,t)}}function Dc(c,t){(t==null||t>c.length)&&(t=c.length);for(var s=0,i=new Array(t);s<t;s++)i[s]=c[s];return i}function fp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Nc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function xc(c,t,s){return t&&Nc(c.prototype,t),s&&Nc(c,s),c}function dp(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&vu(c,t)}function vu(c,t){return vu=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},vu(c,t)}function hp(c){var t=mp();return function(){var i=Lo(c),a;if(t){var n=Lo(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return _p(this,a)}}function _p(c,t){return t&&(Io(t)==="object"||typeof t=="function")?t:pp(c)}function pp(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function mp(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Lo(c){return Lo=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},Lo(c)}var gp=dt.EventEmitter,Uc=Mt,Tp=ht,ce=ot,Tn=Ks,kc=dl,Ge=wt(),ki=dd,vp=ys,ql=y_,Sp=hl,Pt=M_,Mc=K_,Ep=X_,yp=up,Pc=Ys(),J=new Tp("RTCSession"),ee={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},Bl=["audio","video"],Cp=function(c){dp(s,c);var t=hp(s);xc(s,null,[{key:"C",get:function(){return ee}}]);function s(i){var a;return fp(this,s),J.debug("new"),a=t.call(this),a._id=null,a._ua=i,a._status=ee.STATUS_NULL,a._dialog=null,a._earlyDialogs={},a._contact=null,a._from_tag=null,a._to_tag=null,a._connection=null,a._connectionPromiseQueue=Promise.resolve(),a._request=null,a._is_canceled=!1,a._cancel_reason="",a._is_confirmed=!1,a._late_sdp=!1,a._rtcOfferConstraints=null,a._rtcAnswerConstraints=null,a._localMediaStream=null,a._localMediaStreamLocallyGenerated=!1,a._rtcReady=!0,a._iceReady=!1,a._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},a._direction=null,a._local_identity=null,a._remote_identity=null,a._start_time=null,a._end_time=null,a._tones=null,a._audioMuted=!1,a._videoMuted=!1,a._localHold=!1,a._remoteHold=!1,a._sessionTimers={enabled:a._ua.configuration.session_timers,refreshMethod:a._ua.configuration.session_timers_refresh_method,defaultExpires:ce.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},a._referSubscribers={},a._data={},a}return xc(s,[{key:"isInProgress",value:function(){switch(this._status){case ee.STATUS_NULL:case ee.STATUS_INVITE_SENT:case ee.STATUS_1XX_RECEIVED:case ee.STATUS_INVITE_RECEIVED:case ee.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}},{key:"isEstablished",value:function(){switch(this._status){case ee.STATUS_ANSWERED:case ee.STATUS_WAITING_FOR_ACK:case ee.STATUS_CONFIRMED:return!0;default:return!1}}},{key:"isEnded",value:function(){switch(this._status){case ee.STATUS_CANCELED:case ee.STATUS_TERMINATED:return!0;default:return!1}}},{key:"isMuted",value:function(){return{audio:this._audioMuted,video:this._videoMuted}}},{key:"isOnHold",value:function(){return{local:this._localHold,remote:this._remoteHold}}},{key:"connect",value:function(a){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;J.debug("connect()");var h=a,d=Ge.cloneObject(n.eventHandlers),_=Ge.cloneArray(n.extraHeaders),g=Ge.cloneObject(n.mediaConstraints,{audio:!0,video:!0}),T=n.mediaStream||null,S=Ge.cloneObject(n.pcConfig,{iceServers:[]}),E=n.rtcConstraints||null,C=n.rtcOfferConstraints||null;if(this._rtcOfferConstraints=C,this._rtcAnswerConstraints=n.rtcAnswerConstraints||null,this._data=n.data||this._data,a===void 0)throw new TypeError("Not enough arguments");if(this._status!==ee.STATUS_NULL)throw new Tn.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Tn.NotSupportedError("WebRTC not supported");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(h));this._sessionTimers.enabled&&Ge.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=ce.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=ce.SESSION_EXPIRES);for(var A in d)Object.prototype.hasOwnProperty.call(d,A)&&this.on(A,d[A]);this._from_tag=Ge.newTag();var R=n.anonymous||!1,F={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:R,outbound:!0}),R?(F.from_display_name="Anonymous",F.from_uri=new Pc("sip","anonymous","anonymous.invalid"),_.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),_.push("Privacy: id")):n.fromUserName&&(F.from_uri=new Pc("sip",n.fromUserName,this._ua.configuration.uri.host),_.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),n.fromDisplayName&&(F.from_display_name=n.fromDisplayName),_.push("Contact: ".concat(this._contact)),_.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&_.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new vp.InitialOutgoingInviteRequest(a,this._ua,F,_),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(S,E),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,r&&r(this),this._newRTCSession("local",this._request),this._sendInitialRequest(g,C,T)}},{key:"init_incoming",value:function(a,n){var r=this;J.debug("init_incoming()");var h,d=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;if(a.body&&d!=="application/sdp"){a.reply(415);return}if(this._status=ee.STATUS_INVITE_RECEIVED,this._from_tag=a.from_tag,this._id=a.call_id+this._from_tag,this._request=a,this._contact=this._ua.contact.toString(),a.hasHeader("expires")&&(h=a.getHeader("expires")*1e3),a.to_tag=Ge.newTag(),!this._createDialog(a,"UAS",!0)){a.reply(500,"Missing Contact header field");return}a.body?this._late_sdp=!1:this._late_sdp=!0,this._status=ee.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(function(){a.reply(408),r._failed("local",null,ce.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),h&&(this._timers.expiresTimer=setTimeout(function(){r._status===ee.STATUS_WAITING_FOR_ANSWER&&(a.reply(487),r._failed("system",null,ce.causes.EXPIRES))},h)),this._direction="incoming",this._local_identity=a.to,this._remote_identity=a.from,n&&n(this),this._newRTCSession("remote",a),this._status!==ee.STATUS_TERMINATED&&(a.reply(180,null,["Contact: ".concat(this._contact)]),this._progress("local",null))}},{key:"answer",value:function(){var a=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};J.debug("answer()");var r=this._request,h=Ge.cloneArray(n.extraHeaders),d=Ge.cloneObject(n.mediaConstraints),_=n.mediaStream||null,g=Ge.cloneObject(n.pcConfig,{iceServers:[]}),T=n.rtcConstraints||null,S=n.rtcAnswerConstraints||null,E=Ge.cloneObject(n.rtcOfferConstraints),C,A=!1,R=!1,F=!1,I=!1;if(this._rtcAnswerConstraints=S,this._rtcOfferConstraints=n.rtcOfferConstraints||null,this._data=n.data||this._data,this._direction!=="incoming")throw new Tn.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==ee.STATUS_WAITING_FOR_ANSWER)throw new Tn.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Ge.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=ce.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=ce.SESSION_EXPIRES),this._status=ee.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),h.unshift("Contact: ".concat(this._contact));var ie=r.parseSDP();Array.isArray(ie.media)||(ie.media=[ie.media]);var N=ps(ie.media),$;try{for(N.s();!($=N.n()).done;){var ve=$.value;ve.type==="audio"&&(A=!0,(!ve.direction||ve.direction==="sendrecv")&&(F=!0)),ve.type==="video"&&(R=!0,(!ve.direction||ve.direction==="sendrecv")&&(I=!0))}}catch(V){N.e(V)}finally{N.f()}if(_&&d.audio===!1){C=_.getAudioTracks();var _e=ps(C),U;try{for(_e.s();!(U=_e.n()).done;){var x=U.value;_.removeTrack(x)}}catch(V){_e.e(V)}finally{_e.f()}}if(_&&d.video===!1){C=_.getVideoTracks();var q=ps(C),j;try{for(q.s();!(j=q.n()).done;){var Y=j.value;_.removeTrack(Y)}}catch(V){q.e(V)}finally{q.f()}}!_&&d.audio===void 0&&(d.audio=F),!_&&d.video===void 0&&(d.video=I),!_&&!A&&!E.offerToReceiveAudio&&(d.audio=!1),!_&&!R&&!E.offerToReceiveVideo&&(d.video=!1),this._createRTCConnection(g,T),Promise.resolve().then(function(){if(_)return _;if(d.audio||d.video)return a._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(d).catch(function(V){throw a._status===ee.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),a._failed("local",null,ce.causes.USER_DENIED_MEDIA_ACCESS),J.warn('emit "getusermediafailed" [error:%o]',V),a.emit("getusermediafailed",V),new Error("getUserMedia() failed"))})}).then(function(V){if(a._status===ee.STATUS_TERMINATED)throw new Error("terminated");a._localMediaStream=V,V&&V.getTracks().forEach(function(Q){a._connection.addTrack(Q,V)})}).then(function(){if(!a._late_sdp){var V={originator:"remote",type:"offer",sdp:r.body};J.debug('emit "sdp"'),a.emit("sdp",V);var Q=new RTCSessionDescription({type:"offer",sdp:V.sdp});return a._connectionPromiseQueue=a._connectionPromiseQueue.then(function(){return a._connection.setRemoteDescription(Q)}).catch(function(k){throw r.reply(488),a._failed("system",null,ce.causes.WEBRTC_ERROR),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',k),a.emit("peerconnection:setremotedescriptionfailed",k),new Error("peerconnection.setRemoteDescription() failed")}),a._connectionPromiseQueue}}).then(function(){if(a._status===ee.STATUS_TERMINATED)throw new Error("terminated");return a._connecting(r),a._late_sdp?a._createLocalDescription("offer",a._rtcOfferConstraints).catch(function(){throw r.reply(500),new Error("_createLocalDescription() failed")}):a._createLocalDescription("answer",S).catch(function(){throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(function(V){if(a._status===ee.STATUS_TERMINATED)throw new Error("terminated");a._handleSessionTimersInIncomingRequest(r,h),r.reply(200,null,h,V,function(){a._status=ee.STATUS_WAITING_FOR_ACK,a._setInvite2xxTimer(r,V),a._setACKTimer(),a._accepted("local")},function(){a._failed("system",null,ce.causes.CONNECTION_ERROR)})}).catch(function(V){a._status!==ee.STATUS_TERMINATED&&J.warn(V)})}},{key:"terminate",value:function(){var a=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};J.debug("terminate()");var r=n.cause||ce.causes.BYE,h=Ge.cloneArray(n.extraHeaders),d=n.body,_,g=n.status_code,T=n.reason_phrase;if(this._status===ee.STATUS_TERMINATED)throw new Tn.InvalidStateError(this._status);switch(this._status){case ee.STATUS_NULL:case ee.STATUS_INVITE_SENT:case ee.STATUS_1XX_RECEIVED:if(J.debug("canceling session"),g&&(g<200||g>=700))throw new TypeError("Invalid status_code: ".concat(g));g&&(T=T||ce.REASON_PHRASE[g]||"",_="SIP ;cause=".concat(g,' ;text="').concat(T,'"')),this._status===ee.STATUS_NULL||this._status===ee.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=_):this._status===ee.STATUS_1XX_RECEIVED&&this._request.cancel(_),this._status=ee.STATUS_CANCELED,this._failed("local",null,ce.causes.CANCELED);break;case ee.STATUS_WAITING_FOR_ANSWER:case ee.STATUS_ANSWERED:if(J.debug("rejecting session"),g=g||480,g<300||g>=700)throw new TypeError("Invalid status_code: ".concat(g));this._request.reply(g,T,h,d),this._failed("local",null,ce.causes.REJECTED);break;case ee.STATUS_WAITING_FOR_ACK:case ee.STATUS_CONFIRMED:if(J.debug("terminating session"),T=n.reason_phrase||ce.REASON_PHRASE[g]||"",g&&(g<200||g>=700))throw new TypeError("Invalid status_code: ".concat(g));if(g&&h.push("Reason: SIP ;cause=".concat(g,'; text="').concat(T,'"')),this._status===ee.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==kc.C.STATUS_TERMINATED){var S=this._dialog;this.receiveRequest=function(E){var C=E.method;C===ce.ACK&&(a.sendRequest(ce.BYE,{extraHeaders:h,body:d}),S.terminate())},this._request.server_transaction.on("stateChanged",function(){a._request.server_transaction.state===kc.C.STATUS_TERMINATED&&(a.sendRequest(ce.BYE,{extraHeaders:h,body:d}),S.terminate())}),this._ended("local",null,r),this._dialog=S,this._ua.newDialog(S)}else this.sendRequest(ce.BYE,{extraHeaders:h,body:d}),this._ended("local",null,r)}}},{key:"sendDTMF",value:function(a){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};J.debug("sendDTMF() | tones: %s",a);var r=0,h=n.duration||null,d=n.interToneGap||null,_=n.transportType||ce.DTMF_TRANSPORT.INFO;if(a===void 0)throw new TypeError("Not enough arguments");if(this._status!==ee.STATUS_CONFIRMED&&this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_1XX_RECEIVED)throw new Tn.InvalidStateError(this._status);if(_!==ce.DTMF_TRANSPORT.INFO&&_!==ce.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(_));if(typeof a=="number"&&(a=a.toString()),!a||typeof a!="string"||!a.match(/^[0-9A-DR#*,]+$/i))throw new TypeError("Invalid tones: ".concat(a));if(h&&!Ge.isDecimal(h))throw new TypeError("Invalid tone duration: ".concat(h));if(h?h<Pt.C.MIN_DURATION?(J.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(Pt.C.MIN_DURATION," milliseconds")),h=Pt.C.MIN_DURATION):h>Pt.C.MAX_DURATION?(J.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(Pt.C.MAX_DURATION," milliseconds")),h=Pt.C.MAX_DURATION):h=Math.abs(h):h=Pt.C.DEFAULT_DURATION,n.duration=h,d&&!Ge.isDecimal(d))throw new TypeError("Invalid interToneGap: ".concat(d));if(d?d<Pt.C.MIN_INTER_TONE_GAP?(J.debug('"interToneGap" value is lower than the minimum allowed, setting it to '.concat(Pt.C.MIN_INTER_TONE_GAP," milliseconds")),d=Pt.C.MIN_INTER_TONE_GAP):d=Math.abs(d):d=Pt.C.DEFAULT_INTER_TONE_GAP,_===ce.DTMF_TRANSPORT.RFC2833){var g=this._getDTMFRTPSender();g&&(a=g.toneBuffer+a,g.insertDTMF(a,h,d));return}if(this._tones){this._tones+=a;return}this._tones=a,T.call(this);function T(){var S=this,E;if(this._status===ee.STATUS_TERMINATED||!this._tones||r>=this._tones.length){this._tones=null;return}var C=this._tones[r];if(r+=1,C===",")E=2e3;else{var A=new Pt(this);n.eventHandlers={onFailed:function(){S._tones=null}},A.send(C,n),E=h+d}setTimeout(T.bind(this),E)}}},{key:"sendInfo",value:function(a,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(J.debug("sendInfo()"),this._status!==ee.STATUS_CONFIRMED&&this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_1XX_RECEIVED)throw new Tn.InvalidStateError(this._status);var h=new Mc(this);h.send(a,n,r)}},{key:"mute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};J.debug("mute()");var n=!1,r=!1;this._audioMuted===!1&&a.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&a.video&&(r=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||r===!0)&&this._onmute({audio:n,video:r})}},{key:"unmute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!0};J.debug("unmute()");var n=!1,r=!1;this._audioMuted===!0&&a.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&a.video&&(r=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||r===!0)&&this._onunmute({audio:n,video:r})}},{key:"hold",value:function(){var a=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;if(J.debug("hold()"),this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");var h={succeeded:function(){r&&r()},failed:function(){a.terminate({cause:ce.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:h,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:h,extraHeaders:n.extraHeaders}),!0}},{key:"unhold",value:function(){var a=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;if(J.debug("unhold()"),this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");var h={succeeded:function(){r&&r()},failed:function(){a.terminate({cause:ce.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:h,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:h,extraHeaders:n.extraHeaders}),!0}},{key:"renegotiate",value:function(){var a=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;J.debug("renegotiate()");var h=n.rtcOfferConstraints||null;if(this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;var d={succeeded:function(){r&&r()},failed:function(){a.terminate({cause:ce.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:d,rtcOfferConstraints:h,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:d,rtcOfferConstraints:h,extraHeaders:n.extraHeaders}),!0}},{key:"refer",value:function(a,n){var r=this;J.debug("refer()");var h=a;if(this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED)return!1;if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(h));var d=new yp(this);d.sendRefer(a,n);var _=d.id;return this._referSubscribers[_]=d,d.on("requestFailed",function(){delete r._referSubscribers[_]}),d.on("accepted",function(){delete r._referSubscribers[_]}),d.on("failed",function(){delete r._referSubscribers[_]}),d}},{key:"sendRequest",value:function(a,n){return J.debug("sendRequest()"),this._dialog.sendRequest(a,n)}},{key:"receiveRequest",value:function(a){var n=this;if(J.debug("receiveRequest()"),a.method===ce.CANCEL)(this._status===ee.STATUS_WAITING_FOR_ANSWER||this._status===ee.STATUS_ANSWERED)&&(this._status=ee.STATUS_CANCELED,this._request.reply(487),this._failed("remote",a,ce.causes.CANCELED));else switch(a.method){case ce.ACK:if(this._status!==ee.STATUS_WAITING_FOR_ACK)return;if(this._status=ee.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!a.body){this.terminate({cause:ce.causes.MISSING_SDP,status_code:400});break}var r={originator:"remote",type:"answer",sdp:a.body};J.debug('emit "sdp"'),this.emit("sdp",r);var h=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return n._connection.setRemoteDescription(h)}).then(function(){n._is_confirmed||n._confirmed("remote",a)}).catch(function(_){n.terminate({cause:ce.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',_),n.emit("peerconnection:setremotedescriptionfailed",_)})}else this._is_confirmed||this._confirmed("remote",a);break;case ce.BYE:this._status===ee.STATUS_CONFIRMED||this._status===ee.STATUS_WAITING_FOR_ACK?(a.reply(200),this._ended("remote",a,ce.causes.BYE)):this._status===ee.STATUS_INVITE_RECEIVED||this._status===ee.STATUS_WAITING_FOR_ANSWER?(a.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",a,ce.causes.BYE)):a.reply(403,"Wrong Status");break;case ce.INVITE:this._status===ee.STATUS_CONFIRMED?a.hasHeader("replaces")?this._receiveReplaces(a):this._receiveReinvite(a):a.reply(403,"Wrong Status");break;case ce.INFO:if(this._status===ee.STATUS_1XX_RECEIVED||this._status===ee.STATUS_WAITING_FOR_ANSWER||this._status===ee.STATUS_ANSWERED||this._status===ee.STATUS_WAITING_FOR_ACK||this._status===ee.STATUS_CONFIRMED){var d=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;d&&d.match(/^application\/dtmf-relay/i)?new Pt(this).init_incoming(a):d!==void 0?new Mc(this).init_incoming(a):a.reply(415)}else a.reply(403,"Wrong Status");break;case ce.UPDATE:this._status===ee.STATUS_CONFIRMED?this._receiveUpdate(a):a.reply(403,"Wrong Status");break;case ce.REFER:this._status===ee.STATUS_CONFIRMED?this._receiveRefer(a):a.reply(403,"Wrong Status");break;case ce.NOTIFY:this._status===ee.STATUS_CONFIRMED?this._receiveNotify(a):a.reply(403,"Wrong Status");break;default:a.reply(501)}}},{key:"onTransportError",value:function(){J.warn("onTransportError()"),this._status!==ee.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ce.causes.CONNECTION_ERROR,cause:ce.causes.CONNECTION_ERROR})}},{key:"onRequestTimeout",value:function(){J.warn("onRequestTimeout()"),this._status!==ee.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:ce.causes.REQUEST_TIMEOUT,cause:ce.causes.REQUEST_TIMEOUT})}},{key:"onDialogError",value:function(){J.warn("onDialogError()"),this._status!==ee.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:ce.causes.DIALOG_ERROR,cause:ce.causes.DIALOG_ERROR})}},{key:"newDTMF",value:function(a){J.debug("newDTMF()"),this.emit("newDTMF",a)}},{key:"newInfo",value:function(a){J.debug("newInfo()"),this.emit("newInfo",a)}},{key:"_isReadyToReOffer",value:function(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(J.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(J.debug("_isReadyToReOffer() | session not established yet"),!1):(J.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(J.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(J.debug("close() | closing local MediaStream"),Ge.closeMediaStream(this._localMediaStream)),this._status!==ee.STATUS_TERMINATED){if(this._status=ee.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(h){J.warn("close() | error closing the RTCPeerConnection: %o",h)}for(var a in this._timers)Object.prototype.hasOwnProperty.call(this._timers,a)&&clearTimeout(this._timers[a]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(var n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(var r in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,r)&&delete this._referSubscribers[r];this._ua.destroyRTCSession(this)}}},{key:"_setInvite2xxTimer",value:function(a,n){var r=ki.T1;function h(){this._status===ee.STATUS_WAITING_FOR_ACK&&(a.reply(200,null,["Contact: ".concat(this._contact)],n),r<ki.T2&&(r=r*2,r>ki.T2&&(r=ki.T2)),this._timers.invite2xxTimer=setTimeout(h.bind(this),r))}this._timers.invite2xxTimer=setTimeout(h.bind(this),r)}},{key:"_setACKTimer",value:function(){var a=this;this._timers.ackTimer=setTimeout(function(){a._status===ee.STATUS_WAITING_FOR_ACK&&(J.debug("no ACK received, terminating the session"),clearTimeout(a._timers.invite2xxTimer),a.sendRequest(ce.BYE),a._ended("remote",null,ce.causes.NO_ACK))},ki.TIMER_H)}},{key:"_createRTCConnection",value:function(a,n){var r=this;this._connection=new RTCPeerConnection(a,n),this._connection.addEventListener("iceconnectionstatechange",function(){var h=r._connection.iceConnectionState;h==="failed"&&r.terminate({cause:ce.causes.RTP_TIMEOUT,status_code:408,reason_phrase:ce.causes.RTP_TIMEOUT})}),J.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(a,n){var r=this;if(J.debug("createLocalDescription()"),a!=="offer"&&a!=="answer")throw new Error('createLocalDescription() | invalid type "'.concat(a,'"'));var h=this._connection;return this._rtcReady=!1,Promise.resolve().then(function(){return a==="offer"?h.createOffer(n).catch(function(d){return J.warn('emit "peerconnection:createofferfailed" [error:%o]',d),r.emit("peerconnection:createofferfailed",d),Promise.reject(d)}):h.createAnswer(n).catch(function(d){return J.warn('emit "peerconnection:createanswerfailed" [error:%o]',d),r.emit("peerconnection:createanswerfailed",d),Promise.reject(d)})}).then(function(d){return h.setLocalDescription(d).catch(function(_){return r._rtcReady=!0,J.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',_),r.emit("peerconnection:setlocaldescriptionfailed",_),Promise.reject(_)})}).then(function(){var d=n&&n.iceRestart;if(h.iceGatheringState==="complete"&&!d||h.iceGatheringState==="gathering"&&r._iceReady){r._rtcReady=!0;var _={originator:"local",type:a,sdp:h.localDescription.sdp};return J.debug('emit "sdp"'),r.emit("sdp",_),Promise.resolve(_.sdp)}return new Promise(function(g){var T=!1,S,E;r._iceReady=!1;var C=function(){h.removeEventListener("icecandidate",S),h.removeEventListener("icegatheringstatechange",E),T=!0,r._rtcReady=!0,r._iceReady=!0;var R={originator:"local",type:a,sdp:h.localDescription.sdp};J.debug('emit "sdp"'),r.emit("sdp",R),g(R.sdp)};h.addEventListener("icecandidate",S=function(R){var F=R.candidate;F?r.emit("icecandidate",{candidate:F,ready:C}):T||C()}),h.addEventListener("icegatheringstatechange",E=function(){h.iceGatheringState==="complete"&&!T&&C()})})})}},{key:"_createDialog",value:function(a,n,r){var h=n==="UAS"?a.to_tag:a.from_tag,d=n==="UAS"?a.from_tag:a.to_tag,_=a.call_id+h+d,g=this._earlyDialogs[_];if(r)return g?!0:(g=new ql(this,a,n,ql.C.STATUS_EARLY),g.error?(J.debug(g.error),this._failed("remote",a,ce.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[_]=g,!0));if(this._from_tag=a.from_tag,this._to_tag=a.to_tag,g)return g.update(a,n),this._dialog=g,delete this._earlyDialogs[_],!0;var T=new ql(this,a,n);return T.error?(J.debug(T.error),this._failed("remote",a,ce.causes.INTERNAL_ERROR),!1):(this._dialog=T,!0)}},{key:"_receiveReinvite",value:function(a){var n=this;J.debug("receiveReinvite()");var r=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,h={request:a,callback:void 0,reject:_.bind(this)},d=!1;function _(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};d=!0;var S=T.status_code||403,E=T.reason_phrase||"",C=Ge.cloneArray(T.extraHeaders);if(this._status!==ee.STATUS_CONFIRMED)return!1;if(S<300||S>=700)throw new TypeError("Invalid status_code: ".concat(S));a.reply(S,E,C)}if(this.emit("reinvite",h),d)return;if(this._late_sdp=!1,!a.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return n._createLocalDescription("offer",n._rtcOfferConstraints)}).then(function(T){g.call(n,T)}).catch(function(){a.reply(500)});return}if(r!=="application/sdp"){J.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(T){n._status!==ee.STATUS_TERMINATED&&g.call(n,T)}).catch(function(T){J.warn(T)});function g(T){var S=this,E=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,E),this._late_sdp&&(T=this._mangleOffer(T)),a.reply(200,null,E,T,function(){S._status=ee.STATUS_WAITING_FOR_ACK,S._setInvite2xxTimer(a,T),S._setACKTimer()}),typeof h.callback=="function"&&h.callback()}}},{key:"_receiveUpdate",value:function(a){var n=this;J.debug("receiveUpdate()");var r=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,h={request:a,callback:void 0,reject:_.bind(this)},d=!1;function _(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};d=!0;var S=T.status_code||403,E=T.reason_phrase||"",C=Ge.cloneArray(T.extraHeaders);if(this._status!==ee.STATUS_CONFIRMED)return!1;if(S<300||S>=700)throw new TypeError("Invalid status_code: ".concat(S));a.reply(S,E,C)}if(this.emit("update",h),d)return;if(!a.body){g.call(this,null);return}if(r!=="application/sdp"){J.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(T){n._status!==ee.STATUS_TERMINATED&&g.call(n,T)}).catch(function(T){J.warn(T)});function g(T){var S=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,S),a.reply(200,null,S,T),typeof h.callback=="function"&&h.callback()}}},{key:"_processInDialogSdpOffer",value:function(a){var n=this;J.debug("_processInDialogSdpOffer()");var r=a.parseSDP(),h=!1,d=ps(r.media),_;try{for(d.s();!(_=d.n()).done;){var g=_.value;if(Bl.indexOf(g.type)!==-1){var T=g.direction||r.direction||"sendrecv";if(T==="sendonly"||T==="inactive")h=!0;else{h=!1;break}}}}catch(C){d.e(C)}finally{d.f()}var S={originator:"remote",type:"offer",sdp:a.body};J.debug('emit "sdp"'),this.emit("sdp",S);var E=new RTCSessionDescription({type:"offer",sdp:S.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(n._status===ee.STATUS_TERMINATED)throw new Error("terminated");return n._connection.setRemoteDescription(E).catch(function(C){throw a.reply(488),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',C),n.emit("peerconnection:setremotedescriptionfailed",C),C})}).then(function(){if(n._status===ee.STATUS_TERMINATED)throw new Error("terminated");n._remoteHold===!0&&h===!1?(n._remoteHold=!1,n._onunhold("remote")):n._remoteHold===!1&&h===!0&&(n._remoteHold=!0,n._onhold("remote"))}).then(function(){if(n._status===ee.STATUS_TERMINATED)throw new Error("terminated");return n._createLocalDescription("answer",n._rtcAnswerConstraints).catch(function(C){throw a.reply(500),J.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',C),C})}).catch(function(C){J.warn("_processInDialogSdpOffer() failed [error: %o]",C)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(a){var n=this;if(J.debug("receiveRefer()"),!a.refer_to){J.debug("no Refer-To header field present in REFER"),a.reply(400);return}if(a.refer_to.uri.scheme!==ce.SIP){J.debug("Refer-To header field points to a non-SIP URI scheme"),a.reply(416);return}a.reply(202);var r=new Ep(this,a.cseq);J.debug('emit "refer"'),this.emit("refer",{request:a,accept:function(g,T){h.call(n,g,T)},reject:function(){d.call(n)}});function h(_){var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(_=typeof _=="function"?_:null,this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED)return!1;var T=new s(this._ua);if(T.on("progress",function(E){var C=E.response;r.notify(C.status_code,C.reason_phrase)}),T.on("accepted",function(E){var C=E.response;r.notify(C.status_code,C.reason_phrase)}),T.on("_failed",function(E){var C=E.message,A=E.cause;C?r.notify(C.status_code,C.reason_phrase):r.notify(487,A)}),a.refer_to.uri.hasHeader("replaces")){var S=decodeURIComponent(a.refer_to.uri.getHeader("replaces"));g.extraHeaders=Ge.cloneArray(g.extraHeaders),g.extraHeaders.push("Replaces: ".concat(S))}T.connect(a.refer_to.uri.toAor(),g,_)}function d(){r.notify(603)}}},{key:"_receiveNotify",value:function(a){switch(J.debug("receiveNotify()"),a.event||a.reply(400),a.event.event){case"refer":{var n,r;if(a.event.params&&a.event.params.id)n=a.event.params.id,r=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)r=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{a.reply(400,"Missing event id parameter");return}if(!r){a.reply(481,"Subscription does not exist");return}r.receiveNotify(a),a.reply(200);break}default:a.reply(489)}}},{key:"_receiveReplaces",value:function(a){var n=this;J.debug("receiveReplaces()");function r(d){var _=this;if(this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED)return!1;var g=new s(this._ua);g.on("confirmed",function(){_.terminate()}),g.init_incoming(a,d)}function h(){J.debug("Replaced INVITE rejected by the user"),a.reply(486)}this.emit("replaces",{request:a,accept:function(_){r.call(n,_)},reject:function(){h.call(n)}})}},{key:"_sendInitialRequest",value:function(a,n,r){var h=this,d=new Sp(this._ua,this._request,{onRequestTimeout:function(){h.onRequestTimeout()},onTransportError:function(){h.onTransportError()},onAuthenticated:function(g){h._request=g},onReceiveResponse:function(g){h._receiveInviteResponse(g)}});Promise.resolve().then(function(){if(r)return r;if(a.audio||a.video)return h._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(function(_){throw h._status===ee.STATUS_TERMINATED?new Error("terminated"):(h._failed("local",null,ce.causes.USER_DENIED_MEDIA_ACCESS),J.warn('emit "getusermediafailed" [error:%o]',_),h.emit("getusermediafailed",_),_)})}).then(function(_){if(h._status===ee.STATUS_TERMINATED)throw new Error("terminated");return h._localMediaStream=_,_&&_.getTracks().forEach(function(g){h._connection.addTrack(g,_)}),h._connecting(h._request),h._createLocalDescription("offer",n).catch(function(g){throw h._failed("local",null,ce.causes.WEBRTC_ERROR),g})}).then(function(_){if(h._is_canceled||h._status===ee.STATUS_TERMINATED)throw new Error("terminated");h._request.body=_,h._status=ee.STATUS_INVITE_SENT,J.debug('emit "sending" [request:%o]',h._request),h.emit("sending",{request:h._request}),d.send()}).catch(function(_){h._status!==ee.STATUS_TERMINATED&&J.warn(_)})}},{key:"_getDTMFRTPSender",value:function(){var a=this._connection.getSenders().find(function(n){return n.track&&n.track.kind==="audio"});if(!(a&&a.dtmf)){J.warn("sendDTMF() | no local audio track to send DTMF with");return}return a.dtmf}},{key:"_receiveInviteResponse",value:function(a){var n=this;if(J.debug("receiveInviteResponse()"),this._dialog&&a.status_code>=200&&a.status_code<=299)if(this._dialog.id.call_id===a.call_id&&this._dialog.id.local_tag===a.from_tag&&this._dialog.id.remote_tag===a.to_tag){this.sendRequest(ce.ACK);return}else{var r=new ql(this,a,"UAC");if(r.error!==void 0){J.debug(r.error);return}this.sendRequest(ce.ACK),this.sendRequest(ce.BYE);return}if(this._is_canceled){a.status_code>=100&&a.status_code<200?this._request.cancel(this._cancel_reason):a.status_code>=200&&a.status_code<299&&this._acceptAndTerminate(a);return}if(!(this._status!==ee.STATUS_INVITE_SENT&&this._status!==ee.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(a.status_code):this._status=ee.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(a.status_code):{if(!a.to_tag){J.debug("1xx response received without to tag");break}if(a.hasHeader("contact")&&!this._createDialog(a,"UAC",!0))break;if(this._status=ee.STATUS_1XX_RECEIVED,!a.body){this._progress("remote",a);break}var h={originator:"remote",type:"answer",sdp:a.body};J.debug('emit "sdp"'),this.emit("sdp",h);var d=new RTCSessionDescription({type:"answer",sdp:h.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return n._connection.setRemoteDescription(d)}).then(function(){return n._progress("remote",a)}).catch(function(S){J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),n.emit("peerconnection:setremotedescriptionfailed",S)});break}case/^2[0-9]{2}$/.test(a.status_code):{if(this._status=ee.STATUS_CONFIRMED,!a.body){this._acceptAndTerminate(a,400,ce.causes.MISSING_SDP),this._failed("remote",a,ce.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(a,"UAC"))break;var _={originator:"remote",type:"answer",sdp:a.body};J.debug('emit "sdp"'),this.emit("sdp",_);var g=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(n._connection.signalingState==="stable")return n._connection.createOffer(n._rtcOfferConstraints).then(function(S){return n._connection.setLocalDescription(S)}).catch(function(S){n._acceptAndTerminate(a,500,S.toString()),n._failed("local",a,ce.causes.WEBRTC_ERROR)})}).then(function(){n._connection.setRemoteDescription(g).then(function(){n._handleSessionTimersInIncomingResponse(a),n._accepted("remote",a),n.sendRequest(ce.ACK),n._confirmed("local",null)}).catch(function(S){n._acceptAndTerminate(a,488,"Not Acceptable Here"),n._failed("remote",a,ce.causes.BAD_MEDIA_DESCRIPTION),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),n.emit("peerconnection:setremotedescriptionfailed",S)})});break}default:{var T=Ge.sipErrorCause(a.status_code);this._failed("remote",a,T)}}}},{key:"_sendReinvite",value:function(){var a=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};J.debug("sendReinvite()");var r=Ge.cloneArray(n.extraHeaders),h=Ge.cloneObject(n.eventHandlers),d=n.rtcOfferConstraints||this._rtcOfferConstraints||null,_=!1;r.push("Contact: ".concat(this._contact)),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",d)}).then(function(S){S=a._mangleOffer(S);var E={originator:"local",type:"offer",sdp:S};J.debug('emit "sdp"'),a.emit("sdp",E),a.sendRequest(ce.INVITE,{extraHeaders:r,body:S,eventHandlers:{onSuccessResponse:function(A){g.call(a,A),_=!0},onErrorResponse:function(A){T.call(a,A)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){T()});function g(S){var E=this;if(this._status!==ee.STATUS_TERMINATED&&(this.sendRequest(ce.ACK),!_)){if(this._handleSessionTimersInIncomingResponse(S),S.body){if(!S.hasHeader("Content-Type")||S.getHeader("Content-Type").toLowerCase()!=="application/sdp"){T.call(this);return}}else{T.call(this);return}var C={originator:"remote",type:"answer",sdp:S.body};J.debug('emit "sdp"'),this.emit("sdp",C);var A=new RTCSessionDescription({type:"answer",sdp:C.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return E._connection.setRemoteDescription(A)}).then(function(){h.succeeded&&h.succeeded(S)}).catch(function(R){T.call(E),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),E.emit("peerconnection:setremotedescriptionfailed",R)})}}function T(S){h.failed&&h.failed(S)}}},{key:"_sendUpdate",value:function(){var a=this,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};J.debug("sendUpdate()");var r=Ge.cloneArray(n.extraHeaders),h=Ge.cloneObject(n.eventHandlers),d=n.rtcOfferConstraints||this._rtcOfferConstraints||null,_=n.sdpOffer||!1,g=!1;r.push("Contact: ".concat(this._contact)),this._sessionTimers.running&&r.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),_?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",d)}).then(function(E){E=a._mangleOffer(E);var C={originator:"local",type:"offer",sdp:E};J.debug('emit "sdp"'),a.emit("sdp",C),a.sendRequest(ce.UPDATE,{extraHeaders:r,body:E,eventHandlers:{onSuccessResponse:function(R){T.call(a,R),g=!0},onErrorResponse:function(R){S.call(a,R)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){S.call(a)})):this.sendRequest(ce.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:function(C){T.call(a,C)},onErrorResponse:function(C){S.call(a,C)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}});function T(E){var C=this;if(this._status!==ee.STATUS_TERMINATED&&!g)if(this._handleSessionTimersInIncomingResponse(E),_){if(E.body){if(!E.hasHeader("Content-Type")||E.getHeader("Content-Type").toLowerCase()!=="application/sdp"){S.call(this);return}}else{S.call(this);return}var A={originator:"remote",type:"answer",sdp:E.body};J.debug('emit "sdp"'),this.emit("sdp",A);var R=new RTCSessionDescription({type:"answer",sdp:A.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return C._connection.setRemoteDescription(R)}).then(function(){h.succeeded&&h.succeeded(E)}).catch(function(F){S.call(C),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',F),C.emit("peerconnection:setremotedescriptionfailed",F)})}else h.succeeded&&h.succeeded(E)}function S(E){h.failed&&h.failed(E)}}},{key:"_acceptAndTerminate",value:function(a,n,r){J.debug("acceptAndTerminate()");var h=[];n&&(r=r||ce.REASON_PHRASE[n]||"",h.push("Reason: SIP ;cause=".concat(n,'; text="').concat(r,'"'))),(this._dialog||this._createDialog(a,"UAC"))&&(this.sendRequest(ce.ACK),this.sendRequest(ce.BYE,{extraHeaders:h})),this._status=ee.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(a){if(!this._localHold&&!this._remoteHold)return a;if(a=Uc.parse(a),this._localHold&&!this._remoteHold){J.debug("mangleOffer() | me on hold, mangling offer");var n=ps(a.media),r;try{for(n.s();!(r=n.n()).done;){var h=r.value;Bl.indexOf(h.type)!==-1&&(h.direction?h.direction==="sendrecv"?h.direction="sendonly":h.direction==="recvonly"&&(h.direction="inactive"):h.direction="sendonly")}}catch(C){n.e(C)}finally{n.f()}}else if(this._localHold&&this._remoteHold){J.debug("mangleOffer() | both on hold, mangling offer");var d=ps(a.media),_;try{for(d.s();!(_=d.n()).done;){var g=_.value;Bl.indexOf(g.type)!==-1&&(g.direction="inactive")}}catch(C){d.e(C)}finally{d.f()}}else if(this._remoteHold){J.debug("mangleOffer() | remote on hold, mangling offer");var T=ps(a.media),S;try{for(T.s();!(S=T.n()).done;){var E=S.value;Bl.indexOf(E.type)!==-1&&(E.direction?E.direction==="sendrecv"?E.direction="recvonly":E.direction==="recvonly"&&(E.direction="inactive"):E.direction="recvonly")}}catch(C){T.e(C)}finally{T.f()}}return Uc.write(a)}},{key:"_setLocalMediaStatus",value:function(){var a=!0,n=!0;(this._localHold||this._remoteHold)&&(a=!1,n=!1),this._audioMuted&&(a=!1),this._videoMuted&&(n=!1),this._toggleMuteAudio(!a),this._toggleMuteVideo(!n)}},{key:"_handleSessionTimersInIncomingRequest",value:function(a,n){if(this._sessionTimers.enabled){var r;a.session_expires&&a.session_expires>=ce.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,r=a.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uas"),n.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(r)),this._sessionTimers.refresher=r==="uas",this._runSessionTimer()}}},{key:"_handleSessionTimersInIncomingResponse",value:function(a){if(this._sessionTimers.enabled){var n;a.session_expires&&a.session_expires>=ce.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,n=a.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}}},{key:"_runSessionTimer",value:function(){var a=this,n=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(function(){a._status!==ee.STATUS_TERMINATED&&a._isReadyToReOffer()&&(J.debug("runSessionTimer() | sending session refresh request"),a._sessionTimers.refreshMethod===ce.UPDATE?a._sendUpdate():a._sendReinvite())},n*500):this._sessionTimers.timer=setTimeout(function(){a._status!==ee.STATUS_TERMINATED&&(J.warn("runSessionTimer() | timer expired, terminating the session"),a.terminate({cause:ce.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},n*1100)}},{key:"_toggleMuteAudio",value:function(a){var n=this._connection.getSenders().filter(function(_){return _.track&&_.track.kind==="audio"}),r=ps(n),h;try{for(r.s();!(h=r.n()).done;){var d=h.value;d.track.enabled=!a}}catch(_){r.e(_)}finally{r.f()}}},{key:"_toggleMuteVideo",value:function(a){var n=this._connection.getSenders().filter(function(_){return _.track&&_.track.kind==="video"}),r=ps(n),h;try{for(r.s();!(h=r.n()).done;){var d=h.value;d.track.enabled=!a}}catch(_){r.e(_)}finally{r.f()}}},{key:"_newRTCSession",value:function(a,n){J.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:a,session:this,request:n})}},{key:"_connecting",value:function(a){J.debug("session connecting"),J.debug('emit "connecting"'),this.emit("connecting",{request:a})}},{key:"_progress",value:function(a,n){J.debug("session progress"),J.debug('emit "progress"'),this.emit("progress",{originator:a,response:n||null})}},{key:"_accepted",value:function(a,n){J.debug("session accepted"),this._start_time=new Date,J.debug('emit "accepted"'),this.emit("accepted",{originator:a,response:n||null})}},{key:"_confirmed",value:function(a,n){J.debug("session confirmed"),this._is_confirmed=!0,J.debug('emit "confirmed"'),this.emit("confirmed",{originator:a,ack:n||null})}},{key:"_ended",value:function(a,n,r){J.debug("session ended"),this._end_time=new Date,this._close(),J.debug('emit "ended"'),this.emit("ended",{originator:a,message:n||null,cause:r})}},{key:"_failed",value:function(a,n,r){J.debug("session failed"),J.debug('emit "_failed"'),this.emit("_failed",{originator:a,message:n||null,cause:r}),this._close(),J.debug('emit "failed"'),this.emit("failed",{originator:a,message:n||null,cause:r})}},{key:"_onhold",value:function(a){J.debug("session onhold"),this._setLocalMediaStatus(),J.debug('emit "hold"'),this.emit("hold",{originator:a})}},{key:"_onunhold",value:function(a){J.debug("session onunhold"),this._setLocalMediaStatus(),J.debug('emit "unhold"'),this.emit("unhold",{originator:a})}},{key:"_onmute",value:function(a){var n=a.audio,r=a.video;J.debug("session onmute"),this._setLocalMediaStatus(),J.debug('emit "muted"'),this.emit("muted",{audio:n,video:r})}},{key:"_onunmute",value:function(a){var n=a.audio,r=a.video;J.debug("session onunmute"),this._setLocalMediaStatus(),J.debug('emit "unmuted"'),this.emit("unmuted",{audio:n,video:r})}},{key:"C",get:function(){return ee}},{key:"causes",get:function(){return ce.causes}},{key:"id",get:function(){return this._id}},{key:"connection",get:function(){return this._connection}},{key:"contact",get:function(){return this._contact}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}},{key:"start_time",get:function(){return this._start_time}},{key:"end_time",get:function(){return this._end_time}},{key:"data",get:function(){return this._data},set:function(a){this._data=a}},{key:"status",get:function(){return this._status}}]),s}(gp);function bo(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?bo=function(s){return typeof s}:bo=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},bo(c)}function Ap(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Lc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function Rp(c,t,s){return t&&Lc(c.prototype,t),s&&Lc(c,s),c}function Ip(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&Su(c,t)}function Su(c,t){return Su=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},Su(c,t)}function bp(c){var t=Dp();return function(){var i=$o(c),a;if(t){var n=$o(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return wp(this,a)}}function wp(c,t){return t&&(bo(t)==="object"||typeof t=="function")?t:Op(c)}function Op(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Dp(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function $o(c){return $o=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},$o(c)}var Np=dt.EventEmitter,xp=ht,ba=ot,Up=ys,Mi=wt(),kp=hl,$c=Ks,Mp=Ys(),Gl=new xp("Message"),Pp=function(c){Ip(s,c);var t=bp(s);function s(i){var a;return Ap(this,s),a=t.call(this),a._ua=i,a._request=null,a._closed=!1,a._direction=null,a._local_identity=null,a._remote_identity=null,a._is_replied=!1,a._data={},a}return Rp(s,[{key:"send",value:function(a,n){var r=this,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},d=a;if(a===void 0||n===void 0)throw new TypeError("Not enough arguments");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(d));var _=Mi.cloneArray(h.extraHeaders),g=Mi.cloneObject(h.eventHandlers),T=h.contentType||"text/plain",S={};h.fromUserName&&(S.from_uri=new Mp("sip",h.fromUserName,this._ua.configuration.uri.host),_.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),h.fromDisplayName&&(S.from_display_name=h.fromDisplayName);for(var E in g)Object.prototype.hasOwnProperty.call(g,E)&&this.on(E,g[E]);_.push("Content-Type: ".concat(T)),this._request=new Up.OutgoingRequest(ba.MESSAGE,a,this._ua,S,_),n&&(this._request.body=n);var C=new kp(this._ua,this._request,{onRequestTimeout:function(){r._onRequestTimeout()},onTransportError:function(){r._onTransportError()},onReceiveResponse:function(R){r._receiveResponse(R)}});this._newMessage("local",this._request),C.send()}},{key:"init_incoming",value:function(a){this._request=a,this._newMessage("remote",a),this._is_replied||(this._is_replied=!0,a.reply(200)),this._close()}},{key:"accept",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=Mi.cloneArray(a.extraHeaders),r=a.body;if(this._direction!=="incoming")throw new $c.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,n,r)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=a.status_code||480,r=a.reason_phrase,h=Mi.cloneArray(a.extraHeaders),d=a.body;if(this._direction!=="incoming")throw new $c.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(n<300||n>=700)throw new TypeError("Invalid status_code: ".concat(n));this._is_replied=!0,this._request.reply(n,r,h,d)}},{key:"_receiveResponse",value:function(a){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._succeeded("remote",a);break;default:{var n=Mi.sipErrorCause(a.status_code);this._failed("remote",a,n);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,ba.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,ba.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newMessage",value:function(a,n){a==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):a==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newMessage(this,{originator:a,message:this,request:n})}},{key:"_failed",value:function(a,n,r){Gl.debug("MESSAGE failed"),this._close(),Gl.debug('emit "failed"'),this.emit("failed",{originator:a,response:n||null,cause:r})}},{key:"_succeeded",value:function(a,n){Gl.debug("MESSAGE succeeded"),this._close(),Gl.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:n})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),s}(Np);function wo(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?wo=function(s){return typeof s}:wo=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},wo(c)}function Lp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Hc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function $p(c,t,s){return t&&Hc(c.prototype,t),s&&Hc(c,s),c}function Hp(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&Eu(c,t)}function Eu(c,t){return Eu=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},Eu(c,t)}function Fp(c){var t=qp();return function(){var i=Ho(c),a;if(t){var n=Ho(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return Vp(this,a)}}function Vp(c,t){return t&&(wo(t)==="object"||typeof t=="function")?t:jp(c)}function jp(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function qp(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Ho(c){return Ho=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},Ho(c)}var Bp=dt.EventEmitter,Gp=ht,wa=ot,Wp=ys,Pi=wt(),Kp=hl,Fc=Ks,Wl=new Gp("Options"),Yp=function(c){Hp(s,c);var t=Fp(s);function s(i){var a;return Lp(this,s),a=t.call(this),a._ua=i,a._request=null,a._closed=!1,a._direction=null,a._local_identity=null,a._remote_identity=null,a._is_replied=!1,a._data={},a}return $p(s,[{key:"send",value:function(a,n){var r=this,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},d=a;if(a===void 0)throw new TypeError("A target is required for OPTIONS");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(d));var _=Pi.cloneArray(h.extraHeaders),g=Pi.cloneObject(h.eventHandlers),T=h.contentType||"application/sdp";for(var S in g)Object.prototype.hasOwnProperty.call(g,S)&&this.on(S,g[S]);_.push("Content-Type: ".concat(T)),this._request=new Wp.OutgoingRequest(wa.OPTIONS,a,this._ua,null,_),n&&(this._request.body=n);var E=new Kp(this._ua,this._request,{onRequestTimeout:function(){r._onRequestTimeout()},onTransportError:function(){r._onTransportError()},onReceiveResponse:function(A){r._receiveResponse(A)}});this._newOptions("local",this._request),E.send()}},{key:"init_incoming",value:function(a){this._request=a,this._newOptions("remote",a),this._is_replied||(this._is_replied=!0,a.reply(200)),this._close()}},{key:"accept",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=Pi.cloneArray(a.extraHeaders),r=a.body;if(this._direction!=="incoming")throw new Fc.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,n,r)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=a.status_code||480,r=a.reason_phrase,h=Pi.cloneArray(a.extraHeaders),d=a.body;if(this._direction!=="incoming")throw new Fc.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(n<300||n>=700)throw new TypeError("Invalid status_code: ".concat(n));this._is_replied=!0,this._request.reply(n,r,h,d)}},{key:"_receiveResponse",value:function(a){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._succeeded("remote",a);break;default:{var n=Pi.sipErrorCause(a.status_code);this._failed("remote",a,n);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,wa.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,wa.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newOptions",value:function(a,n){a==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):a==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newOptions(this,{originator:a,message:this,request:n})}},{key:"_failed",value:function(a,n,r){Wl.debug("OPTIONS failed"),this._close(),Wl.debug('emit "failed"'),this.emit("failed",{originator:a,response:n||null,cause:r})}},{key:"_succeeded",value:function(a,n){Wl.debug("OPTIONS succeeded"),this._close(),Wl.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:n})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),s}(Bp),$u={},Jp=ht,Oa=wt(),zp=us(),Li=new Jp("Socket");$u.isSocket=function(c){if(Array.isArray(c))return!1;if(typeof c>"u")return Li.warn("undefined JsSIP.Socket instance"),!1;try{if(!Oa.isString(c.url))throw Li.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!Oa.isString(c.via_transport))throw Li.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(zp.parse(c.sip_uri,"SIP_URI")===-1)throw Li.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(function(t){if(!Oa.isFunction(c[t]))throw Li.warn("missing or invalid JsSIP.Socket method: ".concat(t)),new Error("Missing or invalid JsSIP.Socket method: ".concat(t))})}catch{return!1}return!0};function Qp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Vc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function Xp(c,t,s){return t&&Vc(c.prototype,t),s&&Vc(c,s),c}var Zp=ht,em=$u,jc=ot,xt=new Zp("Transport"),qt={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:jc.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:jc.CONNECTION_RECOVERY_MAX_INTERVAL}},tm=function(){function c(t){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:qt.recovery_options;Qp(this,c),xt.debug("new()"),this.status=qt.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=s,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(i){xt.warn("cannot use TextDecoder: ".concat(i))}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(i){if(!em.isSocket(i.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(i.weight&&!Number(i.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:i.socket,weight:i.weight||0,status:qt.SOCKET_STATUS_READY})},this),this._getSocket()}return Xp(c,[{key:"connect",value:function(){if(xt.debug("connect()"),this.isConnected()){xt.debug("Transport is already connected");return}else if(this.isConnecting()){xt.debug("Transport is connecting");return}this.close_requested=!1,this.status=qt.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}},{key:"disconnect",value:function(){xt.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=qt.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=function(){},this.socket.ondisconnect=function(){},this.socket.ondata=function(){},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}},{key:"send",value:function(s){if(xt.debug("send()"),!this.isConnected())return xt.warn("unable to send message, transport is not connected"),!1;var i=s.toString();return xt.debug(`sending message:
|
|
51
51
|
|
|
52
|
-
`.concat(
|
|
53
|
-
`)),this.socket.send(
|
|
54
|
-
`){
|
|
52
|
+
`.concat(i,`
|
|
53
|
+
`)),this.socket.send(i)}},{key:"isConnected",value:function(){return this.status===qt.STATUS_CONNECTED}},{key:"isConnecting",value:function(){return this.status===qt.STATUS_CONNECTING}},{key:"_reconnect",value:function(){var s=this;this.recover_attempts+=1;var i=Math.floor(Math.random()*Math.pow(2,this.recover_attempts)+1);i<this.recovery_options.min_interval?i=this.recovery_options.min_interval:i>this.recovery_options.max_interval&&(i=this.recovery_options.max_interval),xt.debug("reconnection attempt: ".concat(this.recover_attempts,". next connection attempt in ").concat(i," seconds")),this.recovery_timer=setTimeout(function(){!s.close_requested&&!(s.isConnected()||s.isConnecting())&&(s._getSocket(),s.connect())},i*1e3)}},{key:"_getSocket",value:function(){var s=[];if(this.sockets.forEach(function(a){a.status!==qt.SOCKET_STATUS_ERROR&&(s.length===0?s.push(a):a.weight>s[0].weight?s=[a]:a.weight===s[0].weight&&s.push(a))}),s.length===0){this.sockets.forEach(function(a){a.status=qt.SOCKET_STATUS_READY}),this._getSocket();return}var i=Math.floor(Math.random()*s.length);this.socket=s[i].socket}},{key:"_onConnect",value:function(){this.recover_attempts=0,this.status=qt.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}},{key:"_onDisconnect",value:function(s,i,a){this.status=qt.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:s,code:i,reason:a}),!this.close_requested&&(this.sockets.forEach(function(n){this.socket===n.socket&&(n.status=qt.SOCKET_STATUS_ERROR)},this),this._reconnect(s))}},{key:"_onData",value:function(s){if(s===`\r
|
|
54
|
+
`){xt.debug("received message with CRLF Keep Alive response");return}else if(typeof s!="string"){try{this.textDecoder?s=this.textDecoder.decode(s):s=String.fromCharCode.apply(null,new Uint8Array(s))}catch{xt.debug("received binary message failed to be converted into string, message discarded");return}xt.debug(`received binary message:
|
|
55
55
|
|
|
56
|
-
`.concat(
|
|
57
|
-
`))}else
|
|
56
|
+
`.concat(s,`
|
|
57
|
+
`))}else xt.debug(`received text message:
|
|
58
58
|
|
|
59
|
-
`.concat(
|
|
60
|
-
`));this.ondata({transport:this,message:
|
|
61
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var
|
|
62
|
-
`);if(a===-1){
|
|
63
|
-
`,
|
|
64
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var
|
|
65
|
-
`),a=
|
|
66
|
-
`)}}catch(h){a.e(h)}finally{a.f()}
|
|
67
|
-
`),
|
|
68
|
-
`),
|
|
69
|
-
`),
|
|
70
|
-
`),
|
|
71
|
-
`,
|
|
72
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,h;return{s:function(){n=c[Symbol.iterator]()},n:function(){var _=n.next();return s=_.done,_},e:function(_){r=!0,h=_},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw h}}}}function dm(c,t){if(c){if(typeof c=="string")return Wc(c,t);var n=Object.prototype.toString.call(c).slice(8,-1);if(n==="Object"&&c.constructor&&(n=c.constructor.name),n==="Map"||n==="Set")return Array.from(c);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Wc(c,t)}}function Wc(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,l=new Array(t);n<t;n++)l[n]=c[n];return l}var cr=bt(),yn=lt,wa=as(),Kc=Ks(),Oa=Mu,Da=Ws;Hu.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:yn.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:yn.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:yn.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(cr.createRandomToken(12),".invalid")};var Kl={mandatory:{sockets:function(t){var n=[];if(Oa.isSocket(t))n.push({socket:t});else if(Array.isArray(t)&&t.length){var l=Gc(t),a;try{for(l.s();!(a=l.n()).done;){var s=a.value;Object.prototype.hasOwnProperty.call(s,"socket")&&Oa.isSocket(s.socket)?n.push(s):Oa.isSocket(s)&&n.push({socket:s})}}catch(r){l.e(r)}finally{l.f()}}else return;return n},uri:function(t){/^sip:/i.test(t)||(t="".concat(yn.SIP,":").concat(t));var n=Kc.parse(t);if(n)return n.user?n:void 0}},optional:{authorization_user:function(t){if(wa.parse('"'.concat(t,'"'),"quoted_string")!==-1)return t},authorization_jwt:function(t){if(typeof t=="string")return t},user_agent:function(t){if(typeof t=="string")return t},connection_recovery_max_interval:function(t){if(cr.isDecimal(t)){var n=Number(t);if(n>0)return n}},connection_recovery_min_interval:function(t){if(cr.isDecimal(t)){var n=Number(t);if(n>0)return n}},contact_uri:function(t){if(typeof t=="string"){var n=wa.parse(t,"SIP_URI");if(n!==-1)return n}},display_name:function(t){return t},instance_id:function(t){if(/^uuid:/i.test(t)&&(t=t.substr(5)),wa.parse(t,"uuid")!==-1)return t},no_answer_timeout:function(t){if(cr.isDecimal(t)){var n=Number(t);if(n>0)return n}},session_timers:function(t){if(typeof t=="boolean")return t},session_timers_refresh_method:function(t){if(typeof t=="string"&&(t=t.toUpperCase(),t===yn.INVITE||t===yn.UPDATE))return t},session_timers_force_refresher:function(t){if(typeof t=="boolean")return t},password:function(t){return String(t)},realm:function(t){return String(t)},ha1:function(t){return String(t)},register:function(t){if(typeof t=="boolean")return t},register_expires:function(t){if(cr.isDecimal(t)){var n=Number(t);if(n>0)return n}},registrar_server:function(t){/^sip:/i.test(t)||(t="".concat(yn.SIP,":").concat(t));var n=Kc.parse(t);if(n)return n.user?void 0:n},use_preloaded_route:function(t){if(typeof t=="boolean")return t},extra_headers:function(t){var n=[];if(Array.isArray(t)&&t.length){var l=Gc(t),a;try{for(l.s();!(a=l.n()).done;){var s=a.value;typeof s=="string"&&n.push(s)}}catch(r){l.e(r)}finally{l.f()}}else return;return n}}};Hu.load=function(c,t){for(var n in Kl.mandatory)if(t.hasOwnProperty(n)){var l=t[n],a=Kl.mandatory[n](l);if(a!==void 0)c[n]=a;else throw new Da.ConfigurationError(n,l)}else throw new Da.ConfigurationError(n);for(var s in Kl.optional)if(t.hasOwnProperty(s)){var r=t[s];if(cr.isEmpty(r))continue;var h=Kl.optional[s](r);if(h!==void 0)c[s]=h;else throw new Da.ConfigurationError(s,r)}};function wo(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?wo=function(n){return typeof n}:wo=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},wo(c)}function hm(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Yc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function Jc(c,t,n){return t&&Yc(c.prototype,t),n&&Yc(c,n),c}function _m(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&yu(c,t)}function yu(c,t){return yu=Object.setPrototypeOf||function(l,a){return l.__proto__=a,l},yu(c,t)}function pm(c){var t=gm();return function(){var l=$o(c),a;if(t){var s=$o(this).constructor;a=Reflect.construct(l,arguments,s)}else a=l.apply(this,arguments);return mm(this,a)}}function mm(c,t){return t&&(wo(t)==="object"||typeof t=="function")?t:fd(c)}function fd(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function gm(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function $o(c){return $o=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},$o(c)}var Tm=ft.EventEmitter,vm=dt,pt=lt,Sm=o_,zc=mp,Xc=Op,Qc=Vp,Na=fl,Em=Yp,Yl=bt(),ym=Ws,Cm=Ks(),Am=ad,xa=Es,Rm=rm,Ua=Hu,je=new vm("UA"),Tt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},Im=function(c){_m(n,c);var t=pm(n);Jc(n,null,[{key:"C",get:function(){return Tt}}]);function n(l){var a;if(hm(this,n),je.debug("new() [configuration:%o]",l),a=t.call(this),a._cache={credentials:{}},a._configuration=Object.assign({},Ua.settings),a._dynConfiguration={},a._dialogs={},a._applicants={},a._sessions={},a._transport=null,a._contact=null,a._status=Tt.STATUS_INIT,a._error=null,a._transactions={nist:{},nict:{},ist:{},ict:{}},a._data={},a._closeTimer=null,l===void 0)throw new TypeError("Not enough arguments");try{a._loadConfig(l)}catch(s){throw a._status=Tt.STATUS_NOT_READY,a._error=Tt.CONFIGURATION_ERROR,s}return a._registrator=new Sm(fd(a)),a}return Jc(n,[{key:"start",value:function(){je.debug("start()"),this._status===Tt.STATUS_INIT?this._transport.connect():this._status===Tt.STATUS_USER_CLOSED?(je.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Tt.STATUS_INIT,this._transport.connect()):this._status===Tt.STATUS_READY?je.debug("UA is in READY status, not restarted"):je.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}},{key:"register",value:function(){je.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}},{key:"unregister",value:function(a){je.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(a)}},{key:"registrator",value:function(){return this._registrator}},{key:"isRegistered",value:function(){return this._registrator.registered}},{key:"isConnected",value:function(){return this._transport.isConnected()}},{key:"call",value:function(a,s){je.debug("call()");var r=new zc(this);return r.connect(a,s),r}},{key:"sendMessage",value:function(a,s,r){je.debug("sendMessage()");var h=new Xc(this);return h.send(a,s,r),h}},{key:"sendOptions",value:function(a,s,r){je.debug("sendOptions()");var h=new Qc(this);return h.send(a,s,r),h}},{key:"terminateSessions",value:function(a){je.debug("terminateSessions()");for(var s in this._sessions)this._sessions[s].isEnded()||this._sessions[s].terminate(a)}},{key:"stop",value:function(){var a=this;if(je.debug("stop()"),this._dynConfiguration={},this._status===Tt.STATUS_USER_CLOSED){je.debug("UA already closed");return}this._registrator.close();var s=Object.keys(this._sessions).length;for(var r in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,r)){je.debug("closing session ".concat(r));try{this._sessions[r].terminate()}catch{}}for(var h in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,h))try{this._applicants[h].close()}catch{}this._status=Tt.STATUS_USER_CLOSED;var d=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;d===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){a._closeTimer=null,a._transport.disconnect()},2e3)}},{key:"normalizeTarget",value:function(a){return Yl.normalizeTarget(a,this._configuration.hostport_params)}},{key:"get",value:function(a){switch(a){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:je.warn('get() | cannot get "%s" parameter in runtime',a);return}}},{key:"set",value:function(a,s){switch(a){case"authorization_user":{this._configuration.authorization_user=String(s);break}case"password":{this._configuration.password=String(s);break}case"realm":{this._configuration.realm=String(s);break}case"ha1":{this._configuration.ha1=String(s),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(s);break}case"display_name":{this._configuration.display_name=s;break}default:return je.warn('set() | cannot set "%s" parameter in runtime',a),!1}return!0}},{key:"newTransaction",value:function(a){this._transactions[a.type][a.id]=a,this.emit("newTransaction",{transaction:a})}},{key:"destroyTransaction",value:function(a){delete this._transactions[a.type][a.id],this.emit("transactionDestroyed",{transaction:a})}},{key:"newDialog",value:function(a){this._dialogs[a.id]=a}},{key:"destroyDialog",value:function(a){delete this._dialogs[a.id]}},{key:"newMessage",value:function(a,s){this._applicants[a]=a,this.emit("newMessage",s)}},{key:"newOptions",value:function(a,s){this._applicants[a]=a,this.emit("newOptions",s)}},{key:"destroyMessage",value:function(a){delete this._applicants[a]}},{key:"newRTCSession",value:function(a,s){this._sessions[a.id]=a,this.emit("newRTCSession",s)}},{key:"destroyRTCSession",value:function(a){delete this._sessions[a.id]}},{key:"registered",value:function(a){this.emit("registered",a)}},{key:"unregistered",value:function(a){this.emit("unregistered",a)}},{key:"registrationFailed",value:function(a){this.emit("registrationFailed",a)}},{key:"receiveRequest",value:function(a){var s=a.method;if(a.ruri.user!==this._configuration.uri.user&&a.ruri.user!==this._contact.uri.user){je.debug("Request-URI does not point to us"),a.method!==pt.ACK&&a.reply_sl(404);return}if(a.ruri.scheme===pt.SIPS){a.reply_sl(416);return}if(!Na.checkTransaction(this,a)){if(s===pt.INVITE?new Na.InviteServerTransaction(this,this._transport,a):s!==pt.ACK&&s!==pt.CANCEL&&new Na.NonInviteServerTransaction(this,this._transport,a),s===pt.OPTIONS){if(this.listeners("newOptions").length===0){a.reply(200);return}var r=new Qc(this);r.init_incoming(a)}else if(s===pt.MESSAGE){if(this.listeners("newMessage").length===0){a.reply(405);return}var h=new Xc(this);h.init_incoming(a)}else if(s===pt.INVITE&&!a.to_tag&&this.listeners("newRTCSession").length===0){a.reply(405);return}var d,_;if(a.to_tag)d=this._findDialog(a.call_id,a.from_tag,a.to_tag),d?d.receiveRequest(a):s===pt.NOTIFY?(_=this._findSession(a),_?_.receiveRequest(a):(je.debug("received NOTIFY request for a non existent subscription"),a.reply(481,"Subscription does not exist"))):s!==pt.ACK&&a.reply(481);else switch(s){case pt.INVITE:if(window.RTCPeerConnection)if(a.hasHeader("replaces")){var g=a.replaces;d=this._findDialog(g.call_id,g.from_tag,g.to_tag),d?(_=d.owner,_.isEnded()?a.reply(603):_.receiveRequest(a)):a.reply(481)}else _=new zc(this),_.init_incoming(a);else je.warn("INVITE received but WebRTC is not supported"),a.reply(488);break;case pt.BYE:a.reply(481);break;case pt.CANCEL:_=this._findSession(a),_?_.receiveRequest(a):je.debug("received CANCEL request for a non existent session");break;case pt.ACK:break;case pt.NOTIFY:this.emit("sipEvent",{event:a.event,request:a}),a.reply(200);break;default:a.reply(405);break}}}},{key:"_findSession",value:function(a){var s=a.call_id,r=a.from_tag,h=a.to_tag,d=s+r,_=this._sessions[d],g=s+h,T=this._sessions[g];return _||T||null}},{key:"_findDialog",value:function(a,s,r){var h=a+s+r,d=this._dialogs[h];return d||(h=a+r+s,d=this._dialogs[h],d||null)}},{key:"_loadConfig",value:function(a){try{Ua.load(this._configuration,a)}catch(g){throw g}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Yl.newUUID()),this._configuration.jssip_id=Yl.createRandomToken(5);var s=this._configuration.uri.clone();s.user=null,this._configuration.hostport_params=s.toString().replace(/^sip:/i,"");try{this._transport=new Em(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=bm.bind(this),this._transport.onconnect=wm.bind(this),this._transport.ondisconnect=Om.bind(this),this._transport.ondata=Dm.bind(this)}catch(g){throw je.warn(g),new ym.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){var r=this._configuration.uri.clone();r.user=null,r.clearParams(),r.clearHeaders(),this._configuration.registrar_server=r}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Cm("sip",Yl.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString:function(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},S=T.anonymous||null,E=T.outbound||null,C="<";return S?C+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":C+=this.pub_gruu||this.uri.toString(),E&&(S?!this.temp_gruu:!this.pub_gruu)&&(C+=";ob"),C+=">",C}};var h=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var d in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,d)&&(h.indexOf(d)!==-1?Object.defineProperty(this._configuration,d,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,d,{writable:!1,configurable:!1}));je.debug("configuration parameters after validation:");for(var _ in this._configuration)if(Object.prototype.hasOwnProperty.call(Ua.settings,_))switch(_){case"uri":case"registrar_server":je.debug("- ".concat(_,": ").concat(this._configuration[_]));break;case"password":case"ha1":case"authorization_jwt":je.debug("- ".concat(_,": NOT SHOWN"));break;default:je.debug("- ".concat(_,": ").concat(JSON.stringify(this._configuration[_])))}}},{key:"C",get:function(){return Tt}},{key:"status",get:function(){return this._status}},{key:"contact",get:function(){return this._contact}},{key:"configuration",get:function(){return this._configuration}},{key:"transport",get:function(){return this._transport}}]),n}(Tm);function bm(c){this.emit("connecting",c)}function wm(c){this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function Om(c){for(var t=["nict","ict","nist","ist"],n=0,l=t;n<l.length;n++){var a=l[n];for(var s in this._transactions[a])Object.prototype.hasOwnProperty.call(this._transactions[a],s)&&this._transactions[a][s].onTransportError()}this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Tt.STATUS_USER_CLOSED&&(this._status=Tt.STATUS_NOT_READY,this._error=Tt.NETWORK_ERROR)}function Dm(c){var t=c.transport,n=c.message;if(n=Am.parseMessage(n,this),!!n&&!(this._status===Tt.STATUS_USER_CLOSED&&n instanceof xa.IncomingRequest)&&Rm(n,this,t)){if(n instanceof xa.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof xa.IncomingResponse){var l;switch(n.method){case pt.INVITE:l=this._transactions.ict[n.via_branch],l&&l.receiveResponse(n);break;case pt.ACK:break;default:l=this._transactions.nict[n.via_branch],l&&l.receiveResponse(n);break}}}}function Nm(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Zc(c,t){for(var n=0;n<t.length;n++){var l=t[n];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}function xm(c,t,n){return t&&Zc(c.prototype,t),n&&Zc(c,n),c}var Um=dt,km=as(),Ot=new Um("WebSocketInterface"),Pm=function(){function c(t){Nm(this,c),Ot.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var n=km.parse(t,"absoluteURI");if(n===-1)throw Ot.warn("invalid WebSocket URI: ".concat(t)),new TypeError("Invalid argument: ".concat(t));if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ot.warn("invalid WebSocket URI scheme: ".concat(n.scheme)),new TypeError("Invalid argument: ".concat(t));this._sip_uri="sip:".concat(n.host).concat(n.port?":".concat(n.port):"",";transport=ws"),this._via_transport=n.scheme.toUpperCase()}return xm(c,[{key:"connect",value:function(){if(Ot.debug("connect()"),this.isConnected()){Ot.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){Ot.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),Ot.debug("connecting to WebSocket ".concat(this._url));try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(n){this._onError(n)}}},{key:"disconnect",value:function(){Ot.debug("disconnect()"),this._ws&&(this._ws.onopen=function(){},this._ws.onclose=function(){},this._ws.onmessage=function(){},this._ws.onerror=function(){},this._ws.close(),this._ws=null)}},{key:"send",value:function(n){return Ot.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(Ot.warn("unable to send message, WebSocket is not open"),!1)}},{key:"isConnected",value:function(){return this._ws&&this._ws.readyState===this._ws.OPEN}},{key:"isConnecting",value:function(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}},{key:"_onOpen",value:function(){Ot.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(n){var l=n.wasClean,a=n.code,s=n.reason;Ot.debug("WebSocket ".concat(this._url," closed")),l===!1&&Ot.debug("WebSocket abrupt disconnection"),this.ondisconnect(!l,a,s)}},{key:"_onMessage",value:function(n){var l=n.data;Ot.debug("received WebSocket message"),this.ondata(l)}},{key:"_onError",value:function(n){Ot.warn("WebSocket ".concat(this._url," error: "),n)}},{key:"via_transport",get:function(){return this._via_transport},set:function(n){this._via_transport=n.toUpperCase()}},{key:"sip_uri",get:function(){return this._sip_uri}},{key:"url",get:function(){return this._url}}]),c}(),Cu=Fo,Mm=lt,Lm=Ws,$m=bt(),Hm=Im,Fm=Ks(),Vm=Nu(),jm=as(),qm=Pm,Bm=mr("JsSIP");Bm("version %s",Cu.version);var ef={C:Mm,Exceptions:Lm,Utils:$m,UA:Hm,URI:Fm,NameAddrHeader:Vm,WebSocketInterface:qm,Grammar:jm,debug:mr,get name(){return Cu.title},get version(){return Cu.version}};const or=mr,ar="JsSIP";var ut=class{constructor(t){t?(this._debug=or.default(`${ar}:${t}`),this._warn=or.default(`${ar}:WARN:${t}`),this._error=or.default(`${ar}:ERROR:${t}`)):(this._debug=or.default(ar),this._warn=or.default(`${ar}:WARN`),this._error=or.default(`${ar}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};const Wo=Xe(ut),tf=Fo;var De={USER_AGENT:`${tf.title} ${tf.version}`,SIP:"sip",SIPS:"sips",causes:{CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:"Request Timeout",SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:"Rejected",REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:"Terminated",WEBRTC_ERROR:"WebRTC Error",CANCELED:"Canceled",NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:"ACK",BYE:"BYE",CANCEL:"CANCEL",INFO:"INFO",INVITE:"INVITE",MESSAGE:"MESSAGE",NOTIFY:"NOTIFY",OPTIONS:"OPTIONS",REGISTER:"REGISTER",REFER:"REFER",UPDATE:"UPDATE",SUBSCRIBE:"SUBSCRIBE",DTMF_TRANSPORT:{INFO:"INFO",RFC2833:"RFC2833"},REASON_PHRASE:{100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",424:"Bad Location Information",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:"JsSIP Internal 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"},ALLOWED_METHODS:"INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY",ACCEPTED_BODY_TYPES:"application/sdp, application/dtmf-relay",MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2};const $=Xe(De);var tt={},ka,sf;function Fu(){if(sf)return ka;sf=1;const c=ys(),t=Zt();return ka=class dd{static parse(l){if(l=t.parse(l,"Name_Addr_Header"),l!==-1)return l}constructor(l,a,s){if(!l||!(l instanceof c))throw new TypeError('missing or invalid "uri" parameter');this._uri=l,this._parameters={},this.display_name=a;for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&this.setParam(r,s[r])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(l){this._display_name=l===0?"0":l}setParam(l,a){l&&(this._parameters[l.toLowerCase()]=typeof a>"u"||a===null?null:a.toString())}getParam(l){if(l)return this._parameters[l.toLowerCase()]}hasParam(l){if(l)return this._parameters.hasOwnProperty(l.toLowerCase())&&!0||!1}deleteParam(l){if(l=l.toLowerCase(),this._parameters.hasOwnProperty(l)){const a=this._parameters[l];return delete this._parameters[l],a}}clearParams(){this._parameters={}}clone(){return new dd(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(l){return l.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let l=this._display_name?`"${this._quote(this._display_name)}" `:"";l+=`<${this._uri.toString()}>`;for(const a in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,a)&&(l+=`;${a}`,this._parameters[a]!==null&&(l+=`=${this._parameters[a]}`));return l}},ka}var Pa,nf;function Zt(){return nf||(nf=1,Pa=function(){function c(n){return'"'+n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+'"'}var t={parse:function(n,l){var a={CRLF:_,DIGIT:g,ALPHA:T,HEXDIG:S,WSP:E,OCTET:C,DQUOTE:A,SP:R,HTAB:V,alphanum:w,reserved:le,unreserved:x,mark:H,escaped:ve,LWS:pe,SWS:P,HCOLON:N,TEXT_UTF8_TRIM:q,TEXT_UTF8char:j,UTF8_NONASCII:Y,UTF8_CONT:F,LHEX:X,token:U,token_nodot:k,separators:B,word:He,STAR:Q,SLASH:W,EQUAL:G,LPAREN:re,RPAREN:_e,RAQUOT:Ie,LAQUOT:ke,COMMA:Ae,SEMI:oe,COLON:ye,LDQUOT:nt,RDQUOT:ot,comment:Ee,ctext:Ce,quoted_string:be,quoted_string_clean:Oe,qdtext:ge,quoted_pair:ue,SIP_URI_noparams:me,SIP_URI:we,uri_scheme:Ne,uri_scheme_sips:Ze,uri_scheme_sip:Le,userinfo:Lt,user:ht,user_unreserved:bn,password:wn,hostport:Ys,host:es,hostname:us,domainlabel:Js,toplabel:On,IPv6reference:Dn,IPv6address:zs,h16:Te,ls32:ae,IPv4address:at,dec_octet:Wt,port:As,uri_parameters:vr,uri_parameter:Nn,transport_param:xn,user_param:Sr,method_param:Er,ttl_param:yr,maddr_param:Cr,lr_param:Ar,other_param:Rr,pname:Ir,pvalue:br,paramchar:Rs,param_unreserved:Is,headers:wr,header:Xs,hname:Qs,hvalue:Or,hnv_unreserved:bs,Request_Response:Zs,Request_Line:ml,Request_URI:Dr,absoluteURI:Un,hier_part:kn,net_path:Nr,abs_path:en,opaque_part:tn,uric:ws,uric_no_slash:Os,path_segments:xr,segment:sn,param:Ds,pchar:cs,scheme:Ns,authority:Ur,srvr:kr,reg_name:Pr,query:Mr,SIP_Version:Pn,INVITEm:Mn,ACKm:Lr,OPTIONSm:$r,BYEm:Hr,CANCELm:Fr,REGISTERm:Vr,SUBSCRIBEm:jr,NOTIFYm:qr,REFERm:Br,Method:nn,Status_Line:rn,Status_Code:Gr,extension_code:Wr,Reason_Phrase:Kr,Allow_Events:gl,Call_ID:Jo,Contact:zo,contact_param:Ln,name_addr:$t,display_name:Ht,contact_params:xs,c_p_q:$n,c_p_expires:Yr,delta_seconds:ts,qvalue:ss,generic_param:We,gen_value:Ke,Content_Disposition:Tl,disp_type:vl,disp_param:Hn,handling_param:Fn,Content_Encoding:Sl,Content_Length:Xo,Content_Type:Qo,media_type:El,m_type:Jr,discrete_type:zr,composite_type:Xr,extension_token:ln,x_token:on,m_subtype:Qr,m_parameter:Vn,m_value:jn,CSeq:yl,CSeq_value:Cl,Expires:Al,Event:Zo,event_type:an,From:un,from_param:Zr,tag_param:cn,Max_Forwards:ei,Min_Expires:ea,Name_Addr_Header:ta,Proxy_Authenticate:sa,challenge:ti,other_challenge:qn,auth_param:Us,digest_cln:ns,realm:fn,realm_value:si,domain:ni,URI:dn,nonce:hn,nonce_value:ri,opaque:ii,stale:li,algorithm:oi,qop_options:ai,qop_value:_n,Proxy_Require:Bn,Record_Route:na,rec_route:Gn,Reason:Wn,reason_param:ui,reason_cause:Kn,Require:Rl,Route:ra,route_param:Yn,Subscription_State:Jn,substate_value:Il,subexp_params:zn,event_reason_value:Xn,Subject:bl,Supported:ia,To:la,to_param:ci,Via:fi,via_param:Qn,via_params:ks,via_ttl:Zn,via_maddr:di,via_received:hi,via_branch:_i,response_port:pi,rport:mi,sent_protocol:gi,protocol_name:Ti,transport:vi,sent_by:Si,via_host:Ei,via_port:yi,ttl:er,WWW_Authenticate:Ci,Session_Expires:oa,s_e_expires:wl,s_e_params:tr,s_e_refresher:sr,extension_header:Ol,header_value:Dl,message_body:Nl,uuid_URI:aa,uuid:xl,hex4:Ft,hex8:Vt,hex12:Ai,Refer_To:Ul,Replaces:ua,call_id:kl,replaces_param:nr,to_tag:rr,from_tag:Ri,early_flag:Ii};if(l!==void 0){if(a[l]===void 0)throw new Error("Invalid rule name: "+c(l)+".")}else l="CRLF";var s=0,r=0,h=[];function d(i){s<r||(s>r&&(r=s,h=[]),h.push(i))}function _(){var i;return n.substr(s,2)===`\r
|
|
73
|
-
`?(
|
|
74
|
-
`,s+=2):(i=null,d('"\\r\\n"')),i}function g(){var i;return/^[0-9]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[0-9]")),i}function T(){var i;return/^[a-zA-Z]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[a-zA-Z]")),i}function S(){var i;return/^[0-9a-fA-F]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[0-9a-fA-F]")),i}function E(){var i;return i=R(),i===null&&(i=V()),i}function C(){var i;return/^[\0-\xFF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\0-\\xFF]")),i}function A(){var i;return/^["]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d('["]')),i}function R(){var i;return n.charCodeAt(s)===32?(i=" ",s++):(i=null,d('" "')),i}function V(){var i;return n.charCodeAt(s)===9?(i=" ",s++):(i=null,d('"\\t"')),i}function w(){var i;return/^[a-zA-Z0-9]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[a-zA-Z0-9]")),i}function le(){var i;return n.charCodeAt(s)===59?(i=";",s++):(i=null,d('";"')),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,d('"/"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,d('"?"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,d('":"')),i===null&&(n.charCodeAt(s)===64?(i="@",s++):(i=null,d('"@"')),i===null&&(n.charCodeAt(s)===38?(i="&",s++):(i=null,d('"&"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,d('"="')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,d('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,d('"$"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,d('","'))))))))))),i}function x(){var i;return i=w(),i===null&&(i=H()),i}function H(){var i;return n.charCodeAt(s)===45?(i="-",s++):(i=null,d('"-"')),i===null&&(n.charCodeAt(s)===95?(i="_",s++):(i=null,d('"_"')),i===null&&(n.charCodeAt(s)===46?(i=".",s++):(i=null,d('"."')),i===null&&(n.charCodeAt(s)===33?(i="!",s++):(i=null,d('"!"')),i===null&&(n.charCodeAt(s)===126?(i="~",s++):(i=null,d('"~"')),i===null&&(n.charCodeAt(s)===42?(i="*",s++):(i=null,d('"*"')),i===null&&(n.charCodeAt(s)===39?(i="'",s++):(i=null,d(`"'"`)),i===null&&(n.charCodeAt(s)===40?(i="(",s++):(i=null,d('"("')),i===null&&(n.charCodeAt(s)===41?(i=")",s++):(i=null,d('")"')))))))))),i}function ve(){var i,e,o,u,f;return u=s,f=s,n.charCodeAt(s)===37?(i="%",s++):(i=null,d('"%"')),i!==null?(e=S(),e!==null?(o=S(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){return m.join("")}(u,i)),i===null&&(s=u),i}function pe(){var i,e,o,u,f,p;for(u=s,f=s,p=s,i=[],e=E();e!==null;)i.push(e),e=E();if(i!==null?(e=_(),e!==null?i=[i,e]:(i=null,s=p)):(i=null,s=p),i=i!==null?i:"",i!==null){if(o=E(),o!==null)for(e=[];o!==null;)e.push(o),o=E();else e=null;e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i!==null&&(i=function(m){return" "}()),i===null&&(s=u),i}function P(){var i;return i=pe(),i=i!==null?i:"",i}function N(){var i,e,o,u,f;for(u=s,f=s,i=[],e=R(),e===null&&(e=V());e!==null;)i.push(e),e=R(),e===null&&(e=V());return i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=P(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return":"}()),i===null&&(s=u),i}function q(){var i,e,o,u,f,p,m;if(f=s,p=s,e=j(),e!==null)for(i=[];e!==null;)i.push(e),e=j();else i=null;if(i!==null){for(e=[],m=s,o=[],u=pe();u!==null;)o.push(u),u=pe();for(o!==null?(u=j(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;){for(e.push(o),m=s,o=[],u=pe();u!==null;)o.push(u),u=pe();o!==null?(u=j(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m)}e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){return n.substring(s,v)}(f)),i===null&&(s=f),i}function j(){var i;return/^[!-~]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[!-~]")),i===null&&(i=Y()),i}function Y(){var i;return/^[\x80-\uFFFF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\x80-\\uFFFF]")),i}function F(){var i;return/^[\x80-\xBF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\x80-\\xBF]")),i}function X(){var i;return i=g(),i===null&&(/^[a-f]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[a-f]"))),i}function U(){var i,e,o;if(o=s,e=w(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,d('"-"')),e===null&&(n.charCodeAt(s)===46?(e=".",s++):(e=null,d('"."')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,d('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,d('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,d('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,d('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,d('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,d(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,d('"~"')))))))))))),e!==null)for(i=[];e!==null;)i.push(e),e=w(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,d('"-"')),e===null&&(n.charCodeAt(s)===46?(e=".",s++):(e=null,d('"."')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,d('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,d('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,d('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,d('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,d('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,d(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,d('"~"'))))))))))));else i=null;return i!==null&&(i=function(u){return n.substring(s,u)}(o)),i===null&&(s=o),i}function k(){var i,e,o;if(o=s,e=w(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,d('"-"')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,d('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,d('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,d('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,d('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,d('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,d(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,d('"~"'))))))))))),e!==null)for(i=[];e!==null;)i.push(e),e=w(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,d('"-"')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,d('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,d('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,d('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,d('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,d('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,d(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,d('"~"')))))))))));else i=null;return i!==null&&(i=function(u){return n.substring(s,u)}(o)),i===null&&(s=o),i}function B(){var i;return n.charCodeAt(s)===40?(i="(",s++):(i=null,d('"("')),i===null&&(n.charCodeAt(s)===41?(i=")",s++):(i=null,d('")"')),i===null&&(n.charCodeAt(s)===60?(i="<",s++):(i=null,d('"<"')),i===null&&(n.charCodeAt(s)===62?(i=">",s++):(i=null,d('">"')),i===null&&(n.charCodeAt(s)===64?(i="@",s++):(i=null,d('"@"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,d('","')),i===null&&(n.charCodeAt(s)===59?(i=";",s++):(i=null,d('";"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,d('":"')),i===null&&(n.charCodeAt(s)===92?(i="\\",s++):(i=null,d('"\\\\"')),i===null&&(i=A(),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,d('"/"')),i===null&&(n.charCodeAt(s)===91?(i="[",s++):(i=null,d('"["')),i===null&&(n.charCodeAt(s)===93?(i="]",s++):(i=null,d('"]"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,d('"?"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,d('"="')),i===null&&(n.charCodeAt(s)===123?(i="{",s++):(i=null,d('"{"')),i===null&&(n.charCodeAt(s)===125?(i="}",s++):(i=null,d('"}"')),i===null&&(i=R(),i===null&&(i=V())))))))))))))))))),i}function He(){var i,e,o;if(o=s,e=w(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,d('"-"')),e===null&&(n.charCodeAt(s)===46?(e=".",s++):(e=null,d('"."')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,d('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,d('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,d('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,d('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,d('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,d(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,d('"~"')),e===null&&(n.charCodeAt(s)===40?(e="(",s++):(e=null,d('"("')),e===null&&(n.charCodeAt(s)===41?(e=")",s++):(e=null,d('")"')),e===null&&(n.charCodeAt(s)===60?(e="<",s++):(e=null,d('"<"')),e===null&&(n.charCodeAt(s)===62?(e=">",s++):(e=null,d('">"')),e===null&&(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e===null&&(n.charCodeAt(s)===92?(e="\\",s++):(e=null,d('"\\\\"')),e===null&&(e=A(),e===null&&(n.charCodeAt(s)===47?(e="/",s++):(e=null,d('"/"')),e===null&&(n.charCodeAt(s)===91?(e="[",s++):(e=null,d('"["')),e===null&&(n.charCodeAt(s)===93?(e="]",s++):(e=null,d('"]"')),e===null&&(n.charCodeAt(s)===63?(e="?",s++):(e=null,d('"?"')),e===null&&(n.charCodeAt(s)===123?(e="{",s++):(e=null,d('"{"')),e===null&&(n.charCodeAt(s)===125?(e="}",s++):(e=null,d('"}"'))))))))))))))))))))))))),e!==null)for(i=[];e!==null;)i.push(e),e=w(),e===null&&(n.charCodeAt(s)===45?(e="-",s++):(e=null,d('"-"')),e===null&&(n.charCodeAt(s)===46?(e=".",s++):(e=null,d('"."')),e===null&&(n.charCodeAt(s)===33?(e="!",s++):(e=null,d('"!"')),e===null&&(n.charCodeAt(s)===37?(e="%",s++):(e=null,d('"%"')),e===null&&(n.charCodeAt(s)===42?(e="*",s++):(e=null,d('"*"')),e===null&&(n.charCodeAt(s)===95?(e="_",s++):(e=null,d('"_"')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"')),e===null&&(n.charCodeAt(s)===96?(e="`",s++):(e=null,d('"`"')),e===null&&(n.charCodeAt(s)===39?(e="'",s++):(e=null,d(`"'"`)),e===null&&(n.charCodeAt(s)===126?(e="~",s++):(e=null,d('"~"')),e===null&&(n.charCodeAt(s)===40?(e="(",s++):(e=null,d('"("')),e===null&&(n.charCodeAt(s)===41?(e=")",s++):(e=null,d('")"')),e===null&&(n.charCodeAt(s)===60?(e="<",s++):(e=null,d('"<"')),e===null&&(n.charCodeAt(s)===62?(e=">",s++):(e=null,d('">"')),e===null&&(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e===null&&(n.charCodeAt(s)===92?(e="\\",s++):(e=null,d('"\\\\"')),e===null&&(e=A(),e===null&&(n.charCodeAt(s)===47?(e="/",s++):(e=null,d('"/"')),e===null&&(n.charCodeAt(s)===91?(e="[",s++):(e=null,d('"["')),e===null&&(n.charCodeAt(s)===93?(e="]",s++):(e=null,d('"]"')),e===null&&(n.charCodeAt(s)===63?(e="?",s++):(e=null,d('"?"')),e===null&&(n.charCodeAt(s)===123?(e="{",s++):(e=null,d('"{"')),e===null&&(n.charCodeAt(s)===125?(e="}",s++):(e=null,d('"}"')))))))))))))))))))))))));else i=null;return i!==null&&(i=function(u){return n.substring(s,u)}(o)),i===null&&(s=o),i}function Q(){var i,e,o,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===42?(e="*",s++):(e=null,d('"*"')),e!==null?(o=P(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"*"}()),i===null&&(s=u),i}function W(){var i,e,o,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===47?(e="/",s++):(e=null,d('"/"')),e!==null?(o=P(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"/"}()),i===null&&(s=u),i}function G(){var i,e,o,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(o=P(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"="}()),i===null&&(s=u),i}function re(){var i,e,o,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===40?(e="(",s++):(e=null,d('"("')),e!==null?(o=P(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"("}()),i===null&&(s=u),i}function _e(){var i,e,o,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===41?(e=")",s++):(e=null,d('")"')),e!==null?(o=P(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return")"}()),i===null&&(s=u),i}function Ie(){var i,e,o,u;return o=s,u=s,n.charCodeAt(s)===62?(i=">",s++):(i=null,d('">"')),i!==null?(e=P(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return">"}()),i===null&&(s=o),i}function ke(){var i,e,o,u;return o=s,u=s,i=P(),i!==null?(n.charCodeAt(s)===60?(e="<",s++):(e=null,d('"<"')),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return"<"}()),i===null&&(s=o),i}function Ae(){var i,e,o,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===44?(e=",",s++):(e=null,d('","')),e!==null?(o=P(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return","}()),i===null&&(s=u),i}function oe(){var i,e,o,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===59?(e=";",s++):(e=null,d('";"')),e!==null?(o=P(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return";"}()),i===null&&(s=u),i}function ye(){var i,e,o,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=P(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return":"}()),i===null&&(s=u),i}function nt(){var i,e,o,u;return o=s,u=s,i=P(),i!==null?(e=A(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return'"'}()),i===null&&(s=o),i}function ot(){var i,e,o,u;return o=s,u=s,i=A(),i!==null?(e=P(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return'"'}()),i===null&&(s=o),i}function Ee(){var i,e,o,u;if(u=s,i=re(),i!==null){for(e=[],o=Ce(),o===null&&(o=ue(),o===null&&(o=Ee()));o!==null;)e.push(o),o=Ce(),o===null&&(o=ue(),o===null&&(o=Ee()));e!==null?(o=_e(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)}else i=null,s=u;return i}function Ce(){var i;return/^[!-']/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[!-']")),i===null&&(/^[*-[]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[*-[]")),i===null&&(/^[\]-~]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\]-~]")),i===null&&(i=Y(),i===null&&(i=pe())))),i}function be(){var i,e,o,u,f,p;if(f=s,p=s,i=P(),i!==null)if(e=A(),e!==null){for(o=[],u=ge(),u===null&&(u=ue());u!==null;)o.push(u),u=ge(),u===null&&(u=ue());o!==null?(u=A(),u!==null?i=[i,e,o,u]:(i=null,s=p)):(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(m){return n.substring(s,m)}(f)),i===null&&(s=f),i}function Oe(){var i,e,o,u,f,p;if(f=s,p=s,i=P(),i!==null)if(e=A(),e!==null){for(o=[],u=ge(),u===null&&(u=ue());u!==null;)o.push(u),u=ge(),u===null&&(u=ue());o!==null?(u=A(),u!==null?i=[i,e,o,u]:(i=null,s=p)):(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(m){var v=n.substring(s,m).trim();return v.substring(1,v.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(f)),i===null&&(s=f),i}function ge(){var i;return i=pe(),i===null&&(n.charCodeAt(s)===33?(i="!",s++):(i=null,d('"!"')),i===null&&(/^[#-[]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[#-[]")),i===null&&(/^[\]-~]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\]-~]")),i===null&&(i=Y())))),i}function ue(){var i,e,o;return o=s,n.charCodeAt(s)===92?(i="\\",s++):(i=null,d('"\\\\"')),i!==null?(/^[\0-\t]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,d("[\\0-\\t]")),e===null&&(/^[\x0B-\f]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,d("[\\x0B-\\f]")),e===null&&(/^[\x0E-]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,d("[\\x0E-]")))),e!==null?i=[i,e]:(i=null,s=o)):(i=null,s=o),i}function me(){var i,e,o,u,f,p;return f=s,p=s,i=Ne(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Lt(),o=o!==null?o:"",o!==null?(u=Ys(),u!==null?i=[i,e,o,u]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i!==null&&(i=function(m){try{b.uri=new Ml(b.scheme,b.user,b.host,b.port),delete b.scheme,delete b.user,delete b.host,delete b.host_type,delete b.port}catch{b=-1}}()),i===null&&(s=f),i}function we(){var i,e,o,u,f,p,m,v;return m=s,v=s,i=Ne(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Lt(),o=o!==null?o:"",o!==null?(u=Ys(),u!==null?(f=vr(),f!==null?(p=wr(),p=p!==null?p:"",p!==null?i=[i,e,o,u,f,p]:(i=null,s=v)):(i=null,s=v)):(i=null,s=v)):(i=null,s=v)):(i=null,s=v)):(i=null,s=v),i!==null&&(i=function(y){try{b.uri=new Ml(b.scheme,b.user,b.host,b.port,b.uri_params,b.uri_headers),delete b.scheme,delete b.user,delete b.host,delete b.host_type,delete b.port,delete b.uri_params,l==="SIP_URI"&&(b=b.uri)}catch{b=-1}}()),i===null&&(s=m),i}function Ne(){var i;return i=Ze(),i===null&&(i=Le()),i}function Ze(){var i,e;return e=s,n.substr(s,4).toLowerCase()==="sips"?(i=n.substr(s,4),s+=4):(i=null,d('"sips"')),i!==null&&(i=function(o,u){b.scheme=u.toLowerCase()}(e,i)),i===null&&(s=e),i}function Le(){var i,e;return e=s,n.substr(s,3).toLowerCase()==="sip"?(i=n.substr(s,3),s+=3):(i=null,d('"sip"')),i!==null&&(i=function(o,u){b.scheme=u.toLowerCase()}(e,i)),i===null&&(s=e),i}function Lt(){var i,e,o,u,f,p;return u=s,f=s,i=ht(),i!==null?(p=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=wn(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?(n.charCodeAt(s)===64?(o="@",s++):(o=null,d('"@"')),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){b.user=decodeURIComponent(n.substring(s-1,m))}(u)),i===null&&(s=u),i}function ht(){var i,e;if(e=x(),e===null&&(e=ve(),e===null&&(e=bn())),e!==null)for(i=[];e!==null;)i.push(e),e=x(),e===null&&(e=ve(),e===null&&(e=bn()));else i=null;return i}function bn(){var i;return n.charCodeAt(s)===38?(i="&",s++):(i=null,d('"&"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,d('"="')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,d('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,d('"$"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,d('","')),i===null&&(n.charCodeAt(s)===59?(i=";",s++):(i=null,d('";"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,d('"?"')),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,d('"/"'))))))))),i}function wn(){var i,e,o;for(o=s,i=[],e=x(),e===null&&(e=ve(),e===null&&(n.charCodeAt(s)===38?(e="&",s++):(e=null,d('"&"')),e===null&&(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"')),e===null&&(n.charCodeAt(s)===36?(e="$",s++):(e=null,d('"$"')),e===null&&(n.charCodeAt(s)===44?(e=",",s++):(e=null,d('","'))))))));e!==null;)i.push(e),e=x(),e===null&&(e=ve(),e===null&&(n.charCodeAt(s)===38?(e="&",s++):(e=null,d('"&"')),e===null&&(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"')),e===null&&(n.charCodeAt(s)===36?(e="$",s++):(e=null,d('"$"')),e===null&&(n.charCodeAt(s)===44?(e=",",s++):(e=null,d('","'))))))));return i!==null&&(i=function(u){b.password=n.substring(s,u)}(o)),i===null&&(s=o),i}function Ys(){var i,e,o,u,f;return u=s,i=es(),i!==null?(f=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=As(),o!==null?e=[e,o]:(e=null,s=f)):(e=null,s=f),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i}function es(){var i,e;return e=s,i=us(),i===null&&(i=at(),i===null&&(i=Dn())),i!==null&&(i=function(o){return b.host=n.substring(s,o).toLowerCase(),b.host}(e)),i===null&&(s=e),i}function us(){var i,e,o,u,f,p;for(u=s,f=s,i=[],p=s,e=Js(),e!==null?(n.charCodeAt(s)===46?(o=".",s++):(o=null,d('"."')),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p);e!==null;)i.push(e),p=s,e=Js(),e!==null?(n.charCodeAt(s)===46?(o=".",s++):(o=null,d('"."')),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p);return i!==null?(e=On(),e!==null?(n.charCodeAt(s)===46?(o=".",s++):(o=null,d('"."')),o=o!==null?o:"",o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){return b.host_type="domain",n.substring(s,m)}(u)),i===null&&(s=u),i}function Js(){var i,e,o,u;if(u=s,i=w(),i!==null){for(e=[],o=w(),o===null&&(n.charCodeAt(s)===45?(o="-",s++):(o=null,d('"-"')),o===null&&(n.charCodeAt(s)===95?(o="_",s++):(o=null,d('"_"'))));o!==null;)e.push(o),o=w(),o===null&&(n.charCodeAt(s)===45?(o="-",s++):(o=null,d('"-"')),o===null&&(n.charCodeAt(s)===95?(o="_",s++):(o=null,d('"_"'))));e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function On(){var i,e,o,u;if(u=s,i=T(),i!==null){for(e=[],o=w(),o===null&&(n.charCodeAt(s)===45?(o="-",s++):(o=null,d('"-"')),o===null&&(n.charCodeAt(s)===95?(o="_",s++):(o=null,d('"_"'))));o!==null;)e.push(o),o=w(),o===null&&(n.charCodeAt(s)===45?(o="-",s++):(o=null,d('"-"')),o===null&&(n.charCodeAt(s)===95?(o="_",s++):(o=null,d('"_"'))));e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function Dn(){var i,e,o,u,f;return u=s,f=s,n.charCodeAt(s)===91?(i="[",s++):(i=null,d('"["')),i!==null?(e=zs(),e!==null?(n.charCodeAt(s)===93?(o="]",s++):(o=null,d('"]"')),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return b.host_type="IPv6",n.substring(s,p)}(u)),i===null&&(s=u),i}function zs(){var i,e,o,u,f,p,m,v,y,D,ie,xe,wt,Ps,L,I;return Ps=s,L=s,i=Te(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?(n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?(n.charCodeAt(s)===58?(p=":",s++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?(n.charCodeAt(s)===58?(v=":",s++):(v=null,d('":"')),v!==null?(y=Te(),y!==null?(n.charCodeAt(s)===58?(D=":",s++):(D=null,d('":"')),D!==null?(ie=Te(),ie!==null?(n.charCodeAt(s)===58?(xe=":",s++):(xe=null,d('":"')),xe!==null?(wt=ae(),wt!==null?i=[i,e,o,u,f,p,m,v,y,D,ie,xe,wt]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,d('"::"')),i!==null?(e=Te(),e!==null?(n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,d('":"')),m!==null?(v=Te(),v!==null?(n.charCodeAt(s)===58?(y=":",s++):(y=null,d('":"')),y!==null?(D=Te(),D!==null?(n.charCodeAt(s)===58?(ie=":",s++):(ie=null,d('":"')),ie!==null?(xe=ae(),xe!==null?i=[i,e,o,u,f,p,m,v,y,D,ie,xe]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,d('"::"')),i!==null?(e=Te(),e!==null?(n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,d('":"')),m!==null?(v=Te(),v!==null?(n.charCodeAt(s)===58?(y=":",s++):(y=null,d('":"')),y!==null?(D=ae(),D!==null?i=[i,e,o,u,f,p,m,v,y,D]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,d('"::"')),i!==null?(e=Te(),e!==null?(n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,d('":"')),m!==null?(v=ae(),v!==null?i=[i,e,o,u,f,p,m,v]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,d('"::"')),i!==null?(e=Te(),e!==null?(n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=ae(),p!==null?i=[i,e,o,u,f,p]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,d('"::"')),i!==null?(e=Te(),e!==null?(n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=ae(),u!==null?i=[i,e,o,u]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,d('"::"')),i!==null?(e=ae(),e!==null?i=[i,e]:(i=null,s=L)):(i=null,s=L),i===null&&(L=s,n.substr(s,2)==="::"?(i="::",s+=2):(i=null,d('"::"')),i!==null?(e=Te(),e!==null?i=[i,e]:(i=null,s=L)):(i=null,s=L),i===null&&(L=s,i=Te(),i!==null?(n.substr(s,2)==="::"?(e="::",s+=2):(e=null,d('"::"')),e!==null?(o=Te(),o!==null?(n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?(n.charCodeAt(s)===58?(p=":",s++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?(n.charCodeAt(s)===58?(v=":",s++):(v=null,d('":"')),v!==null?(y=Te(),y!==null?(n.charCodeAt(s)===58?(D=":",s++):(D=null,d('":"')),D!==null?(ie=ae(),ie!==null?i=[i,e,o,u,f,p,m,v,y,D,ie]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,i=Te(),i!==null?(I=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,s=I)):(e=null,s=I),e=e!==null?e:"",e!==null?(n.substr(s,2)==="::"?(o="::",s+=2):(o=null,d('"::"')),o!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,d('":"')),m!==null?(v=Te(),v!==null?(n.charCodeAt(s)===58?(y=":",s++):(y=null,d('":"')),y!==null?(D=ae(),D!==null?i=[i,e,o,u,f,p,m,v,y,D]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,i=Te(),i!==null?(I=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,s=I)):(e=null,s=I),e=e!==null?e:"",e!==null?(I=s,n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,s=I)):(o=null,s=I),o=o!==null?o:"",o!==null?(n.substr(s,2)==="::"?(u="::",s+=2):(u=null,d('"::"')),u!==null?(f=Te(),f!==null?(n.charCodeAt(s)===58?(p=":",s++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?(n.charCodeAt(s)===58?(v=":",s++):(v=null,d('":"')),v!==null?(y=ae(),y!==null?i=[i,e,o,u,f,p,m,v,y]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,i=Te(),i!==null?(I=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,s=I)):(e=null,s=I),e=e!==null?e:"",e!==null?(I=s,n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,s=I)):(o=null,s=I),o=o!==null?o:"",o!==null?(I=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=I)):(u=null,s=I),u=u!==null?u:"",u!==null?(n.substr(s,2)==="::"?(f="::",s+=2):(f=null,d('"::"')),f!==null?(p=Te(),p!==null?(n.charCodeAt(s)===58?(m=":",s++):(m=null,d('":"')),m!==null?(v=ae(),v!==null?i=[i,e,o,u,f,p,m,v]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,i=Te(),i!==null?(I=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,s=I)):(e=null,s=I),e=e!==null?e:"",e!==null?(I=s,n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,s=I)):(o=null,s=I),o=o!==null?o:"",o!==null?(I=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=I)):(u=null,s=I),u=u!==null?u:"",u!==null?(I=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,s=I)):(f=null,s=I),f=f!==null?f:"",f!==null?(n.substr(s,2)==="::"?(p="::",s+=2):(p=null,d('"::"')),p!==null?(m=ae(),m!==null?i=[i,e,o,u,f,p,m]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,i=Te(),i!==null?(I=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,s=I)):(e=null,s=I),e=e!==null?e:"",e!==null?(I=s,n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,s=I)):(o=null,s=I),o=o!==null?o:"",o!==null?(I=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=I)):(u=null,s=I),u=u!==null?u:"",u!==null?(I=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,s=I)):(f=null,s=I),f=f!==null?f:"",f!==null?(I=s,n.charCodeAt(s)===58?(p=":",s++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?p=[p,m]:(p=null,s=I)):(p=null,s=I),p=p!==null?p:"",p!==null?(n.substr(s,2)==="::"?(m="::",s+=2):(m=null,d('"::"')),m!==null?(v=Te(),v!==null?i=[i,e,o,u,f,p,m,v]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L),i===null&&(L=s,i=Te(),i!==null?(I=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,s=I)):(e=null,s=I),e=e!==null?e:"",e!==null?(I=s,n.charCodeAt(s)===58?(o=":",s++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,s=I)):(o=null,s=I),o=o!==null?o:"",o!==null?(I=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=I)):(u=null,s=I),u=u!==null?u:"",u!==null?(I=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,s=I)):(f=null,s=I),f=f!==null?f:"",f!==null?(I=s,n.charCodeAt(s)===58?(p=":",s++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?p=[p,m]:(p=null,s=I)):(p=null,s=I),p=p!==null?p:"",p!==null?(I=s,n.charCodeAt(s)===58?(m=":",s++):(m=null,d('":"')),m!==null?(v=Te(),v!==null?m=[m,v]:(m=null,s=I)):(m=null,s=I),m=m!==null?m:"",m!==null?(n.substr(s,2)==="::"?(v="::",s+=2):(v=null,d('"::"')),v!==null?i=[i,e,o,u,f,p,m,v]:(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L)):(i=null,s=L))))))))))))))),i!==null&&(i=function(Se){return b.host_type="IPv6",n.substring(s,Se)}(Ps)),i===null&&(s=Ps),i}function Te(){var i,e,o,u,f;return f=s,i=S(),i!==null?(e=S(),e=e!==null?e:"",e!==null?(o=S(),o=o!==null?o:"",o!==null?(u=S(),u=u!==null?u:"",u!==null?i=[i,e,o,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function ae(){var i,e,o,u;return u=s,i=Te(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i===null&&(i=at()),i}function at(){var i,e,o,u,f,p,m,v,y;return v=s,y=s,i=Wt(),i!==null?(n.charCodeAt(s)===46?(e=".",s++):(e=null,d('"."')),e!==null?(o=Wt(),o!==null?(n.charCodeAt(s)===46?(u=".",s++):(u=null,d('"."')),u!==null?(f=Wt(),f!==null?(n.charCodeAt(s)===46?(p=".",s++):(p=null,d('"."')),p!==null?(m=Wt(),m!==null?i=[i,e,o,u,f,p,m]:(i=null,s=y)):(i=null,s=y)):(i=null,s=y)):(i=null,s=y)):(i=null,s=y)):(i=null,s=y)):(i=null,s=y),i!==null&&(i=function(D){return b.host_type="IPv4",n.substring(s,D)}(v)),i===null&&(s=v),i}function Wt(){var i,e,o,u;return u=s,n.substr(s,2)==="25"?(i="25",s+=2):(i=null,d('"25"')),i!==null?(/^[0-5]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,d("[0-5]")),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i===null&&(u=s,n.charCodeAt(s)===50?(i="2",s++):(i=null,d('"2"')),i!==null?(/^[0-4]/.test(n.charAt(s))?(e=n.charAt(s),s++):(e=null,d("[0-4]")),e!==null?(o=g(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i===null&&(u=s,n.charCodeAt(s)===49?(i="1",s++):(i=null,d('"1"')),i!==null?(e=g(),e!==null?(o=g(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i===null&&(u=s,/^[1-9]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[1-9]")),i!==null?(e=g(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i===null&&(i=g())))),i}function As(){var i,e,o,u,f,p,m;return p=s,m=s,i=g(),i=i!==null?i:"",i!==null?(e=g(),e=e!==null?e:"",e!==null?(o=g(),o=o!==null?o:"",o!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?i=[i,e,o,u,f]:(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m),i!==null&&(i=function(v,y){return y=parseInt(y.join("")),b.port=y,y}(p,i)),i===null&&(s=p),i}function vr(){var i,e,o,u;for(i=[],u=s,n.charCodeAt(s)===59?(e=";",s++):(e=null,d('";"')),e!==null?(o=Nn(),o!==null?e=[e,o]:(e=null,s=u)):(e=null,s=u);e!==null;)i.push(e),u=s,n.charCodeAt(s)===59?(e=";",s++):(e=null,d('";"')),e!==null?(o=Nn(),o!==null?e=[e,o]:(e=null,s=u)):(e=null,s=u);return i}function Nn(){var i;return i=xn(),i===null&&(i=Sr(),i===null&&(i=Er(),i===null&&(i=yr(),i===null&&(i=Cr(),i===null&&(i=Ar(),i===null&&(i=Rr())))))),i}function xn(){var i,e,o,u;return o=s,u=s,n.substr(s,10).toLowerCase()==="transport="?(i=n.substr(s,10),s+=10):(i=null,d('"transport="')),i!==null?(n.substr(s,3).toLowerCase()==="udp"?(e=n.substr(s,3),s+=3):(e=null,d('"udp"')),e===null&&(n.substr(s,3).toLowerCase()==="tcp"?(e=n.substr(s,3),s+=3):(e=null,d('"tcp"')),e===null&&(n.substr(s,4).toLowerCase()==="sctp"?(e=n.substr(s,4),s+=4):(e=null,d('"sctp"')),e===null&&(n.substr(s,3).toLowerCase()==="tls"?(e=n.substr(s,3),s+=3):(e=null,d('"tls"')),e===null&&(e=U())))),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.uri_params||(b.uri_params={}),b.uri_params.transport=p.toLowerCase()}(o,i[1])),i===null&&(s=o),i}function Sr(){var i,e,o,u;return o=s,u=s,n.substr(s,5).toLowerCase()==="user="?(i=n.substr(s,5),s+=5):(i=null,d('"user="')),i!==null?(n.substr(s,5).toLowerCase()==="phone"?(e=n.substr(s,5),s+=5):(e=null,d('"phone"')),e===null&&(n.substr(s,2).toLowerCase()==="ip"?(e=n.substr(s,2),s+=2):(e=null,d('"ip"')),e===null&&(e=U())),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.uri_params||(b.uri_params={}),b.uri_params.user=p.toLowerCase()}(o,i[1])),i===null&&(s=o),i}function Er(){var i,e,o,u;return o=s,u=s,n.substr(s,7).toLowerCase()==="method="?(i=n.substr(s,7),s+=7):(i=null,d('"method="')),i!==null?(e=nn(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.uri_params||(b.uri_params={}),b.uri_params.method=p}(o,i[1])),i===null&&(s=o),i}function yr(){var i,e,o,u;return o=s,u=s,n.substr(s,4).toLowerCase()==="ttl="?(i=n.substr(s,4),s+=4):(i=null,d('"ttl="')),i!==null?(e=er(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.params||(b.params={}),b.params.ttl=p}(o,i[1])),i===null&&(s=o),i}function Cr(){var i,e,o,u;return o=s,u=s,n.substr(s,6).toLowerCase()==="maddr="?(i=n.substr(s,6),s+=6):(i=null,d('"maddr="')),i!==null?(e=es(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){b.uri_params||(b.uri_params={}),b.uri_params.maddr=p}(o,i[1])),i===null&&(s=o),i}function Ar(){var i,e,o,u,f,p;return u=s,f=s,n.substr(s,2).toLowerCase()==="lr"?(i=n.substr(s,2),s+=2):(i=null,d('"lr"')),i!==null?(p=s,n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(o=U(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){b.uri_params||(b.uri_params={}),b.uri_params.lr=void 0}()),i===null&&(s=u),i}function Rr(){var i,e,o,u,f,p;return u=s,f=s,i=Ir(),i!==null?(p=s,n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(o=br(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m,v,y){b.uri_params||(b.uri_params={}),typeof y>"u"?y=void 0:y=y[1],b.uri_params[v.toLowerCase()]=y}(u,i[0],i[1])),i===null&&(s=u),i}function Ir(){var i,e,o;if(o=s,e=Rs(),e!==null)for(i=[];e!==null;)i.push(e),e=Rs();else i=null;return i!==null&&(i=function(u,f){return f.join("")}(o,i)),i===null&&(s=o),i}function br(){var i,e,o;if(o=s,e=Rs(),e!==null)for(i=[];e!==null;)i.push(e),e=Rs();else i=null;return i!==null&&(i=function(u,f){return f.join("")}(o,i)),i===null&&(s=o),i}function Rs(){var i;return i=Is(),i===null&&(i=x(),i===null&&(i=ve())),i}function Is(){var i;return n.charCodeAt(s)===91?(i="[",s++):(i=null,d('"["')),i===null&&(n.charCodeAt(s)===93?(i="]",s++):(i=null,d('"]"')),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,d('"/"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,d('":"')),i===null&&(n.charCodeAt(s)===38?(i="&",s++):(i=null,d('"&"')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,d('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,d('"$"')))))))),i}function wr(){var i,e,o,u,f,p,m;if(p=s,n.charCodeAt(s)===63?(i="?",s++):(i=null,d('"?"')),i!==null)if(e=Xs(),e!==null){for(o=[],m=s,n.charCodeAt(s)===38?(u="&",s++):(u=null,d('"&"')),u!==null?(f=Xs(),f!==null?u=[u,f]:(u=null,s=m)):(u=null,s=m);u!==null;)o.push(u),m=s,n.charCodeAt(s)===38?(u="&",s++):(u=null,d('"&"')),u!==null?(f=Xs(),f!==null?u=[u,f]:(u=null,s=m)):(u=null,s=m);o!==null?i=[i,e,o]:(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i}function Xs(){var i,e,o,u,f;return u=s,f=s,i=Qs(),i!==null?(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(o=Or(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m,v){m=m.join("").toLowerCase(),v=v.join(""),b.uri_headers||(b.uri_headers={}),b.uri_headers[m]?b.uri_headers[m].push(v):b.uri_headers[m]=[v]}(u,i[0],i[2])),i===null&&(s=u),i}function Qs(){var i,e;if(e=bs(),e===null&&(e=x(),e===null&&(e=ve())),e!==null)for(i=[];e!==null;)i.push(e),e=bs(),e===null&&(e=x(),e===null&&(e=ve()));else i=null;return i}function Or(){var i,e;for(i=[],e=bs(),e===null&&(e=x(),e===null&&(e=ve()));e!==null;)i.push(e),e=bs(),e===null&&(e=x(),e===null&&(e=ve()));return i}function bs(){var i;return n.charCodeAt(s)===91?(i="[",s++):(i=null,d('"["')),i===null&&(n.charCodeAt(s)===93?(i="]",s++):(i=null,d('"]"')),i===null&&(n.charCodeAt(s)===47?(i="/",s++):(i=null,d('"/"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,d('"?"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,d('":"')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,d('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,d('"$"')))))))),i}function Zs(){var i;return i=rn(),i===null&&(i=ml()),i}function ml(){var i,e,o,u,f,p;return p=s,i=nn(),i!==null?(e=R(),e!==null?(o=Dr(),o!==null?(u=R(),u!==null?(f=Pn(),f!==null?i=[i,e,o,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function Dr(){var i;return i=we(),i===null&&(i=Un()),i}function Un(){var i,e,o,u;return u=s,i=Ns(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(o=kn(),o===null&&(o=tn()),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function kn(){var i,e,o,u,f;return u=s,i=Nr(),i===null&&(i=en()),i!==null?(f=s,n.charCodeAt(s)===63?(e="?",s++):(e=null,d('"?"')),e!==null?(o=Mr(),o!==null?e=[e,o]:(e=null,s=f)):(e=null,s=f),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i}function Nr(){var i,e,o,u;return u=s,n.substr(s,2)==="//"?(i="//",s+=2):(i=null,d('"//"')),i!==null?(e=Ur(),e!==null?(o=en(),o=o!==null?o:"",o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function en(){var i,e,o;return o=s,n.charCodeAt(s)===47?(i="/",s++):(i=null,d('"/"')),i!==null?(e=xr(),e!==null?i=[i,e]:(i=null,s=o)):(i=null,s=o),i}function tn(){var i,e,o,u;if(u=s,i=Os(),i!==null){for(e=[],o=ws();o!==null;)e.push(o),o=ws();e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function ws(){var i;return i=le(),i===null&&(i=x(),i===null&&(i=ve())),i}function Os(){var i;return i=x(),i===null&&(i=ve(),i===null&&(n.charCodeAt(s)===59?(i=";",s++):(i=null,d('";"')),i===null&&(n.charCodeAt(s)===63?(i="?",s++):(i=null,d('"?"')),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,d('":"')),i===null&&(n.charCodeAt(s)===64?(i="@",s++):(i=null,d('"@"')),i===null&&(n.charCodeAt(s)===38?(i="&",s++):(i=null,d('"&"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,d('"="')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,d('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,d('"$"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,d('","')))))))))))),i}function xr(){var i,e,o,u,f,p;if(f=s,i=sn(),i!==null){for(e=[],p=s,n.charCodeAt(s)===47?(o="/",s++):(o=null,d('"/"')),o!==null?(u=sn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,n.charCodeAt(s)===47?(o="/",s++):(o=null,d('"/"')),o!==null?(u=sn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function sn(){var i,e,o,u,f,p;for(f=s,i=[],e=cs();e!==null;)i.push(e),e=cs();if(i!==null){for(e=[],p=s,n.charCodeAt(s)===59?(o=";",s++):(o=null,d('";"')),o!==null?(u=Ds(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,n.charCodeAt(s)===59?(o=";",s++):(o=null,d('";"')),o!==null?(u=Ds(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Ds(){var i,e;for(i=[],e=cs();e!==null;)i.push(e),e=cs();return i}function cs(){var i;return i=x(),i===null&&(i=ve(),i===null&&(n.charCodeAt(s)===58?(i=":",s++):(i=null,d('":"')),i===null&&(n.charCodeAt(s)===64?(i="@",s++):(i=null,d('"@"')),i===null&&(n.charCodeAt(s)===38?(i="&",s++):(i=null,d('"&"')),i===null&&(n.charCodeAt(s)===61?(i="=",s++):(i=null,d('"="')),i===null&&(n.charCodeAt(s)===43?(i="+",s++):(i=null,d('"+"')),i===null&&(n.charCodeAt(s)===36?(i="$",s++):(i=null,d('"$"')),i===null&&(n.charCodeAt(s)===44?(i=",",s++):(i=null,d('","')))))))))),i}function Ns(){var i,e,o,u,f;if(u=s,f=s,i=T(),i!==null){for(e=[],o=T(),o===null&&(o=g(),o===null&&(n.charCodeAt(s)===43?(o="+",s++):(o=null,d('"+"')),o===null&&(n.charCodeAt(s)===45?(o="-",s++):(o=null,d('"-"')),o===null&&(n.charCodeAt(s)===46?(o=".",s++):(o=null,d('"."'))))));o!==null;)e.push(o),o=T(),o===null&&(o=g(),o===null&&(n.charCodeAt(s)===43?(o="+",s++):(o=null,d('"+"')),o===null&&(n.charCodeAt(s)===45?(o="-",s++):(o=null,d('"-"')),o===null&&(n.charCodeAt(s)===46?(o=".",s++):(o=null,d('"."'))))));e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i!==null&&(i=function(p){b.scheme=n.substring(s,p)}(u)),i===null&&(s=u),i}function Ur(){var i;return i=kr(),i===null&&(i=Pr()),i}function kr(){var i,e,o,u;return o=s,u=s,i=Lt(),i!==null?(n.charCodeAt(s)===64?(e="@",s++):(e=null,d('"@"')),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i=i!==null?i:"",i!==null?(e=Ys(),e!==null?i=[i,e]:(i=null,s=o)):(i=null,s=o),i=i!==null?i:"",i}function Pr(){var i,e;if(e=x(),e===null&&(e=ve(),e===null&&(n.charCodeAt(s)===36?(e="$",s++):(e=null,d('"$"')),e===null&&(n.charCodeAt(s)===44?(e=",",s++):(e=null,d('","')),e===null&&(n.charCodeAt(s)===59?(e=";",s++):(e=null,d('";"')),e===null&&(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e===null&&(n.charCodeAt(s)===64?(e="@",s++):(e=null,d('"@"')),e===null&&(n.charCodeAt(s)===38?(e="&",s++):(e=null,d('"&"')),e===null&&(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"'))))))))))),e!==null)for(i=[];e!==null;)i.push(e),e=x(),e===null&&(e=ve(),e===null&&(n.charCodeAt(s)===36?(e="$",s++):(e=null,d('"$"')),e===null&&(n.charCodeAt(s)===44?(e=",",s++):(e=null,d('","')),e===null&&(n.charCodeAt(s)===59?(e=";",s++):(e=null,d('";"')),e===null&&(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e===null&&(n.charCodeAt(s)===64?(e="@",s++):(e=null,d('"@"')),e===null&&(n.charCodeAt(s)===38?(e="&",s++):(e=null,d('"&"')),e===null&&(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e===null&&(n.charCodeAt(s)===43?(e="+",s++):(e=null,d('"+"')))))))))));else i=null;return i}function Mr(){var i,e;for(i=[],e=ws();e!==null;)i.push(e),e=ws();return i}function Pn(){var i,e,o,u,f,p,m,v;if(m=s,v=s,n.substr(s,3).toLowerCase()==="sip"?(i=n.substr(s,3),s+=3):(i=null,d('"SIP"')),i!==null)if(n.charCodeAt(s)===47?(e="/",s++):(e=null,d('"/"')),e!==null){if(u=g(),u!==null)for(o=[];u!==null;)o.push(u),u=g();else o=null;if(o!==null)if(n.charCodeAt(s)===46?(u=".",s++):(u=null,d('"."')),u!==null){if(p=g(),p!==null)for(f=[];p!==null;)f.push(p),p=g();else f=null;f!==null?i=[i,e,o,u,f]:(i=null,s=v)}else i=null,s=v;else i=null,s=v}else i=null,s=v;else i=null,s=v;return i!==null&&(i=function(y){b.sip_version=n.substring(s,y)}(m)),i===null&&(s=m),i}function Mn(){var i;return n.substr(s,6)==="INVITE"?(i="INVITE",s+=6):(i=null,d('"INVITE"')),i}function Lr(){var i;return n.substr(s,3)==="ACK"?(i="ACK",s+=3):(i=null,d('"ACK"')),i}function $r(){var i;return n.substr(s,7)==="OPTIONS"?(i="OPTIONS",s+=7):(i=null,d('"OPTIONS"')),i}function Hr(){var i;return n.substr(s,3)==="BYE"?(i="BYE",s+=3):(i=null,d('"BYE"')),i}function Fr(){var i;return n.substr(s,6)==="CANCEL"?(i="CANCEL",s+=6):(i=null,d('"CANCEL"')),i}function Vr(){var i;return n.substr(s,8)==="REGISTER"?(i="REGISTER",s+=8):(i=null,d('"REGISTER"')),i}function jr(){var i;return n.substr(s,9)==="SUBSCRIBE"?(i="SUBSCRIBE",s+=9):(i=null,d('"SUBSCRIBE"')),i}function qr(){var i;return n.substr(s,6)==="NOTIFY"?(i="NOTIFY",s+=6):(i=null,d('"NOTIFY"')),i}function Br(){var i;return n.substr(s,5)==="REFER"?(i="REFER",s+=5):(i=null,d('"REFER"')),i}function nn(){var i,e;return e=s,i=Mn(),i===null&&(i=Lr(),i===null&&(i=$r(),i===null&&(i=Hr(),i===null&&(i=Fr(),i===null&&(i=Vr(),i===null&&(i=jr(),i===null&&(i=qr(),i===null&&(i=Br(),i===null&&(i=U()))))))))),i!==null&&(i=function(o){return b.method=n.substring(s,o),b.method}(e)),i===null&&(s=e),i}function rn(){var i,e,o,u,f,p;return p=s,i=Pn(),i!==null?(e=R(),e!==null?(o=Gr(),o!==null?(u=R(),u!==null?(f=Kr(),f!==null?i=[i,e,o,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function Gr(){var i,e;return e=s,i=Wr(),i!==null&&(i=function(o,u){b.status_code=parseInt(u.join(""))}(e,i)),i===null&&(s=e),i}function Wr(){var i,e,o,u;return u=s,i=g(),i!==null?(e=g(),e!==null?(o=g(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Kr(){var i,e,o;for(o=s,i=[],e=le(),e===null&&(e=x(),e===null&&(e=ve(),e===null&&(e=Y(),e===null&&(e=F(),e===null&&(e=R(),e===null&&(e=V()))))));e!==null;)i.push(e),e=le(),e===null&&(e=x(),e===null&&(e=ve(),e===null&&(e=Y(),e===null&&(e=F(),e===null&&(e=R(),e===null&&(e=V()))))));return i!==null&&(i=function(u){b.reason_phrase=n.substring(s,u)}(o)),i===null&&(s=o),i}function gl(){var i,e,o,u,f,p;if(f=s,i=an(),i!==null){for(e=[],p=s,o=Ae(),o!==null?(u=an(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=Ae(),o!==null?(u=an(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Jo(){var i,e,o,u,f,p;return u=s,f=s,i=He(),i!==null?(p=s,n.charCodeAt(s)===64?(e="@",s++):(e=null,d('"@"')),e!==null?(o=He(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){b=n.substring(s,m)}(u)),i===null&&(s=u),i}function zo(){var i,e,o,u,f,p,m;if(f=s,i=Q(),i===null)if(p=s,i=Ln(),i!==null){for(e=[],m=s,o=Ae(),o!==null?(u=Ln(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=Ae(),o!==null?(u=Ln(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y,D;for(D=b.multi_header.length,y=0;y<D;y++)if(b.multi_header[y].parsed===null){b=null;break}b!==null?b=b.multi_header:b=-1}()),i===null&&(s=f),i}function Ln(){var i,e,o,u,f,p,m;if(f=s,p=s,i=me(),i===null&&(i=$t()),i!==null){for(e=[],m=s,o=oe(),o!==null?(u=xs(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=oe(),o!==null?(u=xs(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y;b.multi_header||(b.multi_header=[]);try{y=new fs(b.uri,b.display_name,b.params),delete b.uri,delete b.display_name,delete b.params}catch{y=null}b.multi_header.push({possition:s,offset:v,parsed:y})}(f)),i===null&&(s=f),i}function $t(){var i,e,o,u,f;return f=s,i=Ht(),i=i!==null?i:"",i!==null?(e=ke(),e!==null?(o=we(),o!==null?(u=Ie(),u!==null?i=[i,e,o,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function Ht(){var i,e,o,u,f,p,m;if(f=s,p=s,i=U(),i!==null){for(e=[],m=s,o=pe(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=pe(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i===null&&(i=Oe()),i!==null&&(i=function(v,y){typeof y=="string"?b.display_name=y:b.display_name=y[1].reduce(function(D,ie){return D+ie[0]+ie[1]},y[0])}(f,i)),i===null&&(s=f),i}function xs(){var i;return i=$n(),i===null&&(i=Yr(),i===null&&(i=We())),i}function $n(){var i,e,o,u,f;return u=s,f=s,n.substr(s,1).toLowerCase()==="q"?(i=n.substr(s,1),s++):(i=null,d('"q"')),i!==null?(e=G(),e!==null?(o=ss(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.params||(b.params={}),b.params.q=m}(u,i[2])),i===null&&(s=u),i}function Yr(){var i,e,o,u,f;return u=s,f=s,n.substr(s,7).toLowerCase()==="expires"?(i=n.substr(s,7),s+=7):(i=null,d('"expires"')),i!==null?(e=G(),e!==null?(o=ts(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.params||(b.params={}),b.params.expires=m}(u,i[2])),i===null&&(s=u),i}function ts(){var i,e,o;if(o=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){return parseInt(f.join(""))}(o,i)),i===null&&(s=o),i}function ss(){var i,e,o,u,f,p,m,v;return p=s,m=s,n.charCodeAt(s)===48?(i="0",s++):(i=null,d('"0"')),i!==null?(v=s,n.charCodeAt(s)===46?(e=".",s++):(e=null,d('"."')),e!==null?(o=g(),o=o!==null?o:"",o!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?e=[e,o,u,f]:(e=null,s=v)):(e=null,s=v)):(e=null,s=v)):(e=null,s=v),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=m)):(i=null,s=m),i!==null&&(i=function(y){return parseFloat(n.substring(s,y))}(p)),i===null&&(s=p),i}function We(){var i,e,o,u,f,p;return u=s,f=s,i=U(),i!==null?(p=s,e=G(),e!==null?(o=Ke(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m,v,y){b.params||(b.params={}),typeof y>"u"?y=void 0:y=y[1],b.params[v.toLowerCase()]=y}(u,i[0],i[1])),i===null&&(s=u),i}function Ke(){var i;return i=U(),i===null&&(i=es(),i===null&&(i=be())),i}function Tl(){var i,e,o,u,f,p;if(f=s,i=vl(),i!==null){for(e=[],p=s,o=oe(),o!==null?(u=Hn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=oe(),o!==null?(u=Hn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function vl(){var i;return n.substr(s,6).toLowerCase()==="render"?(i=n.substr(s,6),s+=6):(i=null,d('"render"')),i===null&&(n.substr(s,7).toLowerCase()==="session"?(i=n.substr(s,7),s+=7):(i=null,d('"session"')),i===null&&(n.substr(s,4).toLowerCase()==="icon"?(i=n.substr(s,4),s+=4):(i=null,d('"icon"')),i===null&&(n.substr(s,5).toLowerCase()==="alert"?(i=n.substr(s,5),s+=5):(i=null,d('"alert"')),i===null&&(i=U())))),i}function Hn(){var i;return i=Fn(),i===null&&(i=We()),i}function Fn(){var i,e,o,u;return u=s,n.substr(s,8).toLowerCase()==="handling"?(i=n.substr(s,8),s+=8):(i=null,d('"handling"')),i!==null?(e=G(),e!==null?(n.substr(s,8).toLowerCase()==="optional"?(o=n.substr(s,8),s+=8):(o=null,d('"optional"')),o===null&&(n.substr(s,8).toLowerCase()==="required"?(o=n.substr(s,8),s+=8):(o=null,d('"required"')),o===null&&(o=U())),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Sl(){var i,e,o,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,o=Ae(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=Ae(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Xo(){var i,e,o;if(o=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){b=parseInt(f.join(""))}(o,i)),i===null&&(s=o),i}function Qo(){var i,e;return e=s,i=El(),i!==null&&(i=function(o){b=n.substring(s,o)}(e)),i===null&&(s=e),i}function El(){var i,e,o,u,f,p,m,v;if(m=s,i=Jr(),i!==null)if(e=W(),e!==null)if(o=Qr(),o!==null){for(u=[],v=s,f=oe(),f!==null?(p=Vn(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);f!==null;)u.push(f),v=s,f=oe(),f!==null?(p=Vn(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,o,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i}function Jr(){var i;return i=zr(),i===null&&(i=Xr()),i}function zr(){var i;return n.substr(s,4).toLowerCase()==="text"?(i=n.substr(s,4),s+=4):(i=null,d('"text"')),i===null&&(n.substr(s,5).toLowerCase()==="image"?(i=n.substr(s,5),s+=5):(i=null,d('"image"')),i===null&&(n.substr(s,5).toLowerCase()==="audio"?(i=n.substr(s,5),s+=5):(i=null,d('"audio"')),i===null&&(n.substr(s,5).toLowerCase()==="video"?(i=n.substr(s,5),s+=5):(i=null,d('"video"')),i===null&&(n.substr(s,11).toLowerCase()==="application"?(i=n.substr(s,11),s+=11):(i=null,d('"application"')),i===null&&(i=ln()))))),i}function Xr(){var i;return n.substr(s,7).toLowerCase()==="message"?(i=n.substr(s,7),s+=7):(i=null,d('"message"')),i===null&&(n.substr(s,9).toLowerCase()==="multipart"?(i=n.substr(s,9),s+=9):(i=null,d('"multipart"')),i===null&&(i=ln())),i}function ln(){var i;return i=U(),i===null&&(i=on()),i}function on(){var i,e,o;return o=s,n.substr(s,2).toLowerCase()==="x-"?(i=n.substr(s,2),s+=2):(i=null,d('"x-"')),i!==null?(e=U(),e!==null?i=[i,e]:(i=null,s=o)):(i=null,s=o),i}function Qr(){var i;return i=ln(),i===null&&(i=U()),i}function Vn(){var i,e,o,u;return u=s,i=U(),i!==null?(e=G(),e!==null?(o=jn(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function jn(){var i;return i=U(),i===null&&(i=be()),i}function yl(){var i,e,o,u;return u=s,i=Cl(),i!==null?(e=pe(),e!==null?(o=nn(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Cl(){var i,e,o;if(o=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){b.value=parseInt(f.join(""))}(o,i)),i===null&&(s=o),i}function Al(){var i,e;return e=s,i=ts(),i!==null&&(i=function(o,u){b=u}(e,i)),i===null&&(s=e),i}function Zo(){var i,e,o,u,f,p,m;if(f=s,p=s,i=an(),i!==null){for(e=[],m=s,o=oe(),o!==null?(u=We(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=oe(),o!==null?(u=We(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v,y){b.event=y.join("").toLowerCase()}(f,i[0])),i===null&&(s=f),i}function an(){var i,e,o,u,f,p;if(f=s,i=k(),i!==null){for(e=[],p=s,n.charCodeAt(s)===46?(o=".",s++):(o=null,d('"."')),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,n.charCodeAt(s)===46?(o=".",s++):(o=null,d('"."')),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function un(){var i,e,o,u,f,p,m;if(f=s,p=s,i=me(),i===null&&(i=$t()),i!==null){for(e=[],m=s,o=oe(),o!==null?(u=Zr(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=oe(),o!==null?(u=Zr(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y=b.tag;try{b=new fs(b.uri,b.display_name,b.params),y&&b.setParam("tag",y)}catch{b=-1}}()),i===null&&(s=f),i}function Zr(){var i;return i=cn(),i===null&&(i=We()),i}function cn(){var i,e,o,u,f;return u=s,f=s,n.substr(s,3).toLowerCase()==="tag"?(i=n.substr(s,3),s+=3):(i=null,d('"tag"')),i!==null?(e=G(),e!==null?(o=U(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.tag=m}(u,i[2])),i===null&&(s=u),i}function ei(){var i,e,o;if(o=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){b=parseInt(f.join(""))}(o,i)),i===null&&(s=o),i}function ea(){var i,e;return e=s,i=ts(),i!==null&&(i=function(o,u){b=u}(e,i)),i===null&&(s=e),i}function ta(){var i,e,o,u,f,p,m,v,y,D;for(v=s,y=s,i=[],e=Ht();e!==null;)i.push(e),e=Ht();if(i!==null)if(e=ke(),e!==null)if(o=we(),o!==null)if(u=Ie(),u!==null){for(f=[],D=s,p=oe(),p!==null?(m=We(),m!==null?p=[p,m]:(p=null,s=D)):(p=null,s=D);p!==null;)f.push(p),D=s,p=oe(),p!==null?(m=We(),m!==null?p=[p,m]:(p=null,s=D)):(p=null,s=D);f!==null?i=[i,e,o,u,f]:(i=null,s=y)}else i=null,s=y;else i=null,s=y;else i=null,s=y;else i=null,s=y;return i!==null&&(i=function(ie){try{b=new fs(b.uri,b.display_name,b.params)}catch{b=-1}}()),i===null&&(s=v),i}function sa(){var i;return i=ti(),i}function ti(){var i,e,o,u,f,p,m,v;if(m=s,n.substr(s,6).toLowerCase()==="digest"?(i=n.substr(s,6),s+=6):(i=null,d('"Digest"')),i!==null)if(e=pe(),e!==null)if(o=ns(),o!==null){for(u=[],v=s,f=Ae(),f!==null?(p=ns(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);f!==null;)u.push(f),v=s,f=Ae(),f!==null?(p=ns(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,o,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i===null&&(i=qn()),i}function qn(){var i,e,o,u,f,p,m,v;if(m=s,i=U(),i!==null)if(e=pe(),e!==null)if(o=Us(),o!==null){for(u=[],v=s,f=Ae(),f!==null?(p=Us(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);f!==null;)u.push(f),v=s,f=Ae(),f!==null?(p=Us(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,o,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i}function Us(){var i,e,o,u;return u=s,i=U(),i!==null?(e=G(),e!==null?(o=U(),o===null&&(o=be()),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function ns(){var i;return i=fn(),i===null&&(i=ni(),i===null&&(i=hn(),i===null&&(i=ii(),i===null&&(i=li(),i===null&&(i=oi(),i===null&&(i=ai(),i===null&&(i=Us()))))))),i}function fn(){var i,e,o,u;return u=s,n.substr(s,5).toLowerCase()==="realm"?(i=n.substr(s,5),s+=5):(i=null,d('"realm"')),i!==null?(e=G(),e!==null?(o=si(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function si(){var i,e;return e=s,i=Oe(),i!==null&&(i=function(o,u){b.realm=u}(e,i)),i===null&&(s=e),i}function ni(){var i,e,o,u,f,p,m,v,y;if(v=s,n.substr(s,6).toLowerCase()==="domain"?(i=n.substr(s,6),s+=6):(i=null,d('"domain"')),i!==null)if(e=G(),e!==null)if(o=nt(),o!==null)if(u=dn(),u!==null){if(f=[],y=s,m=R(),m!==null)for(p=[];m!==null;)p.push(m),m=R();else p=null;for(p!==null?(m=dn(),m!==null?p=[p,m]:(p=null,s=y)):(p=null,s=y);p!==null;){if(f.push(p),y=s,m=R(),m!==null)for(p=[];m!==null;)p.push(m),m=R();else p=null;p!==null?(m=dn(),m!==null?p=[p,m]:(p=null,s=y)):(p=null,s=y)}f!==null?(p=ot(),p!==null?i=[i,e,o,u,f,p]:(i=null,s=v)):(i=null,s=v)}else i=null,s=v;else i=null,s=v;else i=null,s=v;else i=null,s=v;return i}function dn(){var i;return i=Un(),i===null&&(i=en()),i}function hn(){var i,e,o,u;return u=s,n.substr(s,5).toLowerCase()==="nonce"?(i=n.substr(s,5),s+=5):(i=null,d('"nonce"')),i!==null?(e=G(),e!==null?(o=ri(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function ri(){var i,e;return e=s,i=Oe(),i!==null&&(i=function(o,u){b.nonce=u}(e,i)),i===null&&(s=e),i}function ii(){var i,e,o,u,f;return u=s,f=s,n.substr(s,6).toLowerCase()==="opaque"?(i=n.substr(s,6),s+=6):(i=null,d('"opaque"')),i!==null?(e=G(),e!==null?(o=Oe(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.opaque=m}(u,i[2])),i===null&&(s=u),i}function li(){var i,e,o,u,f;return u=s,n.substr(s,5).toLowerCase()==="stale"?(i=n.substr(s,5),s+=5):(i=null,d('"stale"')),i!==null?(e=G(),e!==null?(f=s,n.substr(s,4).toLowerCase()==="true"?(o=n.substr(s,4),s+=4):(o=null,d('"true"')),o!==null&&(o=function(p){b.stale=!0}()),o===null&&(s=f),o===null&&(f=s,n.substr(s,5).toLowerCase()==="false"?(o=n.substr(s,5),s+=5):(o=null,d('"false"')),o!==null&&(o=function(p){b.stale=!1}()),o===null&&(s=f)),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function oi(){var i,e,o,u,f;return u=s,f=s,n.substr(s,9).toLowerCase()==="algorithm"?(i=n.substr(s,9),s+=9):(i=null,d('"algorithm"')),i!==null?(e=G(),e!==null?(n.substr(s,3).toLowerCase()==="md5"?(o=n.substr(s,3),s+=3):(o=null,d('"MD5"')),o===null&&(n.substr(s,8).toLowerCase()==="md5-sess"?(o=n.substr(s,8),s+=8):(o=null,d('"MD5-sess"')),o===null&&(o=U())),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.algorithm=m.toUpperCase()}(u,i[2])),i===null&&(s=u),i}function ai(){var i,e,o,u,f,p,m,v,y,D;if(v=s,n.substr(s,3).toLowerCase()==="qop"?(i=n.substr(s,3),s+=3):(i=null,d('"qop"')),i!==null)if(e=G(),e!==null)if(o=nt(),o!==null){if(y=s,u=_n(),u!==null){for(f=[],D=s,n.charCodeAt(s)===44?(p=",",s++):(p=null,d('","')),p!==null?(m=_n(),m!==null?p=[p,m]:(p=null,s=D)):(p=null,s=D);p!==null;)f.push(p),D=s,n.charCodeAt(s)===44?(p=",",s++):(p=null,d('","')),p!==null?(m=_n(),m!==null?p=[p,m]:(p=null,s=D)):(p=null,s=D);f!==null?u=[u,f]:(u=null,s=y)}else u=null,s=y;u!==null?(f=ot(),f!==null?i=[i,e,o,u,f]:(i=null,s=v)):(i=null,s=v)}else i=null,s=v;else i=null,s=v;else i=null,s=v;return i}function _n(){var i,e;return e=s,n.substr(s,8).toLowerCase()==="auth-int"?(i=n.substr(s,8),s+=8):(i=null,d('"auth-int"')),i===null&&(n.substr(s,4).toLowerCase()==="auth"?(i=n.substr(s,4),s+=4):(i=null,d('"auth"')),i===null&&(i=U())),i!==null&&(i=function(o,u){b.qop||(b.qop=[]),b.qop.push(u.toLowerCase())}(e,i)),i===null&&(s=e),i}function Bn(){var i,e,o,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,o=Ae(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=Ae(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function na(){var i,e,o,u,f,p,m;if(f=s,p=s,i=Gn(),i!==null){for(e=[],m=s,o=Ae(),o!==null?(u=Gn(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=Ae(),o!==null?(u=Gn(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y,D;for(D=b.multi_header.length,y=0;y<D;y++)if(b.multi_header[y].parsed===null){b=null;break}b!==null?b=b.multi_header:b=-1}()),i===null&&(s=f),i}function Gn(){var i,e,o,u,f,p,m;if(f=s,p=s,i=$t(),i!==null){for(e=[],m=s,o=oe(),o!==null?(u=We(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=oe(),o!==null?(u=We(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y;b.multi_header||(b.multi_header=[]);try{y=new fs(b.uri,b.display_name,b.params),delete b.uri,delete b.display_name,delete b.params}catch{y=null}b.multi_header.push({possition:s,offset:v,parsed:y})}(f)),i===null&&(s=f),i}function Wn(){var i,e,o,u,f,p,m;if(f=s,p=s,n.substr(s,3).toLowerCase()==="sip"?(i=n.substr(s,3),s+=3):(i=null,d('"SIP"')),i===null&&(i=U()),i!==null){for(e=[],m=s,o=oe(),o!==null?(u=ui(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=oe(),o!==null?(u=ui(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v,y){if(b.protocol=y.toLowerCase(),b.params||(b.params={}),b.params.text&&b.params.text[0]==='"'){var D=b.params.text;b.text=D.substring(1,D.length-1),delete b.params.text}}(f,i[0])),i===null&&(s=f),i}function ui(){var i;return i=Kn(),i===null&&(i=We()),i}function Kn(){var i,e,o,u,f,p;if(f=s,p=s,n.substr(s,5).toLowerCase()==="cause"?(i=n.substr(s,5),s+=5):(i=null,d('"cause"')),i!==null)if(e=G(),e!==null){if(u=g(),u!==null)for(o=[];u!==null;)o.push(u),u=g();else o=null;o!==null?i=[i,e,o]:(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(m,v){b.cause=parseInt(v.join(""))}(f,i[2])),i===null&&(s=f),i}function Rl(){var i,e,o,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,o=Ae(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=Ae(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function ra(){var i,e,o,u,f,p;if(f=s,i=Yn(),i!==null){for(e=[],p=s,o=Ae(),o!==null?(u=Yn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=Ae(),o!==null?(u=Yn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Yn(){var i,e,o,u,f,p;if(f=s,i=$t(),i!==null){for(e=[],p=s,o=oe(),o!==null?(u=We(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=oe(),o!==null?(u=We(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Jn(){var i,e,o,u,f,p;if(f=s,i=Il(),i!==null){for(e=[],p=s,o=oe(),o!==null?(u=zn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=oe(),o!==null?(u=zn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Il(){var i,e;return e=s,n.substr(s,6).toLowerCase()==="active"?(i=n.substr(s,6),s+=6):(i=null,d('"active"')),i===null&&(n.substr(s,7).toLowerCase()==="pending"?(i=n.substr(s,7),s+=7):(i=null,d('"pending"')),i===null&&(n.substr(s,10).toLowerCase()==="terminated"?(i=n.substr(s,10),s+=10):(i=null,d('"terminated"')),i===null&&(i=U()))),i!==null&&(i=function(o){b.state=n.substring(s,o)}(e)),i===null&&(s=e),i}function zn(){var i,e,o,u,f;return u=s,f=s,n.substr(s,6).toLowerCase()==="reason"?(i=n.substr(s,6),s+=6):(i=null,d('"reason"')),i!==null?(e=G(),e!==null?(o=Xn(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){typeof m<"u"&&(b.reason=m)}(u,i[2])),i===null&&(s=u),i===null&&(u=s,f=s,n.substr(s,7).toLowerCase()==="expires"?(i=n.substr(s,7),s+=7):(i=null,d('"expires"')),i!==null?(e=G(),e!==null?(o=ts(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){typeof m<"u"&&(b.expires=m)}(u,i[2])),i===null&&(s=u),i===null&&(u=s,f=s,n.substr(s,11).toLowerCase()==="retry_after"?(i=n.substr(s,11),s+=11):(i=null,d('"retry_after"')),i!==null?(e=G(),e!==null?(o=ts(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){typeof m<"u"&&(b.retry_after=m)}(u,i[2])),i===null&&(s=u),i===null&&(i=We()))),i}function Xn(){var i;return n.substr(s,11).toLowerCase()==="deactivated"?(i=n.substr(s,11),s+=11):(i=null,d('"deactivated"')),i===null&&(n.substr(s,9).toLowerCase()==="probation"?(i=n.substr(s,9),s+=9):(i=null,d('"probation"')),i===null&&(n.substr(s,8).toLowerCase()==="rejected"?(i=n.substr(s,8),s+=8):(i=null,d('"rejected"')),i===null&&(n.substr(s,7).toLowerCase()==="timeout"?(i=n.substr(s,7),s+=7):(i=null,d('"timeout"')),i===null&&(n.substr(s,6).toLowerCase()==="giveup"?(i=n.substr(s,6),s+=6):(i=null,d('"giveup"')),i===null&&(n.substr(s,10).toLowerCase()==="noresource"?(i=n.substr(s,10),s+=10):(i=null,d('"noresource"')),i===null&&(n.substr(s,9).toLowerCase()==="invariant"?(i=n.substr(s,9),s+=9):(i=null,d('"invariant"')),i===null&&(i=U()))))))),i}function bl(){var i;return i=q(),i=i!==null?i:"",i}function ia(){var i,e,o,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,o=Ae(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=Ae(),o!==null?(u=U(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i=i!==null?i:"",i}function la(){var i,e,o,u,f,p,m;if(f=s,p=s,i=me(),i===null&&(i=$t()),i!==null){for(e=[],m=s,o=oe(),o!==null?(u=ci(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=oe(),o!==null?(u=ci(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y=b.tag;try{b=new fs(b.uri,b.display_name,b.params),y&&b.setParam("tag",y)}catch{b=-1}}()),i===null&&(s=f),i}function ci(){var i;return i=cn(),i===null&&(i=We()),i}function fi(){var i,e,o,u,f,p;if(f=s,i=Qn(),i!==null){for(e=[],p=s,o=Ae(),o!==null?(u=Qn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=Ae(),o!==null?(u=Qn(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Qn(){var i,e,o,u,f,p,m,v;if(m=s,i=gi(),i!==null)if(e=pe(),e!==null)if(o=Si(),o!==null){for(u=[],v=s,f=oe(),f!==null?(p=ks(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);f!==null;)u.push(f),v=s,f=oe(),f!==null?(p=ks(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,o,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i}function ks(){var i;return i=Zn(),i===null&&(i=di(),i===null&&(i=hi(),i===null&&(i=_i(),i===null&&(i=pi(),i===null&&(i=We()))))),i}function Zn(){var i,e,o,u,f;return u=s,f=s,n.substr(s,3).toLowerCase()==="ttl"?(i=n.substr(s,3),s+=3):(i=null,d('"ttl"')),i!==null?(e=G(),e!==null?(o=er(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.ttl=m}(u,i[2])),i===null&&(s=u),i}function di(){var i,e,o,u,f;return u=s,f=s,n.substr(s,5).toLowerCase()==="maddr"?(i=n.substr(s,5),s+=5):(i=null,d('"maddr"')),i!==null?(e=G(),e!==null?(o=es(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.maddr=m}(u,i[2])),i===null&&(s=u),i}function hi(){var i,e,o,u,f;return u=s,f=s,n.substr(s,8).toLowerCase()==="received"?(i=n.substr(s,8),s+=8):(i=null,d('"received"')),i!==null?(e=G(),e!==null?(o=at(),o===null&&(o=zs()),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.received=m}(u,i[2])),i===null&&(s=u),i}function _i(){var i,e,o,u,f;return u=s,f=s,n.substr(s,6).toLowerCase()==="branch"?(i=n.substr(s,6),s+=6):(i=null,d('"branch"')),i!==null?(e=G(),e!==null?(o=U(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.branch=m}(u,i[2])),i===null&&(s=u),i}function pi(){var i,e,o,u,f;return u=s,n.substr(s,5).toLowerCase()==="rport"?(i=n.substr(s,5),s+=5):(i=null,d('"rport"')),i!==null?(f=s,e=G(),e!==null?(o=mi(),o!==null?e=[e,o]:(e=null,s=f)):(e=null,s=f),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i}function mi(){var i,e,o,u,f,p,m;return p=s,m=s,i=g(),i=i!==null?i:"",i!==null?(e=g(),e=e!==null?e:"",e!==null?(o=g(),o=o!==null?o:"",o!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?i=[i,e,o,u,f]:(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m),i!==null&&(i=function(v,y){b.rport=parseInt(y.join(""))}(p,i)),i===null&&(s=p),i}function gi(){var i,e,o,u,f,p;return p=s,i=Ti(),i!==null?(e=W(),e!==null?(o=U(),o!==null?(u=W(),u!==null?(f=vi(),f!==null?i=[i,e,o,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function Ti(){var i,e;return e=s,n.substr(s,3).toLowerCase()==="sip"?(i=n.substr(s,3),s+=3):(i=null,d('"SIP"')),i===null&&(i=U()),i!==null&&(i=function(o,u){b.protocol=u}(e,i)),i===null&&(s=e),i}function vi(){var i,e;return e=s,n.substr(s,3).toLowerCase()==="udp"?(i=n.substr(s,3),s+=3):(i=null,d('"UDP"')),i===null&&(n.substr(s,3).toLowerCase()==="tcp"?(i=n.substr(s,3),s+=3):(i=null,d('"TCP"')),i===null&&(n.substr(s,3).toLowerCase()==="tls"?(i=n.substr(s,3),s+=3):(i=null,d('"TLS"')),i===null&&(n.substr(s,4).toLowerCase()==="sctp"?(i=n.substr(s,4),s+=4):(i=null,d('"SCTP"')),i===null&&(i=U())))),i!==null&&(i=function(o,u){b.transport=u}(e,i)),i===null&&(s=e),i}function Si(){var i,e,o,u,f;return u=s,i=Ei(),i!==null?(f=s,e=ye(),e!==null?(o=yi(),o!==null?e=[e,o]:(e=null,s=f)):(e=null,s=f),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i}function Ei(){var i,e;return e=s,i=at(),i===null&&(i=Dn(),i===null&&(i=us())),i!==null&&(i=function(o){b.host=n.substring(s,o)}(e)),i===null&&(s=e),i}function yi(){var i,e,o,u,f,p,m;return p=s,m=s,i=g(),i=i!==null?i:"",i!==null?(e=g(),e=e!==null?e:"",e!==null?(o=g(),o=o!==null?o:"",o!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?i=[i,e,o,u,f]:(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m)):(i=null,s=m),i!==null&&(i=function(v,y){b.port=parseInt(y.join(""))}(p,i)),i===null&&(s=p),i}function er(){var i,e,o,u,f;return u=s,f=s,i=g(),i!==null?(e=g(),e=e!==null?e:"",e!==null?(o=g(),o=o!==null?o:"",o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){return parseInt(m.join(""))}(u,i)),i===null&&(s=u),i}function Ci(){var i;return i=ti(),i}function oa(){var i,e,o,u,f,p;if(f=s,i=wl(),i!==null){for(e=[],p=s,o=oe(),o!==null?(u=tr(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=oe(),o!==null?(u=tr(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function wl(){var i,e;return e=s,i=ts(),i!==null&&(i=function(o,u){b.expires=u}(e,i)),i===null&&(s=e),i}function tr(){var i;return i=sr(),i===null&&(i=We()),i}function sr(){var i,e,o,u,f;return u=s,f=s,n.substr(s,9).toLowerCase()==="refresher"?(i=n.substr(s,9),s+=9):(i=null,d('"refresher"')),i!==null?(e=G(),e!==null?(n.substr(s,3).toLowerCase()==="uac"?(o=n.substr(s,3),s+=3):(o=null,d('"uac"')),o===null&&(n.substr(s,3).toLowerCase()==="uas"?(o=n.substr(s,3),s+=3):(o=null,d('"uas"'))),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.refresher=m.toLowerCase()}(u,i[2])),i===null&&(s=u),i}function Ol(){var i,e,o,u;return u=s,i=U(),i!==null?(e=N(),e!==null?(o=Dl(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Dl(){var i,e;for(i=[],e=j(),e===null&&(e=F(),e===null&&(e=pe()));e!==null;)i.push(e),e=j(),e===null&&(e=F(),e===null&&(e=pe()));return i}function Nl(){var i,e;for(i=[],e=C();e!==null;)i.push(e),e=C();return i}function aa(){var i,e,o;return o=s,n.substr(s,5)==="uuid:"?(i="uuid:",s+=5):(i=null,d('"uuid:"')),i!==null?(e=xl(),e!==null?i=[i,e]:(i=null,s=o)):(i=null,s=o),i}function xl(){var i,e,o,u,f,p,m,v,y,D,ie;return D=s,ie=s,i=Vt(),i!==null?(n.charCodeAt(s)===45?(e="-",s++):(e=null,d('"-"')),e!==null?(o=Ft(),o!==null?(n.charCodeAt(s)===45?(u="-",s++):(u=null,d('"-"')),u!==null?(f=Ft(),f!==null?(n.charCodeAt(s)===45?(p="-",s++):(p=null,d('"-"')),p!==null?(m=Ft(),m!==null?(n.charCodeAt(s)===45?(v="-",s++):(v=null,d('"-"')),v!==null?(y=Ai(),y!==null?i=[i,e,o,u,f,p,m,v,y]:(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie)):(i=null,s=ie),i!==null&&(i=function(xe,wt){b=n.substring(s+5,xe)}(D,i[0])),i===null&&(s=D),i}function Ft(){var i,e,o,u,f;return f=s,i=S(),i!==null?(e=S(),e!==null?(o=S(),o!==null?(u=S(),u!==null?i=[i,e,o,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function Vt(){var i,e,o;return o=s,i=Ft(),i!==null?(e=Ft(),e!==null?i=[i,e]:(i=null,s=o)):(i=null,s=o),i}function Ai(){var i,e,o,u;return u=s,i=Ft(),i!==null?(e=Ft(),e!==null?(o=Ft(),o!==null?i=[i,e,o]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Ul(){var i,e,o,u,f,p,m;if(f=s,p=s,i=me(),i===null&&(i=$t()),i!==null){for(e=[],m=s,o=oe(),o!==null?(u=We(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);o!==null;)e.push(o),m=s,o=oe(),o!==null?(u=We(),u!==null?o=[o,u]:(o=null,s=m)):(o=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){try{b=new fs(b.uri,b.display_name,b.params)}catch{b=-1}}()),i===null&&(s=f),i}function ua(){var i,e,o,u,f,p;if(f=s,i=kl(),i!==null){for(e=[],p=s,o=oe(),o!==null?(u=nr(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);o!==null;)e.push(o),p=s,o=oe(),o!==null?(u=nr(),u!==null?o=[o,u]:(o=null,s=p)):(o=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function kl(){var i,e,o,u,f,p;return u=s,f=s,i=He(),i!==null?(p=s,n.charCodeAt(s)===64?(e="@",s++):(e=null,d('"@"')),e!==null?(o=He(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?i=[i,e]:(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){b.call_id=n.substring(s,m)}(u)),i===null&&(s=u),i}function nr(){var i;return i=rr(),i===null&&(i=Ri(),i===null&&(i=Ii(),i===null&&(i=We()))),i}function rr(){var i,e,o,u,f;return u=s,f=s,n.substr(s,6)==="to-tag"?(i="to-tag",s+=6):(i=null,d('"to-tag"')),i!==null?(e=G(),e!==null?(o=U(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.to_tag=m}(u,i[2])),i===null&&(s=u),i}function Ri(){var i,e,o,u,f;return u=s,f=s,n.substr(s,8)==="from-tag"?(i="from-tag",s+=8):(i=null,d('"from-tag"')),i!==null?(e=G(),e!==null?(o=U(),o!==null?i=[i,e,o]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){b.from_tag=m}(u,i[2])),i===null&&(s=u),i}function Ii(){var i,e;return e=s,n.substr(s,10)==="early-only"?(i="early-only",s+=10):(i=null,d('"early-only"')),i!==null&&(i=function(o){b.early_only=!0}()),i===null&&(s=e),i}function Pl(i){i.sort();for(var e=null,o=[],u=0;u<i.length;u++)i[u]!==e&&(o.push(i[u]),e=i[u]);return o}function ca(){for(var i=1,e=1,o=!1,u=0;u<Math.max(s,r);u++){var f=n.charAt(u);f===`
|
|
75
|
-
`?(o||i++,e=1,o=!1):f==="\r"||f==="\u2028"||f==="\u2029"?(i++,e=1,o=!0):(e++,o=!1)}return{line:i,column:e}}var Ml=ys(),fs=Fu(),b={},O=a[l]();if(O===null||s!==n.length){var bi=Math.max(s,r),wi=bi<n.length?n.charAt(bi):null,Ll=ca();return new this.SyntaxError(Pl(h),wi,bi,Ll.line,Ll.column),-1}return b},toSource:function(){return this._source}};return t.SyntaxError=function(n,l,a,s,r){function h(d,_){var g,T;switch(d.length){case 0:g="end of input";break;case 1:g=d[0];break;default:g=d.slice(0,d.length-1).join(", ")+" or "+d[d.length-1]}return T=_?c(_):"end of input","Expected "+g+" but "+T+" found."}this.name="SyntaxError",this.expected=n,this.found=l,this.message=h(n,l),this.offset=a,this.line=s,this.column=r},t.SyntaxError.prototype=Error.prototype,t}()),Pa}var Ma,rf;function ys(){if(rf)return Ma;rf=1;const c=De,t=Ct(),n=Zt();return Ma=class hd{static parse(a){if(a=n.parse(a,"SIP_URI"),a!==-1)return a}constructor(a,s,r,h,d={},_={}){if(!r)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=a||c.SIP,this._user=s,this._host=r,this._port=h;for(const g in d)Object.prototype.hasOwnProperty.call(d,g)&&this.setParam(g,d[g]);for(const g in _)Object.prototype.hasOwnProperty.call(_,g)&&this.setHeader(g,_[g])}get scheme(){return this._scheme}set scheme(a){this._scheme=a.toLowerCase()}get user(){return this._user}set user(a){this._user=a}get host(){return this._host}set host(a){this._host=a.toLowerCase()}get port(){return this._port}set port(a){this._port=a===0?a:parseInt(a,10)||null}setParam(a,s){a&&(this._parameters[a.toLowerCase()]=typeof s>"u"||s===null?null:s.toString())}getParam(a){if(a)return this._parameters[a.toLowerCase()]}hasParam(a){if(a)return this._parameters.hasOwnProperty(a.toLowerCase())&&!0||!1}deleteParam(a){if(a=a.toLowerCase(),this._parameters.hasOwnProperty(a)){const s=this._parameters[a];return delete this._parameters[a],s}}clearParams(){this._parameters={}}setHeader(a,s){this._headers[t.headerize(a)]=Array.isArray(s)?s:[s]}getHeader(a){if(a)return this._headers[t.headerize(a)]}hasHeader(a){if(a)return this._headers.hasOwnProperty(t.headerize(a))&&!0||!1}deleteHeader(a){if(a=t.headerize(a),this._headers.hasOwnProperty(a)){const s=this._headers[a];return delete this._headers[a],s}}clearHeaders(){this._headers={}}clone(){return new hd(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}toString(){const a=[];let s=`${this._scheme}:`;this._user&&(s+=`${t.escapeUser(this._user)}@`),s+=this._host,(this._port||this._port===0)&&(s+=`:${this._port}`);for(const r in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,r)&&(s+=`;${r}`,this._parameters[r]!==null&&(s+=`=${this._parameters[r]}`));for(const r in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,r))for(const h of this._headers[r])a.push(`${r}=${h}`);return a.length>0&&(s+=`?${a.join("&")}`),s}toAor(a){let s=`${this._scheme}:`;return this._user&&(s+=`${t.escapeUser(this._user)}@`),s+=this._host,a&&(this._port||this._port===0)&&(s+=`:${this._port}`),s}},Ma}var lf;function Ct(){if(lf)return tt;lf=1;const c=De,t=ys(),n=Zt();tt.str_utf8_length=r=>unescape(encodeURIComponent(r)).length;const l=tt.isFunction=r=>r!==void 0?Object.prototype.toString.call(r)==="[object Function]":!1;tt.isString=r=>r!==void 0?Object.prototype.toString.call(r)==="[object String]":!1,tt.isDecimal=r=>!isNaN(r)&&parseFloat(r)===parseInt(r,10),tt.isEmpty=r=>r===null||r===""||r===void 0||Array.isArray(r)&&r.length===0||typeof r=="number"&&isNaN(r),tt.hasMethods=function(r,...h){for(const d of h)if(l(r[d]))return!1;return!0};const a=tt.createRandomToken=(r,h=32)=>{let d,_,g="";for(d=0;d<r;d++)_=Math.random()*h|0,g+=_.toString(h);return g};tt.newTag=()=>a(10),tt.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,h=>{const d=Math.random()*16|0;return(h==="x"?d:d&3|8).toString(16)}),tt.hostType=r=>{if(r){if(r=n.parse(r,"host"),r!==-1)return r.host_type}else return};const s=tt.escapeUser=r=>encodeURIComponent(decodeURIComponent(r)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/");return tt.normalizeTarget=(r,h)=>{if(r){if(r instanceof t)return r;if(typeof r=="string"){const d=r.split("@");let _,g;switch(d.length){case 1:if(!h)return;_=r,g=h;break;case 2:_=d[0],g=d[1];break;default:_=d.slice(0,d.length-1).join("@"),g=d[d.length-1]}_=_.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(_)&&(_=_.replace(/[-.()]/g,"")),r=`${c.SIP}:${s(_)}@${g}`;let T;return(T=t.parse(r))?T:void 0}else return}else return},tt.headerize=r=>{const h={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},d=r.toLowerCase().replace(/_/g,"-").split("-");let _="";const g=d.length;let T;for(T=0;T<g;T++)T!==0&&(_+="-"),_+=d[T].charAt(0).toUpperCase()+d[T].substring(1);return h[_]&&(_=h[_]),_},tt.sipErrorCause=r=>{for(const h in c.SIP_ERROR_CAUSES)if(c.SIP_ERROR_CAUSES[h].indexOf(r)!==-1)return c.causes[h];return c.causes.SIP_FAILURE_CODE},tt.getRandomTestNetIP=()=>{function r(h,d){return Math.floor(Math.random()*(d-h+1)+h)}return`192.0.2.${r(1,254)}`},tt.calculateMD5=r=>{function h(Ee,Ce){return Ee<<Ce|Ee>>>32-Ce}function d(Ee,Ce){const be=Ee&2147483648,Oe=Ce&2147483648,ge=Ee&1073741824,ue=Ce&1073741824,me=(Ee&1073741823)+(Ce&1073741823);return ge&ue?me^2147483648^be^Oe:ge|ue?me&1073741824?me^3221225472^be^Oe:me^1073741824^be^Oe:me^be^Oe}function _(Ee,Ce,be){return Ee&Ce|~Ee&be}function g(Ee,Ce,be){return Ee&be|Ce&~be}function T(Ee,Ce,be){return Ee^Ce^be}function S(Ee,Ce,be){return Ce^(Ee|~be)}function E(Ee,Ce,be,Oe,ge,ue,me){return Ee=d(Ee,d(d(_(Ce,be,Oe),ge),me)),d(h(Ee,ue),Ce)}function C(Ee,Ce,be,Oe,ge,ue,me){return Ee=d(Ee,d(d(g(Ce,be,Oe),ge),me)),d(h(Ee,ue),Ce)}function A(Ee,Ce,be,Oe,ge,ue,me){return Ee=d(Ee,d(d(T(Ce,be,Oe),ge),me)),d(h(Ee,ue),Ce)}function R(Ee,Ce,be,Oe,ge,ue,me){return Ee=d(Ee,d(d(S(Ce,be,Oe),ge),me)),d(h(Ee,ue),Ce)}function V(Ee){let Ce;const be=Ee.length,Oe=be+8,ue=((Oe-Oe%64)/64+1)*16,me=new Array(ue-1);let we=0,Ne=0;for(;Ne<be;)Ce=(Ne-Ne%4)/4,we=Ne%4*8,me[Ce]=me[Ce]|Ee.charCodeAt(Ne)<<we,Ne++;return Ce=(Ne-Ne%4)/4,we=Ne%4*8,me[Ce]=me[Ce]|128<<we,me[ue-2]=be<<3,me[ue-1]=be>>>29,me}function w(Ee){let Ce="",be="",Oe,ge;for(ge=0;ge<=3;ge++)Oe=Ee>>>ge*8&255,be=`0${Oe.toString(16)}`,Ce=Ce+be.substr(be.length-2,2);return Ce}function le(Ee){let Ce="";for(let be=0;be<Ee.length;be++){const Oe=Ee.charCodeAt(be);Oe<128?Ce+=String.fromCharCode(Oe):Oe>127&&Oe<2048?(Ce+=String.fromCharCode(Oe>>6|192),Ce+=String.fromCharCode(Oe&63|128)):(Ce+=String.fromCharCode(Oe>>12|224),Ce+=String.fromCharCode(Oe>>6&63|128),Ce+=String.fromCharCode(Oe&63|128))}return Ce}let x=[],H,ve,pe,P,N,q,j,Y,F;const X=7,U=12,k=17,B=22,He=5,Q=9,W=14,G=20,re=4,_e=11,Ie=16,ke=23,Ae=6,oe=10,ye=15,nt=21;for(r=le(r),x=V(r),q=1732584193,j=4023233417,Y=2562383102,F=271733878,H=0;H<x.length;H+=16)ve=q,pe=j,P=Y,N=F,q=E(q,j,Y,F,x[H+0],X,3614090360),F=E(F,q,j,Y,x[H+1],U,3905402710),Y=E(Y,F,q,j,x[H+2],k,606105819),j=E(j,Y,F,q,x[H+3],B,3250441966),q=E(q,j,Y,F,x[H+4],X,4118548399),F=E(F,q,j,Y,x[H+5],U,1200080426),Y=E(Y,F,q,j,x[H+6],k,2821735955),j=E(j,Y,F,q,x[H+7],B,4249261313),q=E(q,j,Y,F,x[H+8],X,1770035416),F=E(F,q,j,Y,x[H+9],U,2336552879),Y=E(Y,F,q,j,x[H+10],k,4294925233),j=E(j,Y,F,q,x[H+11],B,2304563134),q=E(q,j,Y,F,x[H+12],X,1804603682),F=E(F,q,j,Y,x[H+13],U,4254626195),Y=E(Y,F,q,j,x[H+14],k,2792965006),j=E(j,Y,F,q,x[H+15],B,1236535329),q=C(q,j,Y,F,x[H+1],He,4129170786),F=C(F,q,j,Y,x[H+6],Q,3225465664),Y=C(Y,F,q,j,x[H+11],W,643717713),j=C(j,Y,F,q,x[H+0],G,3921069994),q=C(q,j,Y,F,x[H+5],He,3593408605),F=C(F,q,j,Y,x[H+10],Q,38016083),Y=C(Y,F,q,j,x[H+15],W,3634488961),j=C(j,Y,F,q,x[H+4],G,3889429448),q=C(q,j,Y,F,x[H+9],He,568446438),F=C(F,q,j,Y,x[H+14],Q,3275163606),Y=C(Y,F,q,j,x[H+3],W,4107603335),j=C(j,Y,F,q,x[H+8],G,1163531501),q=C(q,j,Y,F,x[H+13],He,2850285829),F=C(F,q,j,Y,x[H+2],Q,4243563512),Y=C(Y,F,q,j,x[H+7],W,1735328473),j=C(j,Y,F,q,x[H+12],G,2368359562),q=A(q,j,Y,F,x[H+5],re,4294588738),F=A(F,q,j,Y,x[H+8],_e,2272392833),Y=A(Y,F,q,j,x[H+11],Ie,1839030562),j=A(j,Y,F,q,x[H+14],ke,4259657740),q=A(q,j,Y,F,x[H+1],re,2763975236),F=A(F,q,j,Y,x[H+4],_e,1272893353),Y=A(Y,F,q,j,x[H+7],Ie,4139469664),j=A(j,Y,F,q,x[H+10],ke,3200236656),q=A(q,j,Y,F,x[H+13],re,681279174),F=A(F,q,j,Y,x[H+0],_e,3936430074),Y=A(Y,F,q,j,x[H+3],Ie,3572445317),j=A(j,Y,F,q,x[H+6],ke,76029189),q=A(q,j,Y,F,x[H+9],re,3654602809),F=A(F,q,j,Y,x[H+12],_e,3873151461),Y=A(Y,F,q,j,x[H+15],Ie,530742520),j=A(j,Y,F,q,x[H+2],ke,3299628645),q=R(q,j,Y,F,x[H+0],Ae,4096336452),F=R(F,q,j,Y,x[H+7],oe,1126891415),Y=R(Y,F,q,j,x[H+14],ye,2878612391),j=R(j,Y,F,q,x[H+5],nt,4237533241),q=R(q,j,Y,F,x[H+12],Ae,1700485571),F=R(F,q,j,Y,x[H+3],oe,2399980690),Y=R(Y,F,q,j,x[H+10],ye,4293915773),j=R(j,Y,F,q,x[H+1],nt,2240044497),q=R(q,j,Y,F,x[H+8],Ae,1873313359),F=R(F,q,j,Y,x[H+15],oe,4264355552),Y=R(Y,F,q,j,x[H+6],ye,2734768916),j=R(j,Y,F,q,x[H+13],nt,1309151649),q=R(q,j,Y,F,x[H+4],Ae,4149444226),F=R(F,q,j,Y,x[H+11],oe,3174756917),Y=R(Y,F,q,j,x[H+2],ye,718787259),j=R(j,Y,F,q,x[H+9],nt,3951481745),q=d(q,ve),j=d(j,pe),Y=d(Y,P),F=d(F,N);return(w(q)+w(j)+w(Y)+w(F)).toLowerCase()},tt.closeMediaStream=r=>{if(r)try{let h;if(r.getTracks){h=r.getTracks();for(const d of h)d.stop()}else{h=r.getAudioTracks();for(const d of h)d.stop();h=r.getVideoTracks();for(const d of h)d.stop()}}catch{(typeof r.stop=="function"||typeof r.stop=="object")&&r.stop()}},tt.cloneArray=r=>r&&r.slice()||[],tt.cloneObject=(r,h={})=>r&&Object.assign({},r)||h,tt}const _d=kt,Gm=ut,Et=De,it=Ct(),of=Fu(),Wm=Zt(),La=new Gm("SIPMessage");class Ko{constructor(t,n,l,a,s,r){if(!t||!n||!l)return null;a=a||{},this.ua=l,this.headers={},this.method=t,this.ruri=n,this.body=r,this.extraHeaders=it.cloneArray(s),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),a.route_set?this.setHeader("route",a.route_set):l.configuration.use_preloaded_route&&this.setHeader("route",`<${l.transport.sip_uri};lr>`),this.setHeader("via",""),this.setHeader("max-forwards",Et.MAX_FORWARDS);const h=a.to_uri||n,d=a.to_tag?{tag:a.to_tag}:null,_=typeof a.to_display_name<"u"?a.to_display_name:null;this.to=new of(h,_,d),this.setHeader("to",this.to.toString());const g=a.from_uri||l.configuration.uri,T={tag:a.from_tag||it.newTag()};let S;typeof a.from_display_name<"u"?S=a.from_display_name:l.configuration.display_name?S=l.configuration.display_name:S=null,this.from=new of(g,S,T),this.setHeader("from",this.from.toString());const E=a.call_id||l.configuration.jssip_id+it.createRandomToken(15);this.call_id=E,this.setHeader("call-id",E);const C=a.cseq||Math.floor(Math.random()*1e4);this.cseq=C,this.setHeader("cseq",`${C} ${t}`)}setHeader(t,n){const l=new RegExp(`^\\s*${t}\\s*:`,"i");for(let a=0;a<this.extraHeaders.length;a++)l.test(this.extraHeaders[a])&&this.extraHeaders.splice(a,1);this.headers[it.headerize(t)]=Array.isArray(n)?n:[n]}getHeader(t){const n=this.headers[it.headerize(t)];if(n){if(n[0])return n[0]}else{const l=new RegExp(`^\\s*${t}\\s*:`,"i");for(const a of this.extraHeaders)if(l.test(a))return a.substring(a.indexOf(":")+1).trim()}}getHeaders(t){const n=this.headers[it.headerize(t)],l=[];if(n){for(const a of n)l.push(a);return l}else{const a=new RegExp(`^\\s*${t}\\s*:`,"i");for(const s of this.extraHeaders)a.test(s)&&l.push(s.substring(s.indexOf(":")+1).trim());return l}}hasHeader(t){if(this.headers[it.headerize(t)])return!0;{const n=new RegExp(`^\\s*${t}\\s*:`,"i");for(const l of this.extraHeaders)if(n.test(l))return!0}return!1}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=_d.parse(this.body||""),this.sdp)}toString(){let t=`${this.method} ${this.ruri} SIP/2.0\r
|
|
76
|
-
`;for(const a in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,a))for(const
|
|
59
|
+
`.concat(s,`
|
|
60
|
+
`));this.ondata({transport:this,message:s})}},{key:"via_transport",get:function(){return this.socket.via_transport}},{key:"url",get:function(){return this.socket.url}},{key:"sip_uri",get:function(){return this.socket.sip_uri}}]),c}(),_d={};function qc(c,t){var s;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(s=sm(c))||t&&c&&typeof c.length=="number"){s&&(c=s);var i=0,a=function(){};return{s:a,n:function(){return i>=c.length?{done:!0}:{done:!1,value:c[i++]}},e:function(_){throw _},f:a}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
61
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var n=!0,r=!1,h;return{s:function(){s=c[Symbol.iterator]()},n:function(){var _=s.next();return n=_.done,_},e:function(_){r=!0,h=_},f:function(){try{!n&&s.return!=null&&s.return()}finally{if(r)throw h}}}}function sm(c,t){if(c){if(typeof c=="string")return Bc(c,t);var s=Object.prototype.toString.call(c).slice(8,-1);if(s==="Object"&&c.constructor&&(s=c.constructor.name),s==="Map"||s==="Set")return Array.from(c);if(s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s))return Bc(c,t)}}function Bc(c,t){(t==null||t>c.length)&&(t=c.length);for(var s=0,i=new Array(t);s<t;s++)i[s]=c[s];return i}var nm=ht,yu=us(),Cu=ys,Kl=new nm("Parser");_d.parseMessage=function(c,t){var s,i,a=c.indexOf(`\r
|
|
62
|
+
`);if(a===-1){Kl.warn("parseMessage() | no CRLF found, not a SIP message");return}var n=c.substring(0,a),r=yu.parse(n,"Request_Response");if(r===-1){Kl.warn('parseMessage() | error parsing first line of SIP message: "'.concat(n,'"'));return}else r.status_code?(s=new Cu.IncomingResponse,s.status_code=r.status_code,s.reason_phrase=r.reason_phrase):(s=new Cu.IncomingRequest(t),s.method=r.method,s.ruri=r.uri);s.data=c;for(var h=a+2;;){if(a=rm(c,h),a===-2){i=h+2;break}else if(a===-1){Kl.warn("parseMessage() | malformed message");return}if(r=im(s,c,h,a),r!==!0){Kl.warn("parseMessage() |",r.error);return}h=a+2}if(s.hasHeader("content-length")){var d=s.getHeader("content-length");s.body=c.substr(i,d)}else s.body=c.substring(i);return s};function rm(c,t){var s=t,i=0,a=0;if(c.substring(s,s+2).match(/(^\r\n)/))return-2;for(;i===0;){if(a=c.indexOf(`\r
|
|
63
|
+
`,s),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?s=a+2:i=a}return i}function im(c,t,s,i){var a,n=t.indexOf(":",s),r=t.substring(s,n).trim(),h=t.substring(n+1,i).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",h),c.getHeaders("via").length===1?(a=c.parseHeader("Via"),a&&(c.via=a,c.via_branch=a.branch)):a=0;break;case"from":case"f":c.setHeader("from",h),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",h),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=yu.parse(h,"Record_Route"),a===-1)a=void 0;else{var d=qc(a),_;try{for(d.s();!(_=d.n()).done;){var g=_.value;c.addHeader("record-route",h.substring(g.possition,g.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=g.parsed}}catch(C){d.e(C)}finally{d.f()}}break;case"call-id":case"i":c.setHeader("call-id",h),a=c.parseHeader("call-id"),a&&(c.call_id=h);break;case"contact":case"m":if(a=yu.parse(h,"Contact"),a===-1)a=void 0;else{var T=qc(a),S;try{for(T.s();!(S=T.n()).done;){var E=S.value;c.addHeader("contact",h.substring(E.possition,E.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=E.parsed}}catch(C){T.e(C)}finally{T.f()}}break;case"content-length":case"l":c.setHeader("content-length",h),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",h),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",h),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof Cu.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",h),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",h),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",h),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",h),a=c.parseHeader("session-expires"),a&&(c.session_expires=a.expires,c.session_expires_refresher=a.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",h),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",h),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",h),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,h),a=0}return a===void 0?{error:'error parsing header "'.concat(r,'"')}:!0}function Oo(c,t){var s;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(s=lm(c))||t&&c&&typeof c.length=="number"){s&&(c=s);var i=0,a=function(){};return{s:a,n:function(){return i>=c.length?{done:!0}:{done:!1,value:c[i++]}},e:function(_){throw _},f:a}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
64
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var n=!0,r=!1,h;return{s:function(){s=c[Symbol.iterator]()},n:function(){var _=s.next();return n=_.done,_},e:function(_){r=!0,h=_},f:function(){try{!n&&s.return!=null&&s.return()}finally{if(r)throw h}}}}function lm(c,t){if(c){if(typeof c=="string")return Gc(c,t);var s=Object.prototype.toString.call(c).slice(8,-1);if(s==="Object"&&c.constructor&&(s=c.constructor.name),s==="Map"||s==="Set")return Array.from(c);if(s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s))return Gc(c,t)}}function Gc(c,t){(t==null||t>c.length)&&(t=c.length);for(var s=0,i=new Array(t);s<t;s++)i[s]=c[s];return i}var om=ht,pd=ot,Wc=ys,Hu=wt(),Fu=new om("sanityCheck"),am=[Tm],um=[dm,hm,_m,pm],cm=[mm,gm],Ve,is,md,fm=function(c,t,s){Ve=c,is=t,md=s;var i=Oo(am),a;try{for(i.s();!(a=i.n()).done;){var n=a.value;if(n()===!1)return!1}}catch(S){i.e(S)}finally{i.f()}if(Ve instanceof Wc.IncomingRequest){var r=Oo(um),h;try{for(r.s();!(h=r.n()).done;){var d=h.value;if(d()===!1)return!1}}catch(S){r.e(S)}finally{r.f()}}else if(Ve instanceof Wc.IncomingResponse){var _=Oo(cm),g;try{for(_.s();!(g=_.n()).done;){var T=g.value;if(T()===!1)return!1}}catch(S){_.e(S)}finally{_.f()}}return!0};function dm(){if(Ve.s("to").uri.scheme!=="sip")return tl(416),!1}function hm(){if(!Ve.to_tag&&Ve.call_id.substr(0,5)===is.configuration.jssip_id)return tl(482),!1}function _m(){var c=Hu.str_utf8_length(Ve.body),t=Ve.getHeader("content-length");if(c<t)return tl(400),!1}function pm(){var c=Ve.from_tag,t=Ve.call_id,s=Ve.cseq,i;if(!Ve.to_tag)if(Ve.method===pd.INVITE){if(is._transactions.ist[Ve.via_branch])return!1;for(var a in is._transactions.ist)if(Object.prototype.hasOwnProperty.call(is._transactions.ist,a)&&(i=is._transactions.ist[a],i.request.from_tag===c&&i.request.call_id===t&&i.request.cseq===s))return tl(482),!1}else{if(is._transactions.nist[Ve.via_branch])return!1;for(var n in is._transactions.nist)if(Object.prototype.hasOwnProperty.call(is._transactions.nist,n)&&(i=is._transactions.nist[n],i.request.from_tag===c&&i.request.call_id===t&&i.request.cseq===s))return tl(482),!1}}function mm(){if(Ve.getHeaders("via").length>1)return Fu.debug("more than one Via header field present in the response, dropping the response"),!1}function gm(){var c=Hu.str_utf8_length(Ve.body),t=Ve.getHeader("content-length");if(c<t)return Fu.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function Tm(){for(var c=["from","to","call_id","cseq","via"],t=0,s=c;t<s.length;t++){var i=s[t];if(!Ve.hasHeader(i))return Fu.debug("missing mandatory header field : ".concat(i,", dropping the response")),!1}}function tl(c){var t=Ve.getHeaders("via"),s,i="SIP/2.0 ".concat(c," ").concat(pd.REASON_PHRASE[c],`\r
|
|
65
|
+
`),a=Oo(t),n;try{for(a.s();!(n=a.n()).done;){var r=n.value;i+="Via: ".concat(r,`\r
|
|
66
|
+
`)}}catch(h){a.e(h)}finally{a.f()}s=Ve.getHeader("To"),Ve.to_tag||(s+=";tag=".concat(Hu.newTag())),i+="To: ".concat(s,`\r
|
|
67
|
+
`),i+="From: ".concat(Ve.getHeader("From"),`\r
|
|
68
|
+
`),i+="Call-ID: ".concat(Ve.call_id,`\r
|
|
69
|
+
`),i+="CSeq: ".concat(Ve.cseq," ").concat(Ve.method,`\r
|
|
70
|
+
`),i+=`\r
|
|
71
|
+
`,md.send(i)}var Vu={};function Kc(c,t){var s;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(s=vm(c))||t&&c&&typeof c.length=="number"){s&&(c=s);var i=0,a=function(){};return{s:a,n:function(){return i>=c.length?{done:!0}:{done:!1,value:c[i++]}},e:function(_){throw _},f:a}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
72
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var n=!0,r=!1,h;return{s:function(){s=c[Symbol.iterator]()},n:function(){var _=s.next();return n=_.done,_},e:function(_){r=!0,h=_},f:function(){try{!n&&s.return!=null&&s.return()}finally{if(r)throw h}}}}function vm(c,t){if(c){if(typeof c=="string")return Yc(c,t);var s=Object.prototype.toString.call(c).slice(8,-1);if(s==="Object"&&c.constructor&&(s=c.constructor.name),s==="Map"||s==="Set")return Array.from(c);if(s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s))return Yc(c,t)}}function Yc(c,t){(t==null||t>c.length)&&(t=c.length);for(var s=0,i=new Array(t);s<t;s++)i[s]=c[s];return i}var fr=wt(),Cn=ot,Da=us(),Jc=Ys(),Na=$u,xa=Ks;Vu.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:Cn.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:Cn.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:Cn.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(fr.createRandomToken(12),".invalid")};var Yl={mandatory:{sockets:function(t){var s=[];if(Na.isSocket(t))s.push({socket:t});else if(Array.isArray(t)&&t.length){var i=Kc(t),a;try{for(i.s();!(a=i.n()).done;){var n=a.value;Object.prototype.hasOwnProperty.call(n,"socket")&&Na.isSocket(n.socket)?s.push(n):Na.isSocket(n)&&s.push({socket:n})}}catch(r){i.e(r)}finally{i.f()}}else return;return s},uri:function(t){/^sip:/i.test(t)||(t="".concat(Cn.SIP,":").concat(t));var s=Jc.parse(t);if(s)return s.user?s:void 0}},optional:{authorization_user:function(t){if(Da.parse('"'.concat(t,'"'),"quoted_string")!==-1)return t},authorization_jwt:function(t){if(typeof t=="string")return t},user_agent:function(t){if(typeof t=="string")return t},connection_recovery_max_interval:function(t){if(fr.isDecimal(t)){var s=Number(t);if(s>0)return s}},connection_recovery_min_interval:function(t){if(fr.isDecimal(t)){var s=Number(t);if(s>0)return s}},contact_uri:function(t){if(typeof t=="string"){var s=Da.parse(t,"SIP_URI");if(s!==-1)return s}},display_name:function(t){return t},instance_id:function(t){if(/^uuid:/i.test(t)&&(t=t.substr(5)),Da.parse(t,"uuid")!==-1)return t},no_answer_timeout:function(t){if(fr.isDecimal(t)){var s=Number(t);if(s>0)return s}},session_timers:function(t){if(typeof t=="boolean")return t},session_timers_refresh_method:function(t){if(typeof t=="string"&&(t=t.toUpperCase(),t===Cn.INVITE||t===Cn.UPDATE))return t},session_timers_force_refresher:function(t){if(typeof t=="boolean")return t},password:function(t){return String(t)},realm:function(t){return String(t)},ha1:function(t){return String(t)},register:function(t){if(typeof t=="boolean")return t},register_expires:function(t){if(fr.isDecimal(t)){var s=Number(t);if(s>0)return s}},registrar_server:function(t){/^sip:/i.test(t)||(t="".concat(Cn.SIP,":").concat(t));var s=Jc.parse(t);if(s)return s.user?void 0:s},use_preloaded_route:function(t){if(typeof t=="boolean")return t},extra_headers:function(t){var s=[];if(Array.isArray(t)&&t.length){var i=Kc(t),a;try{for(i.s();!(a=i.n()).done;){var n=a.value;typeof n=="string"&&s.push(n)}}catch(r){i.e(r)}finally{i.f()}}else return;return s}}};Vu.load=function(c,t){for(var s in Yl.mandatory)if(t.hasOwnProperty(s)){var i=t[s],a=Yl.mandatory[s](i);if(a!==void 0)c[s]=a;else throw new xa.ConfigurationError(s,i)}else throw new xa.ConfigurationError(s);for(var n in Yl.optional)if(t.hasOwnProperty(n)){var r=t[n];if(fr.isEmpty(r))continue;var h=Yl.optional[n](r);if(h!==void 0)c[n]=h;else throw new xa.ConfigurationError(n,r)}};function Do(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Do=function(s){return typeof s}:Do=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},Do(c)}function Sm(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function zc(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function Qc(c,t,s){return t&&zc(c.prototype,t),s&&zc(c,s),c}function Em(c,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");c.prototype=Object.create(t&&t.prototype,{constructor:{value:c,writable:!0,configurable:!0}}),t&&Au(c,t)}function Au(c,t){return Au=Object.setPrototypeOf||function(i,a){return i.__proto__=a,i},Au(c,t)}function ym(c){var t=Am();return function(){var i=Fo(c),a;if(t){var n=Fo(this).constructor;a=Reflect.construct(i,arguments,n)}else a=i.apply(this,arguments);return Cm(this,a)}}function Cm(c,t){return t&&(Do(t)==="object"||typeof t=="function")?t:gd(c)}function gd(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Am(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Fo(c){return Fo=Object.setPrototypeOf?Object.getPrototypeOf:function(s){return s.__proto__||Object.getPrototypeOf(s)},Fo(c)}var Rm=dt.EventEmitter,Im=ht,mt=ot,bm=__,Xc=Cp,Zc=Pp,ef=Yp,Ua=dl,wm=tm,Jl=wt(),Om=Ks,Dm=Ys(),Nm=_d,ka=ys,xm=fm,Ma=Vu,qe=new Im("UA"),vt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},Um=function(c){Em(s,c);var t=ym(s);Qc(s,null,[{key:"C",get:function(){return vt}}]);function s(i){var a;if(Sm(this,s),qe.debug("new() [configuration:%o]",i),a=t.call(this),a._cache={credentials:{}},a._configuration=Object.assign({},Ma.settings),a._dynConfiguration={},a._dialogs={},a._applicants={},a._sessions={},a._transport=null,a._contact=null,a._status=vt.STATUS_INIT,a._error=null,a._transactions={nist:{},nict:{},ist:{},ict:{}},a._data={},a._closeTimer=null,i===void 0)throw new TypeError("Not enough arguments");try{a._loadConfig(i)}catch(n){throw a._status=vt.STATUS_NOT_READY,a._error=vt.CONFIGURATION_ERROR,n}return a._registrator=new bm(gd(a)),a}return Qc(s,[{key:"start",value:function(){qe.debug("start()"),this._status===vt.STATUS_INIT?this._transport.connect():this._status===vt.STATUS_USER_CLOSED?(qe.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=vt.STATUS_INIT,this._transport.connect()):this._status===vt.STATUS_READY?qe.debug("UA is in READY status, not restarted"):qe.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}},{key:"register",value:function(){qe.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}},{key:"unregister",value:function(a){qe.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(a)}},{key:"registrator",value:function(){return this._registrator}},{key:"isRegistered",value:function(){return this._registrator.registered}},{key:"isConnected",value:function(){return this._transport.isConnected()}},{key:"call",value:function(a,n){qe.debug("call()");var r=new Xc(this);return r.connect(a,n),r}},{key:"sendMessage",value:function(a,n,r){qe.debug("sendMessage()");var h=new Zc(this);return h.send(a,n,r),h}},{key:"sendOptions",value:function(a,n,r){qe.debug("sendOptions()");var h=new ef(this);return h.send(a,n,r),h}},{key:"terminateSessions",value:function(a){qe.debug("terminateSessions()");for(var n in this._sessions)this._sessions[n].isEnded()||this._sessions[n].terminate(a)}},{key:"stop",value:function(){var a=this;if(qe.debug("stop()"),this._dynConfiguration={},this._status===vt.STATUS_USER_CLOSED){qe.debug("UA already closed");return}this._registrator.close();var n=Object.keys(this._sessions).length;for(var r in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,r)){qe.debug("closing session ".concat(r));try{this._sessions[r].terminate()}catch{}}for(var h in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,h))try{this._applicants[h].close()}catch{}this._status=vt.STATUS_USER_CLOSED;var d=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;d===0&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){a._closeTimer=null,a._transport.disconnect()},2e3)}},{key:"normalizeTarget",value:function(a){return Jl.normalizeTarget(a,this._configuration.hostport_params)}},{key:"get",value:function(a){switch(a){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:qe.warn('get() | cannot get "%s" parameter in runtime',a);return}}},{key:"set",value:function(a,n){switch(a){case"authorization_user":{this._configuration.authorization_user=String(n);break}case"password":{this._configuration.password=String(n);break}case"realm":{this._configuration.realm=String(n);break}case"ha1":{this._configuration.ha1=String(n),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(n);break}case"display_name":{this._configuration.display_name=n;break}default:return qe.warn('set() | cannot set "%s" parameter in runtime',a),!1}return!0}},{key:"newTransaction",value:function(a){this._transactions[a.type][a.id]=a,this.emit("newTransaction",{transaction:a})}},{key:"destroyTransaction",value:function(a){delete this._transactions[a.type][a.id],this.emit("transactionDestroyed",{transaction:a})}},{key:"newDialog",value:function(a){this._dialogs[a.id]=a}},{key:"destroyDialog",value:function(a){delete this._dialogs[a.id]}},{key:"newMessage",value:function(a,n){this._applicants[a]=a,this.emit("newMessage",n)}},{key:"newOptions",value:function(a,n){this._applicants[a]=a,this.emit("newOptions",n)}},{key:"destroyMessage",value:function(a){delete this._applicants[a]}},{key:"newRTCSession",value:function(a,n){this._sessions[a.id]=a,this.emit("newRTCSession",n)}},{key:"destroyRTCSession",value:function(a){delete this._sessions[a.id]}},{key:"registered",value:function(a){this.emit("registered",a)}},{key:"unregistered",value:function(a){this.emit("unregistered",a)}},{key:"registrationFailed",value:function(a){this.emit("registrationFailed",a)}},{key:"receiveRequest",value:function(a){var n=a.method;if(a.ruri.user!==this._configuration.uri.user&&a.ruri.user!==this._contact.uri.user){qe.debug("Request-URI does not point to us"),a.method!==mt.ACK&&a.reply_sl(404);return}if(a.ruri.scheme===mt.SIPS){a.reply_sl(416);return}if(!Ua.checkTransaction(this,a)){if(n===mt.INVITE?new Ua.InviteServerTransaction(this,this._transport,a):n!==mt.ACK&&n!==mt.CANCEL&&new Ua.NonInviteServerTransaction(this,this._transport,a),n===mt.OPTIONS){if(this.listeners("newOptions").length===0){a.reply(200);return}var r=new ef(this);r.init_incoming(a)}else if(n===mt.MESSAGE){if(this.listeners("newMessage").length===0){a.reply(405);return}var h=new Zc(this);h.init_incoming(a)}else if(n===mt.INVITE&&!a.to_tag&&this.listeners("newRTCSession").length===0){a.reply(405);return}var d,_;if(a.to_tag)d=this._findDialog(a.call_id,a.from_tag,a.to_tag),d?d.receiveRequest(a):n===mt.NOTIFY?(_=this._findSession(a),_?_.receiveRequest(a):(qe.debug("received NOTIFY request for a non existent subscription"),a.reply(481,"Subscription does not exist"))):n!==mt.ACK&&a.reply(481);else switch(n){case mt.INVITE:if(window.RTCPeerConnection)if(a.hasHeader("replaces")){var g=a.replaces;d=this._findDialog(g.call_id,g.from_tag,g.to_tag),d?(_=d.owner,_.isEnded()?a.reply(603):_.receiveRequest(a)):a.reply(481)}else _=new Xc(this),_.init_incoming(a);else qe.warn("INVITE received but WebRTC is not supported"),a.reply(488);break;case mt.BYE:a.reply(481);break;case mt.CANCEL:_=this._findSession(a),_?_.receiveRequest(a):qe.debug("received CANCEL request for a non existent session");break;case mt.ACK:break;case mt.NOTIFY:this.emit("sipEvent",{event:a.event,request:a}),a.reply(200);break;default:a.reply(405);break}}}},{key:"_findSession",value:function(a){var n=a.call_id,r=a.from_tag,h=a.to_tag,d=n+r,_=this._sessions[d],g=n+h,T=this._sessions[g];return _||T||null}},{key:"_findDialog",value:function(a,n,r){var h=a+n+r,d=this._dialogs[h];return d||(h=a+r+n,d=this._dialogs[h],d||null)}},{key:"_loadConfig",value:function(a){try{Ma.load(this._configuration,a)}catch(g){throw g}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Jl.newUUID()),this._configuration.jssip_id=Jl.createRandomToken(5);var n=this._configuration.uri.clone();n.user=null,this._configuration.hostport_params=n.toString().replace(/^sip:/i,"");try{this._transport=new wm(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=km.bind(this),this._transport.onconnect=Mm.bind(this),this._transport.ondisconnect=Pm.bind(this),this._transport.ondata=Lm.bind(this)}catch(g){throw qe.warn(g),new Om.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){var r=this._configuration.uri.clone();r.user=null,r.clearParams(),r.clearHeaders(),this._configuration.registrar_server=r}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Dm("sip",Jl.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString:function(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},S=T.anonymous||null,E=T.outbound||null,C="<";return S?C+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":C+=this.pub_gruu||this.uri.toString(),E&&(S?!this.temp_gruu:!this.pub_gruu)&&(C+=";ob"),C+=">",C}};var h=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var d in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,d)&&(h.indexOf(d)!==-1?Object.defineProperty(this._configuration,d,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,d,{writable:!1,configurable:!1}));qe.debug("configuration parameters after validation:");for(var _ in this._configuration)if(Object.prototype.hasOwnProperty.call(Ma.settings,_))switch(_){case"uri":case"registrar_server":qe.debug("- ".concat(_,": ").concat(this._configuration[_]));break;case"password":case"ha1":case"authorization_jwt":qe.debug("- ".concat(_,": NOT SHOWN"));break;default:qe.debug("- ".concat(_,": ").concat(JSON.stringify(this._configuration[_])))}}},{key:"C",get:function(){return vt}},{key:"status",get:function(){return this._status}},{key:"contact",get:function(){return this._contact}},{key:"configuration",get:function(){return this._configuration}},{key:"transport",get:function(){return this._transport}}]),s}(Rm);function km(c){this.emit("connecting",c)}function Mm(c){this._status!==vt.STATUS_USER_CLOSED&&(this._status=vt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function Pm(c){for(var t=["nict","ict","nist","ist"],s=0,i=t;s<i.length;s++){var a=i[s];for(var n in this._transactions[a])Object.prototype.hasOwnProperty.call(this._transactions[a],n)&&this._transactions[a][n].onTransportError()}this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==vt.STATUS_USER_CLOSED&&(this._status=vt.STATUS_NOT_READY,this._error=vt.NETWORK_ERROR)}function Lm(c){var t=c.transport,s=c.message;if(s=Nm.parseMessage(s,this),!!s&&!(this._status===vt.STATUS_USER_CLOSED&&s instanceof ka.IncomingRequest)&&xm(s,this,t)){if(s instanceof ka.IncomingRequest)s.transport=t,this.receiveRequest(s);else if(s instanceof ka.IncomingResponse){var i;switch(s.method){case mt.INVITE:i=this._transactions.ict[s.via_branch],i&&i.receiveResponse(s);break;case mt.ACK:break;default:i=this._transactions.nict[s.via_branch],i&&i.receiveResponse(s);break}}}}function $m(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function tf(c,t){for(var s=0;s<t.length;s++){var i=t[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(c,i.key,i)}}function Hm(c,t,s){return t&&tf(c.prototype,t),s&&tf(c,s),c}var Fm=ht,Vm=us(),Dt=new Fm("WebSocketInterface"),jm=function(){function c(t){$m(this,c),Dt.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var s=Vm.parse(t,"absoluteURI");if(s===-1)throw Dt.warn("invalid WebSocket URI: ".concat(t)),new TypeError("Invalid argument: ".concat(t));if(s.scheme!=="wss"&&s.scheme!=="ws")throw Dt.warn("invalid WebSocket URI scheme: ".concat(s.scheme)),new TypeError("Invalid argument: ".concat(t));this._sip_uri="sip:".concat(s.host).concat(s.port?":".concat(s.port):"",";transport=ws"),this._via_transport=s.scheme.toUpperCase()}return Hm(c,[{key:"connect",value:function(){if(Dt.debug("connect()"),this.isConnected()){Dt.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){Dt.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),Dt.debug("connecting to WebSocket ".concat(this._url));try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(s){this._onError(s)}}},{key:"disconnect",value:function(){Dt.debug("disconnect()"),this._ws&&(this._ws.onopen=function(){},this._ws.onclose=function(){},this._ws.onmessage=function(){},this._ws.onerror=function(){},this._ws.close(),this._ws=null)}},{key:"send",value:function(s){return Dt.debug("send()"),this.isConnected()?(this._ws.send(s),!0):(Dt.warn("unable to send message, WebSocket is not open"),!1)}},{key:"isConnected",value:function(){return this._ws&&this._ws.readyState===this._ws.OPEN}},{key:"isConnecting",value:function(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}},{key:"_onOpen",value:function(){Dt.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(s){var i=s.wasClean,a=s.code,n=s.reason;Dt.debug("WebSocket ".concat(this._url," closed")),i===!1&&Dt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!i,a,n)}},{key:"_onMessage",value:function(s){var i=s.data;Dt.debug("received WebSocket message"),this.ondata(i)}},{key:"_onError",value:function(s){Dt.warn("WebSocket ".concat(this._url," error: "),s)}},{key:"via_transport",get:function(){return this._via_transport},set:function(s){this._via_transport=s.toUpperCase()}},{key:"sip_uri",get:function(){return this._sip_uri}},{key:"url",get:function(){return this._url}}]),c}(),Ru=jo,qm=ot,Bm=Ks,Gm=wt(),Wm=Um,Km=Ys(),Ym=Uu(),Jm=us(),zm=jm,Qm=gr("JsSIP");Qm("version %s",Ru.version);var sf={C:qm,Exceptions:Bm,Utils:Gm,UA:Wm,URI:Km,NameAddrHeader:Ym,WebSocketInterface:zm,Grammar:Jm,debug:gr,get name(){return Ru.title},get version(){return Ru.version}};const ar=gr,ur="JsSIP";var ct=class{constructor(t){t?(this._debug=ar.default(`${ur}:${t}`),this._warn=ar.default(`${ur}:WARN:${t}`),this._error=ar.default(`${ur}:ERROR:${t}`)):(this._debug=ar.default(ur),this._warn=ar.default(`${ur}:WARN`),this._error=ar.default(`${ur}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};const Yo=Xe(ct),nf=jo;var De={USER_AGENT:`${nf.title} ${nf.version}`,SIP:"sip",SIPS:"sips",causes:{CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:"Request Timeout",SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:"Rejected",REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:"Terminated",WEBRTC_ERROR:"WebRTC Error",CANCELED:"Canceled",NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:"ACK",BYE:"BYE",CANCEL:"CANCEL",INFO:"INFO",INVITE:"INVITE",MESSAGE:"MESSAGE",NOTIFY:"NOTIFY",OPTIONS:"OPTIONS",REGISTER:"REGISTER",REFER:"REFER",UPDATE:"UPDATE",SUBSCRIBE:"SUBSCRIBE",DTMF_TRANSPORT:{INFO:"INFO",RFC2833:"RFC2833"},REASON_PHRASE:{100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",424:"Bad Location Information",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:"JsSIP Internal 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"},ALLOWED_METHODS:"INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY",ACCEPTED_BODY_TYPES:"application/sdp, application/dtmf-relay",MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60,CONNECTION_RECOVERY_MAX_INTERVAL:30,CONNECTION_RECOVERY_MIN_INTERVAL:2};const H=Xe(De);var st={},Pa,rf;function ju(){if(rf)return Pa;rf=1;const c=Cs(),t=es();return Pa=class Td{static parse(i){if(i=t.parse(i,"Name_Addr_Header"),i!==-1)return i}constructor(i,a,n){if(!i||!(i instanceof c))throw new TypeError('missing or invalid "uri" parameter');this._uri=i,this._parameters={},this.display_name=a;for(const r in n)Object.prototype.hasOwnProperty.call(n,r)&&this.setParam(r,n[r])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(i){this._display_name=i===0?"0":i}setParam(i,a){i&&(this._parameters[i.toLowerCase()]=typeof a>"u"||a===null?null:a.toString())}getParam(i){if(i)return this._parameters[i.toLowerCase()]}hasParam(i){if(i)return this._parameters.hasOwnProperty(i.toLowerCase())&&!0||!1}deleteParam(i){if(i=i.toLowerCase(),this._parameters.hasOwnProperty(i)){const a=this._parameters[i];return delete this._parameters[i],a}}clearParams(){this._parameters={}}clone(){return new Td(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let i=this._display_name?`"${this._quote(this._display_name)}" `:"";i+=`<${this._uri.toString()}>`;for(const a in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,a)&&(i+=`;${a}`,this._parameters[a]!==null&&(i+=`=${this._parameters[a]}`));return i}},Pa}var La,lf;function es(){return lf||(lf=1,La=function(){function c(s){return'"'+s.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+'"'}var t={parse:function(s,i){var a={CRLF:_,DIGIT:g,ALPHA:T,HEXDIG:S,WSP:E,OCTET:C,DQUOTE:A,SP:R,HTAB:F,alphanum:I,reserved:ie,unreserved:N,mark:$,escaped:ve,LWS:_e,SWS:U,HCOLON:x,TEXT_UTF8_TRIM:q,TEXT_UTF8char:j,UTF8_NONASCII:Y,UTF8_CONT:V,LHEX:Q,token:k,token_nodot:M,separators:B,word:Fe,STAR:X,SLASH:W,EQUAL:G,LPAREN:re,RPAREN:pe,RAQUOT:Ie,LAQUOT:ke,COMMA:Ae,SEMI:oe,COLON:ye,LDQUOT:rt,RDQUOT:at,comment:Ee,ctext:Ce,quoted_string:be,quoted_string_clean:Oe,qdtext:ge,quoted_pair:ue,SIP_URI_noparams:me,SIP_URI:we,uri_scheme:Ne,uri_scheme_sips:et,uri_scheme_sip:$e,userinfo:$t,user:_t,user_unreserved:wn,password:On,hostport:Js,host:ts,hostname:cs,domainlabel:zs,toplabel:Dn,IPv6reference:Nn,IPv6address:Qs,h16:Te,ls32:ae,IPv4address:ut,dec_octet:Kt,port:Rs,uri_parameters:Sr,uri_parameter:xn,transport_param:Un,user_param:Er,method_param:yr,ttl_param:Cr,maddr_param:Ar,lr_param:Rr,other_param:Ir,pname:br,pvalue:wr,paramchar:Is,param_unreserved:bs,headers:Or,header:Xs,hname:Zs,hvalue:Dr,hnv_unreserved:ws,Request_Response:en,Request_Line:gl,Request_URI:Nr,absoluteURI:kn,hier_part:Mn,net_path:xr,abs_path:tn,opaque_part:sn,uric:Os,uric_no_slash:Ds,path_segments:Ur,segment:nn,param:Ns,pchar:fs,scheme:xs,authority:kr,srvr:Mr,reg_name:Pr,query:Lr,SIP_Version:Pn,INVITEm:Ln,ACKm:$r,OPTIONSm:Hr,BYEm:Fr,CANCELm:Vr,REGISTERm:jr,SUBSCRIBEm:qr,NOTIFYm:Br,REFERm:Gr,Method:rn,Status_Line:ln,Status_Code:Wr,extension_code:Kr,Reason_Phrase:Yr,Allow_Events:Tl,Call_ID:Qo,Contact:Xo,contact_param:$n,name_addr:Ht,display_name:Ft,contact_params:Us,c_p_q:Hn,c_p_expires:Jr,delta_seconds:ss,qvalue:ns,generic_param:Ke,gen_value:Ye,Content_Disposition:vl,disp_type:Sl,disp_param:Fn,handling_param:Vn,Content_Encoding:El,Content_Length:Zo,Content_Type:ea,media_type:yl,m_type:zr,discrete_type:Qr,composite_type:Xr,extension_token:on,x_token:an,m_subtype:Zr,m_parameter:jn,m_value:qn,CSeq:Cl,CSeq_value:Al,Expires:Rl,Event:ta,event_type:un,From:cn,from_param:ei,tag_param:fn,Max_Forwards:ti,Min_Expires:sa,Name_Addr_Header:na,Proxy_Authenticate:ra,challenge:si,other_challenge:Bn,auth_param:ks,digest_cln:rs,realm:dn,realm_value:ni,domain:ri,URI:hn,nonce:_n,nonce_value:ii,opaque:li,stale:oi,algorithm:ai,qop_options:ui,qop_value:pn,Proxy_Require:Gn,Record_Route:ia,rec_route:Wn,Reason:Kn,reason_param:ci,reason_cause:Yn,Require:Il,Route:la,route_param:Jn,Subscription_State:zn,substate_value:bl,subexp_params:Qn,event_reason_value:Xn,Subject:wl,Supported:oa,To:aa,to_param:fi,Via:di,via_param:Zn,via_params:Ms,via_ttl:er,via_maddr:hi,via_received:_i,via_branch:pi,response_port:mi,rport:gi,sent_protocol:Ti,protocol_name:vi,transport:Si,sent_by:Ei,via_host:yi,via_port:Ci,ttl:tr,WWW_Authenticate:Ai,Session_Expires:ua,s_e_expires:Ol,s_e_params:sr,s_e_refresher:nr,extension_header:Dl,header_value:Nl,message_body:xl,uuid_URI:ca,uuid:Ul,hex4:Vt,hex8:jt,hex12:Ri,Refer_To:kl,Replaces:fa,call_id:Ml,replaces_param:rr,to_tag:ir,from_tag:Ii,early_flag:bi};if(i!==void 0){if(a[i]===void 0)throw new Error("Invalid rule name: "+c(i)+".")}else i="CRLF";var n=0,r=0,h=[];function d(l){n<r||(n>r&&(r=n,h=[]),h.push(l))}function _(){var l;return s.substr(n,2)===`\r
|
|
73
|
+
`?(l=`\r
|
|
74
|
+
`,n+=2):(l=null,d('"\\r\\n"')),l}function g(){var l;return/^[0-9]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[0-9]")),l}function T(){var l;return/^[a-zA-Z]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[a-zA-Z]")),l}function S(){var l;return/^[0-9a-fA-F]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[0-9a-fA-F]")),l}function E(){var l;return l=R(),l===null&&(l=F()),l}function C(){var l;return/^[\0-\xFF]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[\\0-\\xFF]")),l}function A(){var l;return/^["]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d('["]')),l}function R(){var l;return s.charCodeAt(n)===32?(l=" ",n++):(l=null,d('" "')),l}function F(){var l;return s.charCodeAt(n)===9?(l=" ",n++):(l=null,d('"\\t"')),l}function I(){var l;return/^[a-zA-Z0-9]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[a-zA-Z0-9]")),l}function ie(){var l;return s.charCodeAt(n)===59?(l=";",n++):(l=null,d('";"')),l===null&&(s.charCodeAt(n)===47?(l="/",n++):(l=null,d('"/"')),l===null&&(s.charCodeAt(n)===63?(l="?",n++):(l=null,d('"?"')),l===null&&(s.charCodeAt(n)===58?(l=":",n++):(l=null,d('":"')),l===null&&(s.charCodeAt(n)===64?(l="@",n++):(l=null,d('"@"')),l===null&&(s.charCodeAt(n)===38?(l="&",n++):(l=null,d('"&"')),l===null&&(s.charCodeAt(n)===61?(l="=",n++):(l=null,d('"="')),l===null&&(s.charCodeAt(n)===43?(l="+",n++):(l=null,d('"+"')),l===null&&(s.charCodeAt(n)===36?(l="$",n++):(l=null,d('"$"')),l===null&&(s.charCodeAt(n)===44?(l=",",n++):(l=null,d('","'))))))))))),l}function N(){var l;return l=I(),l===null&&(l=$()),l}function $(){var l;return s.charCodeAt(n)===45?(l="-",n++):(l=null,d('"-"')),l===null&&(s.charCodeAt(n)===95?(l="_",n++):(l=null,d('"_"')),l===null&&(s.charCodeAt(n)===46?(l=".",n++):(l=null,d('"."')),l===null&&(s.charCodeAt(n)===33?(l="!",n++):(l=null,d('"!"')),l===null&&(s.charCodeAt(n)===126?(l="~",n++):(l=null,d('"~"')),l===null&&(s.charCodeAt(n)===42?(l="*",n++):(l=null,d('"*"')),l===null&&(s.charCodeAt(n)===39?(l="'",n++):(l=null,d(`"'"`)),l===null&&(s.charCodeAt(n)===40?(l="(",n++):(l=null,d('"("')),l===null&&(s.charCodeAt(n)===41?(l=")",n++):(l=null,d('")"')))))))))),l}function ve(){var l,e,o,u,f;return u=n,f=n,s.charCodeAt(n)===37?(l="%",n++):(l=null,d('"%"')),l!==null?(e=S(),e!==null?(o=S(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){return m.join("")}(u,l)),l===null&&(n=u),l}function _e(){var l,e,o,u,f,p;for(u=n,f=n,p=n,l=[],e=E();e!==null;)l.push(e),e=E();if(l!==null?(e=_(),e!==null?l=[l,e]:(l=null,n=p)):(l=null,n=p),l=l!==null?l:"",l!==null){if(o=E(),o!==null)for(e=[];o!==null;)e.push(o),o=E();else e=null;e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l!==null&&(l=function(m){return" "}()),l===null&&(n=u),l}function U(){var l;return l=_e(),l=l!==null?l:"",l}function x(){var l,e,o,u,f;for(u=n,f=n,l=[],e=R(),e===null&&(e=F());e!==null;)l.push(e),e=R(),e===null&&(e=F());return l!==null?(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=U(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return":"}()),l===null&&(n=u),l}function q(){var l,e,o,u,f,p,m;if(f=n,p=n,e=j(),e!==null)for(l=[];e!==null;)l.push(e),e=j();else l=null;if(l!==null){for(e=[],m=n,o=[],u=_e();u!==null;)o.push(u),u=_e();for(o!==null?(u=j(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;){for(e.push(o),m=n,o=[],u=_e();u!==null;)o.push(u),u=_e();o!==null?(u=j(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m)}e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v){return s.substring(n,v)}(f)),l===null&&(n=f),l}function j(){var l;return/^[!-~]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[!-~]")),l===null&&(l=Y()),l}function Y(){var l;return/^[\x80-\uFFFF]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[\\x80-\\uFFFF]")),l}function V(){var l;return/^[\x80-\xBF]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[\\x80-\\xBF]")),l}function Q(){var l;return l=g(),l===null&&(/^[a-f]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[a-f]"))),l}function k(){var l,e,o;if(o=n,e=I(),e===null&&(s.charCodeAt(n)===45?(e="-",n++):(e=null,d('"-"')),e===null&&(s.charCodeAt(n)===46?(e=".",n++):(e=null,d('"."')),e===null&&(s.charCodeAt(n)===33?(e="!",n++):(e=null,d('"!"')),e===null&&(s.charCodeAt(n)===37?(e="%",n++):(e=null,d('"%"')),e===null&&(s.charCodeAt(n)===42?(e="*",n++):(e=null,d('"*"')),e===null&&(s.charCodeAt(n)===95?(e="_",n++):(e=null,d('"_"')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"')),e===null&&(s.charCodeAt(n)===96?(e="`",n++):(e=null,d('"`"')),e===null&&(s.charCodeAt(n)===39?(e="'",n++):(e=null,d(`"'"`)),e===null&&(s.charCodeAt(n)===126?(e="~",n++):(e=null,d('"~"')))))))))))),e!==null)for(l=[];e!==null;)l.push(e),e=I(),e===null&&(s.charCodeAt(n)===45?(e="-",n++):(e=null,d('"-"')),e===null&&(s.charCodeAt(n)===46?(e=".",n++):(e=null,d('"."')),e===null&&(s.charCodeAt(n)===33?(e="!",n++):(e=null,d('"!"')),e===null&&(s.charCodeAt(n)===37?(e="%",n++):(e=null,d('"%"')),e===null&&(s.charCodeAt(n)===42?(e="*",n++):(e=null,d('"*"')),e===null&&(s.charCodeAt(n)===95?(e="_",n++):(e=null,d('"_"')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"')),e===null&&(s.charCodeAt(n)===96?(e="`",n++):(e=null,d('"`"')),e===null&&(s.charCodeAt(n)===39?(e="'",n++):(e=null,d(`"'"`)),e===null&&(s.charCodeAt(n)===126?(e="~",n++):(e=null,d('"~"'))))))))))));else l=null;return l!==null&&(l=function(u){return s.substring(n,u)}(o)),l===null&&(n=o),l}function M(){var l,e,o;if(o=n,e=I(),e===null&&(s.charCodeAt(n)===45?(e="-",n++):(e=null,d('"-"')),e===null&&(s.charCodeAt(n)===33?(e="!",n++):(e=null,d('"!"')),e===null&&(s.charCodeAt(n)===37?(e="%",n++):(e=null,d('"%"')),e===null&&(s.charCodeAt(n)===42?(e="*",n++):(e=null,d('"*"')),e===null&&(s.charCodeAt(n)===95?(e="_",n++):(e=null,d('"_"')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"')),e===null&&(s.charCodeAt(n)===96?(e="`",n++):(e=null,d('"`"')),e===null&&(s.charCodeAt(n)===39?(e="'",n++):(e=null,d(`"'"`)),e===null&&(s.charCodeAt(n)===126?(e="~",n++):(e=null,d('"~"'))))))))))),e!==null)for(l=[];e!==null;)l.push(e),e=I(),e===null&&(s.charCodeAt(n)===45?(e="-",n++):(e=null,d('"-"')),e===null&&(s.charCodeAt(n)===33?(e="!",n++):(e=null,d('"!"')),e===null&&(s.charCodeAt(n)===37?(e="%",n++):(e=null,d('"%"')),e===null&&(s.charCodeAt(n)===42?(e="*",n++):(e=null,d('"*"')),e===null&&(s.charCodeAt(n)===95?(e="_",n++):(e=null,d('"_"')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"')),e===null&&(s.charCodeAt(n)===96?(e="`",n++):(e=null,d('"`"')),e===null&&(s.charCodeAt(n)===39?(e="'",n++):(e=null,d(`"'"`)),e===null&&(s.charCodeAt(n)===126?(e="~",n++):(e=null,d('"~"')))))))))));else l=null;return l!==null&&(l=function(u){return s.substring(n,u)}(o)),l===null&&(n=o),l}function B(){var l;return s.charCodeAt(n)===40?(l="(",n++):(l=null,d('"("')),l===null&&(s.charCodeAt(n)===41?(l=")",n++):(l=null,d('")"')),l===null&&(s.charCodeAt(n)===60?(l="<",n++):(l=null,d('"<"')),l===null&&(s.charCodeAt(n)===62?(l=">",n++):(l=null,d('">"')),l===null&&(s.charCodeAt(n)===64?(l="@",n++):(l=null,d('"@"')),l===null&&(s.charCodeAt(n)===44?(l=",",n++):(l=null,d('","')),l===null&&(s.charCodeAt(n)===59?(l=";",n++):(l=null,d('";"')),l===null&&(s.charCodeAt(n)===58?(l=":",n++):(l=null,d('":"')),l===null&&(s.charCodeAt(n)===92?(l="\\",n++):(l=null,d('"\\\\"')),l===null&&(l=A(),l===null&&(s.charCodeAt(n)===47?(l="/",n++):(l=null,d('"/"')),l===null&&(s.charCodeAt(n)===91?(l="[",n++):(l=null,d('"["')),l===null&&(s.charCodeAt(n)===93?(l="]",n++):(l=null,d('"]"')),l===null&&(s.charCodeAt(n)===63?(l="?",n++):(l=null,d('"?"')),l===null&&(s.charCodeAt(n)===61?(l="=",n++):(l=null,d('"="')),l===null&&(s.charCodeAt(n)===123?(l="{",n++):(l=null,d('"{"')),l===null&&(s.charCodeAt(n)===125?(l="}",n++):(l=null,d('"}"')),l===null&&(l=R(),l===null&&(l=F())))))))))))))))))),l}function Fe(){var l,e,o;if(o=n,e=I(),e===null&&(s.charCodeAt(n)===45?(e="-",n++):(e=null,d('"-"')),e===null&&(s.charCodeAt(n)===46?(e=".",n++):(e=null,d('"."')),e===null&&(s.charCodeAt(n)===33?(e="!",n++):(e=null,d('"!"')),e===null&&(s.charCodeAt(n)===37?(e="%",n++):(e=null,d('"%"')),e===null&&(s.charCodeAt(n)===42?(e="*",n++):(e=null,d('"*"')),e===null&&(s.charCodeAt(n)===95?(e="_",n++):(e=null,d('"_"')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"')),e===null&&(s.charCodeAt(n)===96?(e="`",n++):(e=null,d('"`"')),e===null&&(s.charCodeAt(n)===39?(e="'",n++):(e=null,d(`"'"`)),e===null&&(s.charCodeAt(n)===126?(e="~",n++):(e=null,d('"~"')),e===null&&(s.charCodeAt(n)===40?(e="(",n++):(e=null,d('"("')),e===null&&(s.charCodeAt(n)===41?(e=")",n++):(e=null,d('")"')),e===null&&(s.charCodeAt(n)===60?(e="<",n++):(e=null,d('"<"')),e===null&&(s.charCodeAt(n)===62?(e=">",n++):(e=null,d('">"')),e===null&&(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e===null&&(s.charCodeAt(n)===92?(e="\\",n++):(e=null,d('"\\\\"')),e===null&&(e=A(),e===null&&(s.charCodeAt(n)===47?(e="/",n++):(e=null,d('"/"')),e===null&&(s.charCodeAt(n)===91?(e="[",n++):(e=null,d('"["')),e===null&&(s.charCodeAt(n)===93?(e="]",n++):(e=null,d('"]"')),e===null&&(s.charCodeAt(n)===63?(e="?",n++):(e=null,d('"?"')),e===null&&(s.charCodeAt(n)===123?(e="{",n++):(e=null,d('"{"')),e===null&&(s.charCodeAt(n)===125?(e="}",n++):(e=null,d('"}"'))))))))))))))))))))))))),e!==null)for(l=[];e!==null;)l.push(e),e=I(),e===null&&(s.charCodeAt(n)===45?(e="-",n++):(e=null,d('"-"')),e===null&&(s.charCodeAt(n)===46?(e=".",n++):(e=null,d('"."')),e===null&&(s.charCodeAt(n)===33?(e="!",n++):(e=null,d('"!"')),e===null&&(s.charCodeAt(n)===37?(e="%",n++):(e=null,d('"%"')),e===null&&(s.charCodeAt(n)===42?(e="*",n++):(e=null,d('"*"')),e===null&&(s.charCodeAt(n)===95?(e="_",n++):(e=null,d('"_"')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"')),e===null&&(s.charCodeAt(n)===96?(e="`",n++):(e=null,d('"`"')),e===null&&(s.charCodeAt(n)===39?(e="'",n++):(e=null,d(`"'"`)),e===null&&(s.charCodeAt(n)===126?(e="~",n++):(e=null,d('"~"')),e===null&&(s.charCodeAt(n)===40?(e="(",n++):(e=null,d('"("')),e===null&&(s.charCodeAt(n)===41?(e=")",n++):(e=null,d('")"')),e===null&&(s.charCodeAt(n)===60?(e="<",n++):(e=null,d('"<"')),e===null&&(s.charCodeAt(n)===62?(e=">",n++):(e=null,d('">"')),e===null&&(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e===null&&(s.charCodeAt(n)===92?(e="\\",n++):(e=null,d('"\\\\"')),e===null&&(e=A(),e===null&&(s.charCodeAt(n)===47?(e="/",n++):(e=null,d('"/"')),e===null&&(s.charCodeAt(n)===91?(e="[",n++):(e=null,d('"["')),e===null&&(s.charCodeAt(n)===93?(e="]",n++):(e=null,d('"]"')),e===null&&(s.charCodeAt(n)===63?(e="?",n++):(e=null,d('"?"')),e===null&&(s.charCodeAt(n)===123?(e="{",n++):(e=null,d('"{"')),e===null&&(s.charCodeAt(n)===125?(e="}",n++):(e=null,d('"}"')))))))))))))))))))))))));else l=null;return l!==null&&(l=function(u){return s.substring(n,u)}(o)),l===null&&(n=o),l}function X(){var l,e,o,u,f;return u=n,f=n,l=U(),l!==null?(s.charCodeAt(n)===42?(e="*",n++):(e=null,d('"*"')),e!==null?(o=U(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return"*"}()),l===null&&(n=u),l}function W(){var l,e,o,u,f;return u=n,f=n,l=U(),l!==null?(s.charCodeAt(n)===47?(e="/",n++):(e=null,d('"/"')),e!==null?(o=U(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return"/"}()),l===null&&(n=u),l}function G(){var l,e,o,u,f;return u=n,f=n,l=U(),l!==null?(s.charCodeAt(n)===61?(e="=",n++):(e=null,d('"="')),e!==null?(o=U(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return"="}()),l===null&&(n=u),l}function re(){var l,e,o,u,f;return u=n,f=n,l=U(),l!==null?(s.charCodeAt(n)===40?(e="(",n++):(e=null,d('"("')),e!==null?(o=U(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return"("}()),l===null&&(n=u),l}function pe(){var l,e,o,u,f;return u=n,f=n,l=U(),l!==null?(s.charCodeAt(n)===41?(e=")",n++):(e=null,d('")"')),e!==null?(o=U(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return")"}()),l===null&&(n=u),l}function Ie(){var l,e,o,u;return o=n,u=n,s.charCodeAt(n)===62?(l=">",n++):(l=null,d('">"')),l!==null?(e=U(),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l!==null&&(l=function(f){return">"}()),l===null&&(n=o),l}function ke(){var l,e,o,u;return o=n,u=n,l=U(),l!==null?(s.charCodeAt(n)===60?(e="<",n++):(e=null,d('"<"')),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l!==null&&(l=function(f){return"<"}()),l===null&&(n=o),l}function Ae(){var l,e,o,u,f;return u=n,f=n,l=U(),l!==null?(s.charCodeAt(n)===44?(e=",",n++):(e=null,d('","')),e!==null?(o=U(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return","}()),l===null&&(n=u),l}function oe(){var l,e,o,u,f;return u=n,f=n,l=U(),l!==null?(s.charCodeAt(n)===59?(e=";",n++):(e=null,d('";"')),e!==null?(o=U(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return";"}()),l===null&&(n=u),l}function ye(){var l,e,o,u,f;return u=n,f=n,l=U(),l!==null?(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=U(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return":"}()),l===null&&(n=u),l}function rt(){var l,e,o,u;return o=n,u=n,l=U(),l!==null?(e=A(),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l!==null&&(l=function(f){return'"'}()),l===null&&(n=o),l}function at(){var l,e,o,u;return o=n,u=n,l=A(),l!==null?(e=U(),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l!==null&&(l=function(f){return'"'}()),l===null&&(n=o),l}function Ee(){var l,e,o,u;if(u=n,l=re(),l!==null){for(e=[],o=Ce(),o===null&&(o=ue(),o===null&&(o=Ee()));o!==null;)e.push(o),o=Ce(),o===null&&(o=ue(),o===null&&(o=Ee()));e!==null?(o=pe(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)}else l=null,n=u;return l}function Ce(){var l;return/^[!-']/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[!-']")),l===null&&(/^[*-[]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[*-[]")),l===null&&(/^[\]-~]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[\\]-~]")),l===null&&(l=Y(),l===null&&(l=_e())))),l}function be(){var l,e,o,u,f,p;if(f=n,p=n,l=U(),l!==null)if(e=A(),e!==null){for(o=[],u=ge(),u===null&&(u=ue());u!==null;)o.push(u),u=ge(),u===null&&(u=ue());o!==null?(u=A(),u!==null?l=[l,e,o,u]:(l=null,n=p)):(l=null,n=p)}else l=null,n=p;else l=null,n=p;return l!==null&&(l=function(m){return s.substring(n,m)}(f)),l===null&&(n=f),l}function Oe(){var l,e,o,u,f,p;if(f=n,p=n,l=U(),l!==null)if(e=A(),e!==null){for(o=[],u=ge(),u===null&&(u=ue());u!==null;)o.push(u),u=ge(),u===null&&(u=ue());o!==null?(u=A(),u!==null?l=[l,e,o,u]:(l=null,n=p)):(l=null,n=p)}else l=null,n=p;else l=null,n=p;return l!==null&&(l=function(m){var v=s.substring(n,m).trim();return v.substring(1,v.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(f)),l===null&&(n=f),l}function ge(){var l;return l=_e(),l===null&&(s.charCodeAt(n)===33?(l="!",n++):(l=null,d('"!"')),l===null&&(/^[#-[]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[#-[]")),l===null&&(/^[\]-~]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[\\]-~]")),l===null&&(l=Y())))),l}function ue(){var l,e,o;return o=n,s.charCodeAt(n)===92?(l="\\",n++):(l=null,d('"\\\\"')),l!==null?(/^[\0-\t]/.test(s.charAt(n))?(e=s.charAt(n),n++):(e=null,d("[\\0-\\t]")),e===null&&(/^[\x0B-\f]/.test(s.charAt(n))?(e=s.charAt(n),n++):(e=null,d("[\\x0B-\\f]")),e===null&&(/^[\x0E-]/.test(s.charAt(n))?(e=s.charAt(n),n++):(e=null,d("[\\x0E-]")))),e!==null?l=[l,e]:(l=null,n=o)):(l=null,n=o),l}function me(){var l,e,o,u,f,p;return f=n,p=n,l=Ne(),l!==null?(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=$t(),o=o!==null?o:"",o!==null?(u=Js(),u!==null?l=[l,e,o,u]:(l=null,n=p)):(l=null,n=p)):(l=null,n=p)):(l=null,n=p),l!==null&&(l=function(m){try{w.uri=new Ll(w.scheme,w.user,w.host,w.port),delete w.scheme,delete w.user,delete w.host,delete w.host_type,delete w.port}catch{w=-1}}()),l===null&&(n=f),l}function we(){var l,e,o,u,f,p,m,v;return m=n,v=n,l=Ne(),l!==null?(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=$t(),o=o!==null?o:"",o!==null?(u=Js(),u!==null?(f=Sr(),f!==null?(p=Or(),p=p!==null?p:"",p!==null?l=[l,e,o,u,f,p]:(l=null,n=v)):(l=null,n=v)):(l=null,n=v)):(l=null,n=v)):(l=null,n=v)):(l=null,n=v),l!==null&&(l=function(y){try{w.uri=new Ll(w.scheme,w.user,w.host,w.port,w.uri_params,w.uri_headers),delete w.scheme,delete w.user,delete w.host,delete w.host_type,delete w.port,delete w.uri_params,i==="SIP_URI"&&(w=w.uri)}catch{w=-1}}()),l===null&&(n=m),l}function Ne(){var l;return l=et(),l===null&&(l=$e()),l}function et(){var l,e;return e=n,s.substr(n,4).toLowerCase()==="sips"?(l=s.substr(n,4),n+=4):(l=null,d('"sips"')),l!==null&&(l=function(o,u){w.scheme=u.toLowerCase()}(e,l)),l===null&&(n=e),l}function $e(){var l,e;return e=n,s.substr(n,3).toLowerCase()==="sip"?(l=s.substr(n,3),n+=3):(l=null,d('"sip"')),l!==null&&(l=function(o,u){w.scheme=u.toLowerCase()}(e,l)),l===null&&(n=e),l}function $t(){var l,e,o,u,f,p;return u=n,f=n,l=_t(),l!==null?(p=n,s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=On(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e=e!==null?e:"",e!==null?(s.charCodeAt(n)===64?(o="@",n++):(o=null,d('"@"')),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(m){w.user=decodeURIComponent(s.substring(n-1,m))}(u)),l===null&&(n=u),l}function _t(){var l,e;if(e=N(),e===null&&(e=ve(),e===null&&(e=wn())),e!==null)for(l=[];e!==null;)l.push(e),e=N(),e===null&&(e=ve(),e===null&&(e=wn()));else l=null;return l}function wn(){var l;return s.charCodeAt(n)===38?(l="&",n++):(l=null,d('"&"')),l===null&&(s.charCodeAt(n)===61?(l="=",n++):(l=null,d('"="')),l===null&&(s.charCodeAt(n)===43?(l="+",n++):(l=null,d('"+"')),l===null&&(s.charCodeAt(n)===36?(l="$",n++):(l=null,d('"$"')),l===null&&(s.charCodeAt(n)===44?(l=",",n++):(l=null,d('","')),l===null&&(s.charCodeAt(n)===59?(l=";",n++):(l=null,d('";"')),l===null&&(s.charCodeAt(n)===63?(l="?",n++):(l=null,d('"?"')),l===null&&(s.charCodeAt(n)===47?(l="/",n++):(l=null,d('"/"'))))))))),l}function On(){var l,e,o;for(o=n,l=[],e=N(),e===null&&(e=ve(),e===null&&(s.charCodeAt(n)===38?(e="&",n++):(e=null,d('"&"')),e===null&&(s.charCodeAt(n)===61?(e="=",n++):(e=null,d('"="')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"')),e===null&&(s.charCodeAt(n)===36?(e="$",n++):(e=null,d('"$"')),e===null&&(s.charCodeAt(n)===44?(e=",",n++):(e=null,d('","'))))))));e!==null;)l.push(e),e=N(),e===null&&(e=ve(),e===null&&(s.charCodeAt(n)===38?(e="&",n++):(e=null,d('"&"')),e===null&&(s.charCodeAt(n)===61?(e="=",n++):(e=null,d('"="')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"')),e===null&&(s.charCodeAt(n)===36?(e="$",n++):(e=null,d('"$"')),e===null&&(s.charCodeAt(n)===44?(e=",",n++):(e=null,d('","'))))))));return l!==null&&(l=function(u){w.password=s.substring(n,u)}(o)),l===null&&(n=o),l}function Js(){var l,e,o,u,f;return u=n,l=ts(),l!==null?(f=n,s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Rs(),o!==null?e=[e,o]:(e=null,n=f)):(e=null,n=f),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l}function ts(){var l,e;return e=n,l=cs(),l===null&&(l=ut(),l===null&&(l=Nn())),l!==null&&(l=function(o){return w.host=s.substring(n,o).toLowerCase(),w.host}(e)),l===null&&(n=e),l}function cs(){var l,e,o,u,f,p;for(u=n,f=n,l=[],p=n,e=zs(),e!==null?(s.charCodeAt(n)===46?(o=".",n++):(o=null,d('"."')),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p);e!==null;)l.push(e),p=n,e=zs(),e!==null?(s.charCodeAt(n)===46?(o=".",n++):(o=null,d('"."')),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p);return l!==null?(e=Dn(),e!==null?(s.charCodeAt(n)===46?(o=".",n++):(o=null,d('"."')),o=o!==null?o:"",o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(m){return w.host_type="domain",s.substring(n,m)}(u)),l===null&&(n=u),l}function zs(){var l,e,o,u;if(u=n,l=I(),l!==null){for(e=[],o=I(),o===null&&(s.charCodeAt(n)===45?(o="-",n++):(o=null,d('"-"')),o===null&&(s.charCodeAt(n)===95?(o="_",n++):(o=null,d('"_"'))));o!==null;)e.push(o),o=I(),o===null&&(s.charCodeAt(n)===45?(o="-",n++):(o=null,d('"-"')),o===null&&(s.charCodeAt(n)===95?(o="_",n++):(o=null,d('"_"'))));e!==null?l=[l,e]:(l=null,n=u)}else l=null,n=u;return l}function Dn(){var l,e,o,u;if(u=n,l=T(),l!==null){for(e=[],o=I(),o===null&&(s.charCodeAt(n)===45?(o="-",n++):(o=null,d('"-"')),o===null&&(s.charCodeAt(n)===95?(o="_",n++):(o=null,d('"_"'))));o!==null;)e.push(o),o=I(),o===null&&(s.charCodeAt(n)===45?(o="-",n++):(o=null,d('"-"')),o===null&&(s.charCodeAt(n)===95?(o="_",n++):(o=null,d('"_"'))));e!==null?l=[l,e]:(l=null,n=u)}else l=null,n=u;return l}function Nn(){var l,e,o,u,f;return u=n,f=n,s.charCodeAt(n)===91?(l="[",n++):(l=null,d('"["')),l!==null?(e=Qs(),e!==null?(s.charCodeAt(n)===93?(o="]",n++):(o=null,d('"]"')),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p){return w.host_type="IPv6",s.substring(n,p)}(u)),l===null&&(n=u),l}function Qs(){var l,e,o,u,f,p,m,v,y,D,le,xe,Ot,Ps,L,b;return Ps=n,L=n,l=Te(),l!==null?(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?(s.charCodeAt(n)===58?(u=":",n++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?(s.charCodeAt(n)===58?(p=":",n++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?(s.charCodeAt(n)===58?(v=":",n++):(v=null,d('":"')),v!==null?(y=Te(),y!==null?(s.charCodeAt(n)===58?(D=":",n++):(D=null,d('":"')),D!==null?(le=Te(),le!==null?(s.charCodeAt(n)===58?(xe=":",n++):(xe=null,d('":"')),xe!==null?(Ot=ae(),Ot!==null?l=[l,e,o,u,f,p,m,v,y,D,le,xe,Ot]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,s.substr(n,2)==="::"?(l="::",n+=2):(l=null,d('"::"')),l!==null?(e=Te(),e!==null?(s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?(s.charCodeAt(n)===58?(f=":",n++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(s.charCodeAt(n)===58?(m=":",n++):(m=null,d('":"')),m!==null?(v=Te(),v!==null?(s.charCodeAt(n)===58?(y=":",n++):(y=null,d('":"')),y!==null?(D=Te(),D!==null?(s.charCodeAt(n)===58?(le=":",n++):(le=null,d('":"')),le!==null?(xe=ae(),xe!==null?l=[l,e,o,u,f,p,m,v,y,D,le,xe]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,s.substr(n,2)==="::"?(l="::",n+=2):(l=null,d('"::"')),l!==null?(e=Te(),e!==null?(s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?(s.charCodeAt(n)===58?(f=":",n++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(s.charCodeAt(n)===58?(m=":",n++):(m=null,d('":"')),m!==null?(v=Te(),v!==null?(s.charCodeAt(n)===58?(y=":",n++):(y=null,d('":"')),y!==null?(D=ae(),D!==null?l=[l,e,o,u,f,p,m,v,y,D]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,s.substr(n,2)==="::"?(l="::",n+=2):(l=null,d('"::"')),l!==null?(e=Te(),e!==null?(s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?(s.charCodeAt(n)===58?(f=":",n++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(s.charCodeAt(n)===58?(m=":",n++):(m=null,d('":"')),m!==null?(v=ae(),v!==null?l=[l,e,o,u,f,p,m,v]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,s.substr(n,2)==="::"?(l="::",n+=2):(l=null,d('"::"')),l!==null?(e=Te(),e!==null?(s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?(s.charCodeAt(n)===58?(f=":",n++):(f=null,d('":"')),f!==null?(p=ae(),p!==null?l=[l,e,o,u,f,p]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,s.substr(n,2)==="::"?(l="::",n+=2):(l=null,d('"::"')),l!==null?(e=Te(),e!==null?(s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=ae(),u!==null?l=[l,e,o,u]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,s.substr(n,2)==="::"?(l="::",n+=2):(l=null,d('"::"')),l!==null?(e=ae(),e!==null?l=[l,e]:(l=null,n=L)):(l=null,n=L),l===null&&(L=n,s.substr(n,2)==="::"?(l="::",n+=2):(l=null,d('"::"')),l!==null?(e=Te(),e!==null?l=[l,e]:(l=null,n=L)):(l=null,n=L),l===null&&(L=n,l=Te(),l!==null?(s.substr(n,2)==="::"?(e="::",n+=2):(e=null,d('"::"')),e!==null?(o=Te(),o!==null?(s.charCodeAt(n)===58?(u=":",n++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?(s.charCodeAt(n)===58?(p=":",n++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?(s.charCodeAt(n)===58?(v=":",n++):(v=null,d('":"')),v!==null?(y=Te(),y!==null?(s.charCodeAt(n)===58?(D=":",n++):(D=null,d('":"')),D!==null?(le=ae(),le!==null?l=[l,e,o,u,f,p,m,v,y,D,le]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,l=Te(),l!==null?(b=n,s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,n=b)):(e=null,n=b),e=e!==null?e:"",e!==null?(s.substr(n,2)==="::"?(o="::",n+=2):(o=null,d('"::"')),o!==null?(u=Te(),u!==null?(s.charCodeAt(n)===58?(f=":",n++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(s.charCodeAt(n)===58?(m=":",n++):(m=null,d('":"')),m!==null?(v=Te(),v!==null?(s.charCodeAt(n)===58?(y=":",n++):(y=null,d('":"')),y!==null?(D=ae(),D!==null?l=[l,e,o,u,f,p,m,v,y,D]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,l=Te(),l!==null?(b=n,s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,n=b)):(e=null,n=b),e=e!==null?e:"",e!==null?(b=n,s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,n=b)):(o=null,n=b),o=o!==null?o:"",o!==null?(s.substr(n,2)==="::"?(u="::",n+=2):(u=null,d('"::"')),u!==null?(f=Te(),f!==null?(s.charCodeAt(n)===58?(p=":",n++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?(s.charCodeAt(n)===58?(v=":",n++):(v=null,d('":"')),v!==null?(y=ae(),y!==null?l=[l,e,o,u,f,p,m,v,y]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,l=Te(),l!==null?(b=n,s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,n=b)):(e=null,n=b),e=e!==null?e:"",e!==null?(b=n,s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,n=b)):(o=null,n=b),o=o!==null?o:"",o!==null?(b=n,s.charCodeAt(n)===58?(u=":",n++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,n=b)):(u=null,n=b),u=u!==null?u:"",u!==null?(s.substr(n,2)==="::"?(f="::",n+=2):(f=null,d('"::"')),f!==null?(p=Te(),p!==null?(s.charCodeAt(n)===58?(m=":",n++):(m=null,d('":"')),m!==null?(v=ae(),v!==null?l=[l,e,o,u,f,p,m,v]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,l=Te(),l!==null?(b=n,s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,n=b)):(e=null,n=b),e=e!==null?e:"",e!==null?(b=n,s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,n=b)):(o=null,n=b),o=o!==null?o:"",o!==null?(b=n,s.charCodeAt(n)===58?(u=":",n++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,n=b)):(u=null,n=b),u=u!==null?u:"",u!==null?(b=n,s.charCodeAt(n)===58?(f=":",n++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,n=b)):(f=null,n=b),f=f!==null?f:"",f!==null?(s.substr(n,2)==="::"?(p="::",n+=2):(p=null,d('"::"')),p!==null?(m=ae(),m!==null?l=[l,e,o,u,f,p,m]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,l=Te(),l!==null?(b=n,s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,n=b)):(e=null,n=b),e=e!==null?e:"",e!==null?(b=n,s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,n=b)):(o=null,n=b),o=o!==null?o:"",o!==null?(b=n,s.charCodeAt(n)===58?(u=":",n++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,n=b)):(u=null,n=b),u=u!==null?u:"",u!==null?(b=n,s.charCodeAt(n)===58?(f=":",n++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,n=b)):(f=null,n=b),f=f!==null?f:"",f!==null?(b=n,s.charCodeAt(n)===58?(p=":",n++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?p=[p,m]:(p=null,n=b)):(p=null,n=b),p=p!==null?p:"",p!==null?(s.substr(n,2)==="::"?(m="::",n+=2):(m=null,d('"::"')),m!==null?(v=Te(),v!==null?l=[l,e,o,u,f,p,m,v]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L),l===null&&(L=n,l=Te(),l!==null?(b=n,s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?e=[e,o]:(e=null,n=b)):(e=null,n=b),e=e!==null?e:"",e!==null?(b=n,s.charCodeAt(n)===58?(o=":",n++):(o=null,d('":"')),o!==null?(u=Te(),u!==null?o=[o,u]:(o=null,n=b)):(o=null,n=b),o=o!==null?o:"",o!==null?(b=n,s.charCodeAt(n)===58?(u=":",n++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,n=b)):(u=null,n=b),u=u!==null?u:"",u!==null?(b=n,s.charCodeAt(n)===58?(f=":",n++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,n=b)):(f=null,n=b),f=f!==null?f:"",f!==null?(b=n,s.charCodeAt(n)===58?(p=":",n++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?p=[p,m]:(p=null,n=b)):(p=null,n=b),p=p!==null?p:"",p!==null?(b=n,s.charCodeAt(n)===58?(m=":",n++):(m=null,d('":"')),m!==null?(v=Te(),v!==null?m=[m,v]:(m=null,n=b)):(m=null,n=b),m=m!==null?m:"",m!==null?(s.substr(n,2)==="::"?(v="::",n+=2):(v=null,d('"::"')),v!==null?l=[l,e,o,u,f,p,m,v]:(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L)):(l=null,n=L))))))))))))))),l!==null&&(l=function(Se){return w.host_type="IPv6",s.substring(n,Se)}(Ps)),l===null&&(n=Ps),l}function Te(){var l,e,o,u,f;return f=n,l=S(),l!==null?(e=S(),e=e!==null?e:"",e!==null?(o=S(),o=o!==null?o:"",o!==null?(u=S(),u=u!==null?u:"",u!==null?l=[l,e,o,u]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l}function ae(){var l,e,o,u;return u=n,l=Te(),l!==null?(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Te(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l===null&&(l=ut()),l}function ut(){var l,e,o,u,f,p,m,v,y;return v=n,y=n,l=Kt(),l!==null?(s.charCodeAt(n)===46?(e=".",n++):(e=null,d('"."')),e!==null?(o=Kt(),o!==null?(s.charCodeAt(n)===46?(u=".",n++):(u=null,d('"."')),u!==null?(f=Kt(),f!==null?(s.charCodeAt(n)===46?(p=".",n++):(p=null,d('"."')),p!==null?(m=Kt(),m!==null?l=[l,e,o,u,f,p,m]:(l=null,n=y)):(l=null,n=y)):(l=null,n=y)):(l=null,n=y)):(l=null,n=y)):(l=null,n=y)):(l=null,n=y),l!==null&&(l=function(D){return w.host_type="IPv4",s.substring(n,D)}(v)),l===null&&(n=v),l}function Kt(){var l,e,o,u;return u=n,s.substr(n,2)==="25"?(l="25",n+=2):(l=null,d('"25"')),l!==null?(/^[0-5]/.test(s.charAt(n))?(e=s.charAt(n),n++):(e=null,d("[0-5]")),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l===null&&(u=n,s.charCodeAt(n)===50?(l="2",n++):(l=null,d('"2"')),l!==null?(/^[0-4]/.test(s.charAt(n))?(e=s.charAt(n),n++):(e=null,d("[0-4]")),e!==null?(o=g(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l===null&&(u=n,s.charCodeAt(n)===49?(l="1",n++):(l=null,d('"1"')),l!==null?(e=g(),e!==null?(o=g(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l===null&&(u=n,/^[1-9]/.test(s.charAt(n))?(l=s.charAt(n),n++):(l=null,d("[1-9]")),l!==null?(e=g(),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l===null&&(l=g())))),l}function Rs(){var l,e,o,u,f,p,m;return p=n,m=n,l=g(),l=l!==null?l:"",l!==null?(e=g(),e=e!==null?e:"",e!==null?(o=g(),o=o!==null?o:"",o!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?l=[l,e,o,u,f]:(l=null,n=m)):(l=null,n=m)):(l=null,n=m)):(l=null,n=m)):(l=null,n=m),l!==null&&(l=function(v,y){return y=parseInt(y.join("")),w.port=y,y}(p,l)),l===null&&(n=p),l}function Sr(){var l,e,o,u;for(l=[],u=n,s.charCodeAt(n)===59?(e=";",n++):(e=null,d('";"')),e!==null?(o=xn(),o!==null?e=[e,o]:(e=null,n=u)):(e=null,n=u);e!==null;)l.push(e),u=n,s.charCodeAt(n)===59?(e=";",n++):(e=null,d('";"')),e!==null?(o=xn(),o!==null?e=[e,o]:(e=null,n=u)):(e=null,n=u);return l}function xn(){var l;return l=Un(),l===null&&(l=Er(),l===null&&(l=yr(),l===null&&(l=Cr(),l===null&&(l=Ar(),l===null&&(l=Rr(),l===null&&(l=Ir())))))),l}function Un(){var l,e,o,u;return o=n,u=n,s.substr(n,10).toLowerCase()==="transport="?(l=s.substr(n,10),n+=10):(l=null,d('"transport="')),l!==null?(s.substr(n,3).toLowerCase()==="udp"?(e=s.substr(n,3),n+=3):(e=null,d('"udp"')),e===null&&(s.substr(n,3).toLowerCase()==="tcp"?(e=s.substr(n,3),n+=3):(e=null,d('"tcp"')),e===null&&(s.substr(n,4).toLowerCase()==="sctp"?(e=s.substr(n,4),n+=4):(e=null,d('"sctp"')),e===null&&(s.substr(n,3).toLowerCase()==="tls"?(e=s.substr(n,3),n+=3):(e=null,d('"tls"')),e===null&&(e=k())))),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l!==null&&(l=function(f,p){w.uri_params||(w.uri_params={}),w.uri_params.transport=p.toLowerCase()}(o,l[1])),l===null&&(n=o),l}function Er(){var l,e,o,u;return o=n,u=n,s.substr(n,5).toLowerCase()==="user="?(l=s.substr(n,5),n+=5):(l=null,d('"user="')),l!==null?(s.substr(n,5).toLowerCase()==="phone"?(e=s.substr(n,5),n+=5):(e=null,d('"phone"')),e===null&&(s.substr(n,2).toLowerCase()==="ip"?(e=s.substr(n,2),n+=2):(e=null,d('"ip"')),e===null&&(e=k())),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l!==null&&(l=function(f,p){w.uri_params||(w.uri_params={}),w.uri_params.user=p.toLowerCase()}(o,l[1])),l===null&&(n=o),l}function yr(){var l,e,o,u;return o=n,u=n,s.substr(n,7).toLowerCase()==="method="?(l=s.substr(n,7),n+=7):(l=null,d('"method="')),l!==null?(e=rn(),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l!==null&&(l=function(f,p){w.uri_params||(w.uri_params={}),w.uri_params.method=p}(o,l[1])),l===null&&(n=o),l}function Cr(){var l,e,o,u;return o=n,u=n,s.substr(n,4).toLowerCase()==="ttl="?(l=s.substr(n,4),n+=4):(l=null,d('"ttl="')),l!==null?(e=tr(),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l!==null&&(l=function(f,p){w.params||(w.params={}),w.params.ttl=p}(o,l[1])),l===null&&(n=o),l}function Ar(){var l,e,o,u;return o=n,u=n,s.substr(n,6).toLowerCase()==="maddr="?(l=s.substr(n,6),n+=6):(l=null,d('"maddr="')),l!==null?(e=ts(),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l!==null&&(l=function(f,p){w.uri_params||(w.uri_params={}),w.uri_params.maddr=p}(o,l[1])),l===null&&(n=o),l}function Rr(){var l,e,o,u,f,p;return u=n,f=n,s.substr(n,2).toLowerCase()==="lr"?(l=s.substr(n,2),n+=2):(l=null,d('"lr"')),l!==null?(p=n,s.charCodeAt(n)===61?(e="=",n++):(e=null,d('"="')),e!==null?(o=k(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(m){w.uri_params||(w.uri_params={}),w.uri_params.lr=void 0}()),l===null&&(n=u),l}function Ir(){var l,e,o,u,f,p;return u=n,f=n,l=br(),l!==null?(p=n,s.charCodeAt(n)===61?(e="=",n++):(e=null,d('"="')),e!==null?(o=wr(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(m,v,y){w.uri_params||(w.uri_params={}),typeof y>"u"?y=void 0:y=y[1],w.uri_params[v.toLowerCase()]=y}(u,l[0],l[1])),l===null&&(n=u),l}function br(){var l,e,o;if(o=n,e=Is(),e!==null)for(l=[];e!==null;)l.push(e),e=Is();else l=null;return l!==null&&(l=function(u,f){return f.join("")}(o,l)),l===null&&(n=o),l}function wr(){var l,e,o;if(o=n,e=Is(),e!==null)for(l=[];e!==null;)l.push(e),e=Is();else l=null;return l!==null&&(l=function(u,f){return f.join("")}(o,l)),l===null&&(n=o),l}function Is(){var l;return l=bs(),l===null&&(l=N(),l===null&&(l=ve())),l}function bs(){var l;return s.charCodeAt(n)===91?(l="[",n++):(l=null,d('"["')),l===null&&(s.charCodeAt(n)===93?(l="]",n++):(l=null,d('"]"')),l===null&&(s.charCodeAt(n)===47?(l="/",n++):(l=null,d('"/"')),l===null&&(s.charCodeAt(n)===58?(l=":",n++):(l=null,d('":"')),l===null&&(s.charCodeAt(n)===38?(l="&",n++):(l=null,d('"&"')),l===null&&(s.charCodeAt(n)===43?(l="+",n++):(l=null,d('"+"')),l===null&&(s.charCodeAt(n)===36?(l="$",n++):(l=null,d('"$"')))))))),l}function Or(){var l,e,o,u,f,p,m;if(p=n,s.charCodeAt(n)===63?(l="?",n++):(l=null,d('"?"')),l!==null)if(e=Xs(),e!==null){for(o=[],m=n,s.charCodeAt(n)===38?(u="&",n++):(u=null,d('"&"')),u!==null?(f=Xs(),f!==null?u=[u,f]:(u=null,n=m)):(u=null,n=m);u!==null;)o.push(u),m=n,s.charCodeAt(n)===38?(u="&",n++):(u=null,d('"&"')),u!==null?(f=Xs(),f!==null?u=[u,f]:(u=null,n=m)):(u=null,n=m);o!==null?l=[l,e,o]:(l=null,n=p)}else l=null,n=p;else l=null,n=p;return l}function Xs(){var l,e,o,u,f;return u=n,f=n,l=Zs(),l!==null?(s.charCodeAt(n)===61?(e="=",n++):(e=null,d('"="')),e!==null?(o=Dr(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m,v){m=m.join("").toLowerCase(),v=v.join(""),w.uri_headers||(w.uri_headers={}),w.uri_headers[m]?w.uri_headers[m].push(v):w.uri_headers[m]=[v]}(u,l[0],l[2])),l===null&&(n=u),l}function Zs(){var l,e;if(e=ws(),e===null&&(e=N(),e===null&&(e=ve())),e!==null)for(l=[];e!==null;)l.push(e),e=ws(),e===null&&(e=N(),e===null&&(e=ve()));else l=null;return l}function Dr(){var l,e;for(l=[],e=ws(),e===null&&(e=N(),e===null&&(e=ve()));e!==null;)l.push(e),e=ws(),e===null&&(e=N(),e===null&&(e=ve()));return l}function ws(){var l;return s.charCodeAt(n)===91?(l="[",n++):(l=null,d('"["')),l===null&&(s.charCodeAt(n)===93?(l="]",n++):(l=null,d('"]"')),l===null&&(s.charCodeAt(n)===47?(l="/",n++):(l=null,d('"/"')),l===null&&(s.charCodeAt(n)===63?(l="?",n++):(l=null,d('"?"')),l===null&&(s.charCodeAt(n)===58?(l=":",n++):(l=null,d('":"')),l===null&&(s.charCodeAt(n)===43?(l="+",n++):(l=null,d('"+"')),l===null&&(s.charCodeAt(n)===36?(l="$",n++):(l=null,d('"$"')))))))),l}function en(){var l;return l=ln(),l===null&&(l=gl()),l}function gl(){var l,e,o,u,f,p;return p=n,l=rn(),l!==null?(e=R(),e!==null?(o=Nr(),o!==null?(u=R(),u!==null?(f=Pn(),f!==null?l=[l,e,o,u,f]:(l=null,n=p)):(l=null,n=p)):(l=null,n=p)):(l=null,n=p)):(l=null,n=p),l}function Nr(){var l;return l=we(),l===null&&(l=kn()),l}function kn(){var l,e,o,u;return u=n,l=xs(),l!==null?(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e!==null?(o=Mn(),o===null&&(o=sn()),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function Mn(){var l,e,o,u,f;return u=n,l=xr(),l===null&&(l=tn()),l!==null?(f=n,s.charCodeAt(n)===63?(e="?",n++):(e=null,d('"?"')),e!==null?(o=Lr(),o!==null?e=[e,o]:(e=null,n=f)):(e=null,n=f),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l}function xr(){var l,e,o,u;return u=n,s.substr(n,2)==="//"?(l="//",n+=2):(l=null,d('"//"')),l!==null?(e=kr(),e!==null?(o=tn(),o=o!==null?o:"",o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function tn(){var l,e,o;return o=n,s.charCodeAt(n)===47?(l="/",n++):(l=null,d('"/"')),l!==null?(e=Ur(),e!==null?l=[l,e]:(l=null,n=o)):(l=null,n=o),l}function sn(){var l,e,o,u;if(u=n,l=Ds(),l!==null){for(e=[],o=Os();o!==null;)e.push(o),o=Os();e!==null?l=[l,e]:(l=null,n=u)}else l=null,n=u;return l}function Os(){var l;return l=ie(),l===null&&(l=N(),l===null&&(l=ve())),l}function Ds(){var l;return l=N(),l===null&&(l=ve(),l===null&&(s.charCodeAt(n)===59?(l=";",n++):(l=null,d('";"')),l===null&&(s.charCodeAt(n)===63?(l="?",n++):(l=null,d('"?"')),l===null&&(s.charCodeAt(n)===58?(l=":",n++):(l=null,d('":"')),l===null&&(s.charCodeAt(n)===64?(l="@",n++):(l=null,d('"@"')),l===null&&(s.charCodeAt(n)===38?(l="&",n++):(l=null,d('"&"')),l===null&&(s.charCodeAt(n)===61?(l="=",n++):(l=null,d('"="')),l===null&&(s.charCodeAt(n)===43?(l="+",n++):(l=null,d('"+"')),l===null&&(s.charCodeAt(n)===36?(l="$",n++):(l=null,d('"$"')),l===null&&(s.charCodeAt(n)===44?(l=",",n++):(l=null,d('","')))))))))))),l}function Ur(){var l,e,o,u,f,p;if(f=n,l=nn(),l!==null){for(e=[],p=n,s.charCodeAt(n)===47?(o="/",n++):(o=null,d('"/"')),o!==null?(u=nn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,s.charCodeAt(n)===47?(o="/",n++):(o=null,d('"/"')),o!==null?(u=nn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function nn(){var l,e,o,u,f,p;for(f=n,l=[],e=fs();e!==null;)l.push(e),e=fs();if(l!==null){for(e=[],p=n,s.charCodeAt(n)===59?(o=";",n++):(o=null,d('";"')),o!==null?(u=Ns(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,s.charCodeAt(n)===59?(o=";",n++):(o=null,d('";"')),o!==null?(u=Ns(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function Ns(){var l,e;for(l=[],e=fs();e!==null;)l.push(e),e=fs();return l}function fs(){var l;return l=N(),l===null&&(l=ve(),l===null&&(s.charCodeAt(n)===58?(l=":",n++):(l=null,d('":"')),l===null&&(s.charCodeAt(n)===64?(l="@",n++):(l=null,d('"@"')),l===null&&(s.charCodeAt(n)===38?(l="&",n++):(l=null,d('"&"')),l===null&&(s.charCodeAt(n)===61?(l="=",n++):(l=null,d('"="')),l===null&&(s.charCodeAt(n)===43?(l="+",n++):(l=null,d('"+"')),l===null&&(s.charCodeAt(n)===36?(l="$",n++):(l=null,d('"$"')),l===null&&(s.charCodeAt(n)===44?(l=",",n++):(l=null,d('","')))))))))),l}function xs(){var l,e,o,u,f;if(u=n,f=n,l=T(),l!==null){for(e=[],o=T(),o===null&&(o=g(),o===null&&(s.charCodeAt(n)===43?(o="+",n++):(o=null,d('"+"')),o===null&&(s.charCodeAt(n)===45?(o="-",n++):(o=null,d('"-"')),o===null&&(s.charCodeAt(n)===46?(o=".",n++):(o=null,d('"."'))))));o!==null;)e.push(o),o=T(),o===null&&(o=g(),o===null&&(s.charCodeAt(n)===43?(o="+",n++):(o=null,d('"+"')),o===null&&(s.charCodeAt(n)===45?(o="-",n++):(o=null,d('"-"')),o===null&&(s.charCodeAt(n)===46?(o=".",n++):(o=null,d('"."'))))));e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l!==null&&(l=function(p){w.scheme=s.substring(n,p)}(u)),l===null&&(n=u),l}function kr(){var l;return l=Mr(),l===null&&(l=Pr()),l}function Mr(){var l,e,o,u;return o=n,u=n,l=$t(),l!==null?(s.charCodeAt(n)===64?(e="@",n++):(e=null,d('"@"')),e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l=l!==null?l:"",l!==null?(e=Js(),e!==null?l=[l,e]:(l=null,n=o)):(l=null,n=o),l=l!==null?l:"",l}function Pr(){var l,e;if(e=N(),e===null&&(e=ve(),e===null&&(s.charCodeAt(n)===36?(e="$",n++):(e=null,d('"$"')),e===null&&(s.charCodeAt(n)===44?(e=",",n++):(e=null,d('","')),e===null&&(s.charCodeAt(n)===59?(e=";",n++):(e=null,d('";"')),e===null&&(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e===null&&(s.charCodeAt(n)===64?(e="@",n++):(e=null,d('"@"')),e===null&&(s.charCodeAt(n)===38?(e="&",n++):(e=null,d('"&"')),e===null&&(s.charCodeAt(n)===61?(e="=",n++):(e=null,d('"="')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"'))))))))))),e!==null)for(l=[];e!==null;)l.push(e),e=N(),e===null&&(e=ve(),e===null&&(s.charCodeAt(n)===36?(e="$",n++):(e=null,d('"$"')),e===null&&(s.charCodeAt(n)===44?(e=",",n++):(e=null,d('","')),e===null&&(s.charCodeAt(n)===59?(e=";",n++):(e=null,d('";"')),e===null&&(s.charCodeAt(n)===58?(e=":",n++):(e=null,d('":"')),e===null&&(s.charCodeAt(n)===64?(e="@",n++):(e=null,d('"@"')),e===null&&(s.charCodeAt(n)===38?(e="&",n++):(e=null,d('"&"')),e===null&&(s.charCodeAt(n)===61?(e="=",n++):(e=null,d('"="')),e===null&&(s.charCodeAt(n)===43?(e="+",n++):(e=null,d('"+"')))))))))));else l=null;return l}function Lr(){var l,e;for(l=[],e=Os();e!==null;)l.push(e),e=Os();return l}function Pn(){var l,e,o,u,f,p,m,v;if(m=n,v=n,s.substr(n,3).toLowerCase()==="sip"?(l=s.substr(n,3),n+=3):(l=null,d('"SIP"')),l!==null)if(s.charCodeAt(n)===47?(e="/",n++):(e=null,d('"/"')),e!==null){if(u=g(),u!==null)for(o=[];u!==null;)o.push(u),u=g();else o=null;if(o!==null)if(s.charCodeAt(n)===46?(u=".",n++):(u=null,d('"."')),u!==null){if(p=g(),p!==null)for(f=[];p!==null;)f.push(p),p=g();else f=null;f!==null?l=[l,e,o,u,f]:(l=null,n=v)}else l=null,n=v;else l=null,n=v}else l=null,n=v;else l=null,n=v;return l!==null&&(l=function(y){w.sip_version=s.substring(n,y)}(m)),l===null&&(n=m),l}function Ln(){var l;return s.substr(n,6)==="INVITE"?(l="INVITE",n+=6):(l=null,d('"INVITE"')),l}function $r(){var l;return s.substr(n,3)==="ACK"?(l="ACK",n+=3):(l=null,d('"ACK"')),l}function Hr(){var l;return s.substr(n,7)==="OPTIONS"?(l="OPTIONS",n+=7):(l=null,d('"OPTIONS"')),l}function Fr(){var l;return s.substr(n,3)==="BYE"?(l="BYE",n+=3):(l=null,d('"BYE"')),l}function Vr(){var l;return s.substr(n,6)==="CANCEL"?(l="CANCEL",n+=6):(l=null,d('"CANCEL"')),l}function jr(){var l;return s.substr(n,8)==="REGISTER"?(l="REGISTER",n+=8):(l=null,d('"REGISTER"')),l}function qr(){var l;return s.substr(n,9)==="SUBSCRIBE"?(l="SUBSCRIBE",n+=9):(l=null,d('"SUBSCRIBE"')),l}function Br(){var l;return s.substr(n,6)==="NOTIFY"?(l="NOTIFY",n+=6):(l=null,d('"NOTIFY"')),l}function Gr(){var l;return s.substr(n,5)==="REFER"?(l="REFER",n+=5):(l=null,d('"REFER"')),l}function rn(){var l,e;return e=n,l=Ln(),l===null&&(l=$r(),l===null&&(l=Hr(),l===null&&(l=Fr(),l===null&&(l=Vr(),l===null&&(l=jr(),l===null&&(l=qr(),l===null&&(l=Br(),l===null&&(l=Gr(),l===null&&(l=k()))))))))),l!==null&&(l=function(o){return w.method=s.substring(n,o),w.method}(e)),l===null&&(n=e),l}function ln(){var l,e,o,u,f,p;return p=n,l=Pn(),l!==null?(e=R(),e!==null?(o=Wr(),o!==null?(u=R(),u!==null?(f=Yr(),f!==null?l=[l,e,o,u,f]:(l=null,n=p)):(l=null,n=p)):(l=null,n=p)):(l=null,n=p)):(l=null,n=p),l}function Wr(){var l,e;return e=n,l=Kr(),l!==null&&(l=function(o,u){w.status_code=parseInt(u.join(""))}(e,l)),l===null&&(n=e),l}function Kr(){var l,e,o,u;return u=n,l=g(),l!==null?(e=g(),e!==null?(o=g(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function Yr(){var l,e,o;for(o=n,l=[],e=ie(),e===null&&(e=N(),e===null&&(e=ve(),e===null&&(e=Y(),e===null&&(e=V(),e===null&&(e=R(),e===null&&(e=F()))))));e!==null;)l.push(e),e=ie(),e===null&&(e=N(),e===null&&(e=ve(),e===null&&(e=Y(),e===null&&(e=V(),e===null&&(e=R(),e===null&&(e=F()))))));return l!==null&&(l=function(u){w.reason_phrase=s.substring(n,u)}(o)),l===null&&(n=o),l}function Tl(){var l,e,o,u,f,p;if(f=n,l=un(),l!==null){for(e=[],p=n,o=Ae(),o!==null?(u=un(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=Ae(),o!==null?(u=un(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function Qo(){var l,e,o,u,f,p;return u=n,f=n,l=Fe(),l!==null?(p=n,s.charCodeAt(n)===64?(e="@",n++):(e=null,d('"@"')),e!==null?(o=Fe(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(m){w=s.substring(n,m)}(u)),l===null&&(n=u),l}function Xo(){var l,e,o,u,f,p,m;if(f=n,l=X(),l===null)if(p=n,l=$n(),l!==null){for(e=[],m=n,o=Ae(),o!==null?(u=$n(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=Ae(),o!==null?(u=$n(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v){var y,D;for(D=w.multi_header.length,y=0;y<D;y++)if(w.multi_header[y].parsed===null){w=null;break}w!==null?w=w.multi_header:w=-1}()),l===null&&(n=f),l}function $n(){var l,e,o,u,f,p,m;if(f=n,p=n,l=me(),l===null&&(l=Ht()),l!==null){for(e=[],m=n,o=oe(),o!==null?(u=Us(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=oe(),o!==null?(u=Us(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v){var y;w.multi_header||(w.multi_header=[]);try{y=new ds(w.uri,w.display_name,w.params),delete w.uri,delete w.display_name,delete w.params}catch{y=null}w.multi_header.push({possition:n,offset:v,parsed:y})}(f)),l===null&&(n=f),l}function Ht(){var l,e,o,u,f;return f=n,l=Ft(),l=l!==null?l:"",l!==null?(e=ke(),e!==null?(o=we(),o!==null?(u=Ie(),u!==null?l=[l,e,o,u]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l}function Ft(){var l,e,o,u,f,p,m;if(f=n,p=n,l=k(),l!==null){for(e=[],m=n,o=_e(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=_e(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l===null&&(l=Oe()),l!==null&&(l=function(v,y){typeof y=="string"?w.display_name=y:w.display_name=y[1].reduce(function(D,le){return D+le[0]+le[1]},y[0])}(f,l)),l===null&&(n=f),l}function Us(){var l;return l=Hn(),l===null&&(l=Jr(),l===null&&(l=Ke())),l}function Hn(){var l,e,o,u,f;return u=n,f=n,s.substr(n,1).toLowerCase()==="q"?(l=s.substr(n,1),n++):(l=null,d('"q"')),l!==null?(e=G(),e!==null?(o=ns(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.params||(w.params={}),w.params.q=m}(u,l[2])),l===null&&(n=u),l}function Jr(){var l,e,o,u,f;return u=n,f=n,s.substr(n,7).toLowerCase()==="expires"?(l=s.substr(n,7),n+=7):(l=null,d('"expires"')),l!==null?(e=G(),e!==null?(o=ss(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.params||(w.params={}),w.params.expires=m}(u,l[2])),l===null&&(n=u),l}function ss(){var l,e,o;if(o=n,e=g(),e!==null)for(l=[];e!==null;)l.push(e),e=g();else l=null;return l!==null&&(l=function(u,f){return parseInt(f.join(""))}(o,l)),l===null&&(n=o),l}function ns(){var l,e,o,u,f,p,m,v;return p=n,m=n,s.charCodeAt(n)===48?(l="0",n++):(l=null,d('"0"')),l!==null?(v=n,s.charCodeAt(n)===46?(e=".",n++):(e=null,d('"."')),e!==null?(o=g(),o=o!==null?o:"",o!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?e=[e,o,u,f]:(e=null,n=v)):(e=null,n=v)):(e=null,n=v)):(e=null,n=v),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=m)):(l=null,n=m),l!==null&&(l=function(y){return parseFloat(s.substring(n,y))}(p)),l===null&&(n=p),l}function Ke(){var l,e,o,u,f,p;return u=n,f=n,l=k(),l!==null?(p=n,e=G(),e!==null?(o=Ye(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(m,v,y){w.params||(w.params={}),typeof y>"u"?y=void 0:y=y[1],w.params[v.toLowerCase()]=y}(u,l[0],l[1])),l===null&&(n=u),l}function Ye(){var l;return l=k(),l===null&&(l=ts(),l===null&&(l=be())),l}function vl(){var l,e,o,u,f,p;if(f=n,l=Sl(),l!==null){for(e=[],p=n,o=oe(),o!==null?(u=Fn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=oe(),o!==null?(u=Fn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function Sl(){var l;return s.substr(n,6).toLowerCase()==="render"?(l=s.substr(n,6),n+=6):(l=null,d('"render"')),l===null&&(s.substr(n,7).toLowerCase()==="session"?(l=s.substr(n,7),n+=7):(l=null,d('"session"')),l===null&&(s.substr(n,4).toLowerCase()==="icon"?(l=s.substr(n,4),n+=4):(l=null,d('"icon"')),l===null&&(s.substr(n,5).toLowerCase()==="alert"?(l=s.substr(n,5),n+=5):(l=null,d('"alert"')),l===null&&(l=k())))),l}function Fn(){var l;return l=Vn(),l===null&&(l=Ke()),l}function Vn(){var l,e,o,u;return u=n,s.substr(n,8).toLowerCase()==="handling"?(l=s.substr(n,8),n+=8):(l=null,d('"handling"')),l!==null?(e=G(),e!==null?(s.substr(n,8).toLowerCase()==="optional"?(o=s.substr(n,8),n+=8):(o=null,d('"optional"')),o===null&&(s.substr(n,8).toLowerCase()==="required"?(o=s.substr(n,8),n+=8):(o=null,d('"required"')),o===null&&(o=k())),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function El(){var l,e,o,u,f,p;if(f=n,l=k(),l!==null){for(e=[],p=n,o=Ae(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=Ae(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function Zo(){var l,e,o;if(o=n,e=g(),e!==null)for(l=[];e!==null;)l.push(e),e=g();else l=null;return l!==null&&(l=function(u,f){w=parseInt(f.join(""))}(o,l)),l===null&&(n=o),l}function ea(){var l,e;return e=n,l=yl(),l!==null&&(l=function(o){w=s.substring(n,o)}(e)),l===null&&(n=e),l}function yl(){var l,e,o,u,f,p,m,v;if(m=n,l=zr(),l!==null)if(e=W(),e!==null)if(o=Zr(),o!==null){for(u=[],v=n,f=oe(),f!==null?(p=jn(),p!==null?f=[f,p]:(f=null,n=v)):(f=null,n=v);f!==null;)u.push(f),v=n,f=oe(),f!==null?(p=jn(),p!==null?f=[f,p]:(f=null,n=v)):(f=null,n=v);u!==null?l=[l,e,o,u]:(l=null,n=m)}else l=null,n=m;else l=null,n=m;else l=null,n=m;return l}function zr(){var l;return l=Qr(),l===null&&(l=Xr()),l}function Qr(){var l;return s.substr(n,4).toLowerCase()==="text"?(l=s.substr(n,4),n+=4):(l=null,d('"text"')),l===null&&(s.substr(n,5).toLowerCase()==="image"?(l=s.substr(n,5),n+=5):(l=null,d('"image"')),l===null&&(s.substr(n,5).toLowerCase()==="audio"?(l=s.substr(n,5),n+=5):(l=null,d('"audio"')),l===null&&(s.substr(n,5).toLowerCase()==="video"?(l=s.substr(n,5),n+=5):(l=null,d('"video"')),l===null&&(s.substr(n,11).toLowerCase()==="application"?(l=s.substr(n,11),n+=11):(l=null,d('"application"')),l===null&&(l=on()))))),l}function Xr(){var l;return s.substr(n,7).toLowerCase()==="message"?(l=s.substr(n,7),n+=7):(l=null,d('"message"')),l===null&&(s.substr(n,9).toLowerCase()==="multipart"?(l=s.substr(n,9),n+=9):(l=null,d('"multipart"')),l===null&&(l=on())),l}function on(){var l;return l=k(),l===null&&(l=an()),l}function an(){var l,e,o;return o=n,s.substr(n,2).toLowerCase()==="x-"?(l=s.substr(n,2),n+=2):(l=null,d('"x-"')),l!==null?(e=k(),e!==null?l=[l,e]:(l=null,n=o)):(l=null,n=o),l}function Zr(){var l;return l=on(),l===null&&(l=k()),l}function jn(){var l,e,o,u;return u=n,l=k(),l!==null?(e=G(),e!==null?(o=qn(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function qn(){var l;return l=k(),l===null&&(l=be()),l}function Cl(){var l,e,o,u;return u=n,l=Al(),l!==null?(e=_e(),e!==null?(o=rn(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function Al(){var l,e,o;if(o=n,e=g(),e!==null)for(l=[];e!==null;)l.push(e),e=g();else l=null;return l!==null&&(l=function(u,f){w.value=parseInt(f.join(""))}(o,l)),l===null&&(n=o),l}function Rl(){var l,e;return e=n,l=ss(),l!==null&&(l=function(o,u){w=u}(e,l)),l===null&&(n=e),l}function ta(){var l,e,o,u,f,p,m;if(f=n,p=n,l=un(),l!==null){for(e=[],m=n,o=oe(),o!==null?(u=Ke(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=oe(),o!==null?(u=Ke(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v,y){w.event=y.join("").toLowerCase()}(f,l[0])),l===null&&(n=f),l}function un(){var l,e,o,u,f,p;if(f=n,l=M(),l!==null){for(e=[],p=n,s.charCodeAt(n)===46?(o=".",n++):(o=null,d('"."')),o!==null?(u=M(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,s.charCodeAt(n)===46?(o=".",n++):(o=null,d('"."')),o!==null?(u=M(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function cn(){var l,e,o,u,f,p,m;if(f=n,p=n,l=me(),l===null&&(l=Ht()),l!==null){for(e=[],m=n,o=oe(),o!==null?(u=ei(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=oe(),o!==null?(u=ei(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v){var y=w.tag;try{w=new ds(w.uri,w.display_name,w.params),y&&w.setParam("tag",y)}catch{w=-1}}()),l===null&&(n=f),l}function ei(){var l;return l=fn(),l===null&&(l=Ke()),l}function fn(){var l,e,o,u,f;return u=n,f=n,s.substr(n,3).toLowerCase()==="tag"?(l=s.substr(n,3),n+=3):(l=null,d('"tag"')),l!==null?(e=G(),e!==null?(o=k(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.tag=m}(u,l[2])),l===null&&(n=u),l}function ti(){var l,e,o;if(o=n,e=g(),e!==null)for(l=[];e!==null;)l.push(e),e=g();else l=null;return l!==null&&(l=function(u,f){w=parseInt(f.join(""))}(o,l)),l===null&&(n=o),l}function sa(){var l,e;return e=n,l=ss(),l!==null&&(l=function(o,u){w=u}(e,l)),l===null&&(n=e),l}function na(){var l,e,o,u,f,p,m,v,y,D;for(v=n,y=n,l=[],e=Ft();e!==null;)l.push(e),e=Ft();if(l!==null)if(e=ke(),e!==null)if(o=we(),o!==null)if(u=Ie(),u!==null){for(f=[],D=n,p=oe(),p!==null?(m=Ke(),m!==null?p=[p,m]:(p=null,n=D)):(p=null,n=D);p!==null;)f.push(p),D=n,p=oe(),p!==null?(m=Ke(),m!==null?p=[p,m]:(p=null,n=D)):(p=null,n=D);f!==null?l=[l,e,o,u,f]:(l=null,n=y)}else l=null,n=y;else l=null,n=y;else l=null,n=y;else l=null,n=y;return l!==null&&(l=function(le){try{w=new ds(w.uri,w.display_name,w.params)}catch{w=-1}}()),l===null&&(n=v),l}function ra(){var l;return l=si(),l}function si(){var l,e,o,u,f,p,m,v;if(m=n,s.substr(n,6).toLowerCase()==="digest"?(l=s.substr(n,6),n+=6):(l=null,d('"Digest"')),l!==null)if(e=_e(),e!==null)if(o=rs(),o!==null){for(u=[],v=n,f=Ae(),f!==null?(p=rs(),p!==null?f=[f,p]:(f=null,n=v)):(f=null,n=v);f!==null;)u.push(f),v=n,f=Ae(),f!==null?(p=rs(),p!==null?f=[f,p]:(f=null,n=v)):(f=null,n=v);u!==null?l=[l,e,o,u]:(l=null,n=m)}else l=null,n=m;else l=null,n=m;else l=null,n=m;return l===null&&(l=Bn()),l}function Bn(){var l,e,o,u,f,p,m,v;if(m=n,l=k(),l!==null)if(e=_e(),e!==null)if(o=ks(),o!==null){for(u=[],v=n,f=Ae(),f!==null?(p=ks(),p!==null?f=[f,p]:(f=null,n=v)):(f=null,n=v);f!==null;)u.push(f),v=n,f=Ae(),f!==null?(p=ks(),p!==null?f=[f,p]:(f=null,n=v)):(f=null,n=v);u!==null?l=[l,e,o,u]:(l=null,n=m)}else l=null,n=m;else l=null,n=m;else l=null,n=m;return l}function ks(){var l,e,o,u;return u=n,l=k(),l!==null?(e=G(),e!==null?(o=k(),o===null&&(o=be()),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function rs(){var l;return l=dn(),l===null&&(l=ri(),l===null&&(l=_n(),l===null&&(l=li(),l===null&&(l=oi(),l===null&&(l=ai(),l===null&&(l=ui(),l===null&&(l=ks()))))))),l}function dn(){var l,e,o,u;return u=n,s.substr(n,5).toLowerCase()==="realm"?(l=s.substr(n,5),n+=5):(l=null,d('"realm"')),l!==null?(e=G(),e!==null?(o=ni(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function ni(){var l,e;return e=n,l=Oe(),l!==null&&(l=function(o,u){w.realm=u}(e,l)),l===null&&(n=e),l}function ri(){var l,e,o,u,f,p,m,v,y;if(v=n,s.substr(n,6).toLowerCase()==="domain"?(l=s.substr(n,6),n+=6):(l=null,d('"domain"')),l!==null)if(e=G(),e!==null)if(o=rt(),o!==null)if(u=hn(),u!==null){if(f=[],y=n,m=R(),m!==null)for(p=[];m!==null;)p.push(m),m=R();else p=null;for(p!==null?(m=hn(),m!==null?p=[p,m]:(p=null,n=y)):(p=null,n=y);p!==null;){if(f.push(p),y=n,m=R(),m!==null)for(p=[];m!==null;)p.push(m),m=R();else p=null;p!==null?(m=hn(),m!==null?p=[p,m]:(p=null,n=y)):(p=null,n=y)}f!==null?(p=at(),p!==null?l=[l,e,o,u,f,p]:(l=null,n=v)):(l=null,n=v)}else l=null,n=v;else l=null,n=v;else l=null,n=v;else l=null,n=v;return l}function hn(){var l;return l=kn(),l===null&&(l=tn()),l}function _n(){var l,e,o,u;return u=n,s.substr(n,5).toLowerCase()==="nonce"?(l=s.substr(n,5),n+=5):(l=null,d('"nonce"')),l!==null?(e=G(),e!==null?(o=ii(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function ii(){var l,e;return e=n,l=Oe(),l!==null&&(l=function(o,u){w.nonce=u}(e,l)),l===null&&(n=e),l}function li(){var l,e,o,u,f;return u=n,f=n,s.substr(n,6).toLowerCase()==="opaque"?(l=s.substr(n,6),n+=6):(l=null,d('"opaque"')),l!==null?(e=G(),e!==null?(o=Oe(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.opaque=m}(u,l[2])),l===null&&(n=u),l}function oi(){var l,e,o,u,f;return u=n,s.substr(n,5).toLowerCase()==="stale"?(l=s.substr(n,5),n+=5):(l=null,d('"stale"')),l!==null?(e=G(),e!==null?(f=n,s.substr(n,4).toLowerCase()==="true"?(o=s.substr(n,4),n+=4):(o=null,d('"true"')),o!==null&&(o=function(p){w.stale=!0}()),o===null&&(n=f),o===null&&(f=n,s.substr(n,5).toLowerCase()==="false"?(o=s.substr(n,5),n+=5):(o=null,d('"false"')),o!==null&&(o=function(p){w.stale=!1}()),o===null&&(n=f)),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function ai(){var l,e,o,u,f;return u=n,f=n,s.substr(n,9).toLowerCase()==="algorithm"?(l=s.substr(n,9),n+=9):(l=null,d('"algorithm"')),l!==null?(e=G(),e!==null?(s.substr(n,3).toLowerCase()==="md5"?(o=s.substr(n,3),n+=3):(o=null,d('"MD5"')),o===null&&(s.substr(n,8).toLowerCase()==="md5-sess"?(o=s.substr(n,8),n+=8):(o=null,d('"MD5-sess"')),o===null&&(o=k())),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.algorithm=m.toUpperCase()}(u,l[2])),l===null&&(n=u),l}function ui(){var l,e,o,u,f,p,m,v,y,D;if(v=n,s.substr(n,3).toLowerCase()==="qop"?(l=s.substr(n,3),n+=3):(l=null,d('"qop"')),l!==null)if(e=G(),e!==null)if(o=rt(),o!==null){if(y=n,u=pn(),u!==null){for(f=[],D=n,s.charCodeAt(n)===44?(p=",",n++):(p=null,d('","')),p!==null?(m=pn(),m!==null?p=[p,m]:(p=null,n=D)):(p=null,n=D);p!==null;)f.push(p),D=n,s.charCodeAt(n)===44?(p=",",n++):(p=null,d('","')),p!==null?(m=pn(),m!==null?p=[p,m]:(p=null,n=D)):(p=null,n=D);f!==null?u=[u,f]:(u=null,n=y)}else u=null,n=y;u!==null?(f=at(),f!==null?l=[l,e,o,u,f]:(l=null,n=v)):(l=null,n=v)}else l=null,n=v;else l=null,n=v;else l=null,n=v;return l}function pn(){var l,e;return e=n,s.substr(n,8).toLowerCase()==="auth-int"?(l=s.substr(n,8),n+=8):(l=null,d('"auth-int"')),l===null&&(s.substr(n,4).toLowerCase()==="auth"?(l=s.substr(n,4),n+=4):(l=null,d('"auth"')),l===null&&(l=k())),l!==null&&(l=function(o,u){w.qop||(w.qop=[]),w.qop.push(u.toLowerCase())}(e,l)),l===null&&(n=e),l}function Gn(){var l,e,o,u,f,p;if(f=n,l=k(),l!==null){for(e=[],p=n,o=Ae(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=Ae(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function ia(){var l,e,o,u,f,p,m;if(f=n,p=n,l=Wn(),l!==null){for(e=[],m=n,o=Ae(),o!==null?(u=Wn(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=Ae(),o!==null?(u=Wn(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v){var y,D;for(D=w.multi_header.length,y=0;y<D;y++)if(w.multi_header[y].parsed===null){w=null;break}w!==null?w=w.multi_header:w=-1}()),l===null&&(n=f),l}function Wn(){var l,e,o,u,f,p,m;if(f=n,p=n,l=Ht(),l!==null){for(e=[],m=n,o=oe(),o!==null?(u=Ke(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=oe(),o!==null?(u=Ke(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v){var y;w.multi_header||(w.multi_header=[]);try{y=new ds(w.uri,w.display_name,w.params),delete w.uri,delete w.display_name,delete w.params}catch{y=null}w.multi_header.push({possition:n,offset:v,parsed:y})}(f)),l===null&&(n=f),l}function Kn(){var l,e,o,u,f,p,m;if(f=n,p=n,s.substr(n,3).toLowerCase()==="sip"?(l=s.substr(n,3),n+=3):(l=null,d('"SIP"')),l===null&&(l=k()),l!==null){for(e=[],m=n,o=oe(),o!==null?(u=ci(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=oe(),o!==null?(u=ci(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v,y){if(w.protocol=y.toLowerCase(),w.params||(w.params={}),w.params.text&&w.params.text[0]==='"'){var D=w.params.text;w.text=D.substring(1,D.length-1),delete w.params.text}}(f,l[0])),l===null&&(n=f),l}function ci(){var l;return l=Yn(),l===null&&(l=Ke()),l}function Yn(){var l,e,o,u,f,p;if(f=n,p=n,s.substr(n,5).toLowerCase()==="cause"?(l=s.substr(n,5),n+=5):(l=null,d('"cause"')),l!==null)if(e=G(),e!==null){if(u=g(),u!==null)for(o=[];u!==null;)o.push(u),u=g();else o=null;o!==null?l=[l,e,o]:(l=null,n=p)}else l=null,n=p;else l=null,n=p;return l!==null&&(l=function(m,v){w.cause=parseInt(v.join(""))}(f,l[2])),l===null&&(n=f),l}function Il(){var l,e,o,u,f,p;if(f=n,l=k(),l!==null){for(e=[],p=n,o=Ae(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=Ae(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function la(){var l,e,o,u,f,p;if(f=n,l=Jn(),l!==null){for(e=[],p=n,o=Ae(),o!==null?(u=Jn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=Ae(),o!==null?(u=Jn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function Jn(){var l,e,o,u,f,p;if(f=n,l=Ht(),l!==null){for(e=[],p=n,o=oe(),o!==null?(u=Ke(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=oe(),o!==null?(u=Ke(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function zn(){var l,e,o,u,f,p;if(f=n,l=bl(),l!==null){for(e=[],p=n,o=oe(),o!==null?(u=Qn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=oe(),o!==null?(u=Qn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function bl(){var l,e;return e=n,s.substr(n,6).toLowerCase()==="active"?(l=s.substr(n,6),n+=6):(l=null,d('"active"')),l===null&&(s.substr(n,7).toLowerCase()==="pending"?(l=s.substr(n,7),n+=7):(l=null,d('"pending"')),l===null&&(s.substr(n,10).toLowerCase()==="terminated"?(l=s.substr(n,10),n+=10):(l=null,d('"terminated"')),l===null&&(l=k()))),l!==null&&(l=function(o){w.state=s.substring(n,o)}(e)),l===null&&(n=e),l}function Qn(){var l,e,o,u,f;return u=n,f=n,s.substr(n,6).toLowerCase()==="reason"?(l=s.substr(n,6),n+=6):(l=null,d('"reason"')),l!==null?(e=G(),e!==null?(o=Xn(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){typeof m<"u"&&(w.reason=m)}(u,l[2])),l===null&&(n=u),l===null&&(u=n,f=n,s.substr(n,7).toLowerCase()==="expires"?(l=s.substr(n,7),n+=7):(l=null,d('"expires"')),l!==null?(e=G(),e!==null?(o=ss(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){typeof m<"u"&&(w.expires=m)}(u,l[2])),l===null&&(n=u),l===null&&(u=n,f=n,s.substr(n,11).toLowerCase()==="retry_after"?(l=s.substr(n,11),n+=11):(l=null,d('"retry_after"')),l!==null?(e=G(),e!==null?(o=ss(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){typeof m<"u"&&(w.retry_after=m)}(u,l[2])),l===null&&(n=u),l===null&&(l=Ke()))),l}function Xn(){var l;return s.substr(n,11).toLowerCase()==="deactivated"?(l=s.substr(n,11),n+=11):(l=null,d('"deactivated"')),l===null&&(s.substr(n,9).toLowerCase()==="probation"?(l=s.substr(n,9),n+=9):(l=null,d('"probation"')),l===null&&(s.substr(n,8).toLowerCase()==="rejected"?(l=s.substr(n,8),n+=8):(l=null,d('"rejected"')),l===null&&(s.substr(n,7).toLowerCase()==="timeout"?(l=s.substr(n,7),n+=7):(l=null,d('"timeout"')),l===null&&(s.substr(n,6).toLowerCase()==="giveup"?(l=s.substr(n,6),n+=6):(l=null,d('"giveup"')),l===null&&(s.substr(n,10).toLowerCase()==="noresource"?(l=s.substr(n,10),n+=10):(l=null,d('"noresource"')),l===null&&(s.substr(n,9).toLowerCase()==="invariant"?(l=s.substr(n,9),n+=9):(l=null,d('"invariant"')),l===null&&(l=k()))))))),l}function wl(){var l;return l=q(),l=l!==null?l:"",l}function oa(){var l,e,o,u,f,p;if(f=n,l=k(),l!==null){for(e=[],p=n,o=Ae(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=Ae(),o!==null?(u=k(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l=l!==null?l:"",l}function aa(){var l,e,o,u,f,p,m;if(f=n,p=n,l=me(),l===null&&(l=Ht()),l!==null){for(e=[],m=n,o=oe(),o!==null?(u=fi(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=oe(),o!==null?(u=fi(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v){var y=w.tag;try{w=new ds(w.uri,w.display_name,w.params),y&&w.setParam("tag",y)}catch{w=-1}}()),l===null&&(n=f),l}function fi(){var l;return l=fn(),l===null&&(l=Ke()),l}function di(){var l,e,o,u,f,p;if(f=n,l=Zn(),l!==null){for(e=[],p=n,o=Ae(),o!==null?(u=Zn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=Ae(),o!==null?(u=Zn(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function Zn(){var l,e,o,u,f,p,m,v;if(m=n,l=Ti(),l!==null)if(e=_e(),e!==null)if(o=Ei(),o!==null){for(u=[],v=n,f=oe(),f!==null?(p=Ms(),p!==null?f=[f,p]:(f=null,n=v)):(f=null,n=v);f!==null;)u.push(f),v=n,f=oe(),f!==null?(p=Ms(),p!==null?f=[f,p]:(f=null,n=v)):(f=null,n=v);u!==null?l=[l,e,o,u]:(l=null,n=m)}else l=null,n=m;else l=null,n=m;else l=null,n=m;return l}function Ms(){var l;return l=er(),l===null&&(l=hi(),l===null&&(l=_i(),l===null&&(l=pi(),l===null&&(l=mi(),l===null&&(l=Ke()))))),l}function er(){var l,e,o,u,f;return u=n,f=n,s.substr(n,3).toLowerCase()==="ttl"?(l=s.substr(n,3),n+=3):(l=null,d('"ttl"')),l!==null?(e=G(),e!==null?(o=tr(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.ttl=m}(u,l[2])),l===null&&(n=u),l}function hi(){var l,e,o,u,f;return u=n,f=n,s.substr(n,5).toLowerCase()==="maddr"?(l=s.substr(n,5),n+=5):(l=null,d('"maddr"')),l!==null?(e=G(),e!==null?(o=ts(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.maddr=m}(u,l[2])),l===null&&(n=u),l}function _i(){var l,e,o,u,f;return u=n,f=n,s.substr(n,8).toLowerCase()==="received"?(l=s.substr(n,8),n+=8):(l=null,d('"received"')),l!==null?(e=G(),e!==null?(o=ut(),o===null&&(o=Qs()),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.received=m}(u,l[2])),l===null&&(n=u),l}function pi(){var l,e,o,u,f;return u=n,f=n,s.substr(n,6).toLowerCase()==="branch"?(l=s.substr(n,6),n+=6):(l=null,d('"branch"')),l!==null?(e=G(),e!==null?(o=k(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.branch=m}(u,l[2])),l===null&&(n=u),l}function mi(){var l,e,o,u,f;return u=n,s.substr(n,5).toLowerCase()==="rport"?(l=s.substr(n,5),n+=5):(l=null,d('"rport"')),l!==null?(f=n,e=G(),e!==null?(o=gi(),o!==null?e=[e,o]:(e=null,n=f)):(e=null,n=f),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l}function gi(){var l,e,o,u,f,p,m;return p=n,m=n,l=g(),l=l!==null?l:"",l!==null?(e=g(),e=e!==null?e:"",e!==null?(o=g(),o=o!==null?o:"",o!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?l=[l,e,o,u,f]:(l=null,n=m)):(l=null,n=m)):(l=null,n=m)):(l=null,n=m)):(l=null,n=m),l!==null&&(l=function(v,y){w.rport=parseInt(y.join(""))}(p,l)),l===null&&(n=p),l}function Ti(){var l,e,o,u,f,p;return p=n,l=vi(),l!==null?(e=W(),e!==null?(o=k(),o!==null?(u=W(),u!==null?(f=Si(),f!==null?l=[l,e,o,u,f]:(l=null,n=p)):(l=null,n=p)):(l=null,n=p)):(l=null,n=p)):(l=null,n=p),l}function vi(){var l,e;return e=n,s.substr(n,3).toLowerCase()==="sip"?(l=s.substr(n,3),n+=3):(l=null,d('"SIP"')),l===null&&(l=k()),l!==null&&(l=function(o,u){w.protocol=u}(e,l)),l===null&&(n=e),l}function Si(){var l,e;return e=n,s.substr(n,3).toLowerCase()==="udp"?(l=s.substr(n,3),n+=3):(l=null,d('"UDP"')),l===null&&(s.substr(n,3).toLowerCase()==="tcp"?(l=s.substr(n,3),n+=3):(l=null,d('"TCP"')),l===null&&(s.substr(n,3).toLowerCase()==="tls"?(l=s.substr(n,3),n+=3):(l=null,d('"TLS"')),l===null&&(s.substr(n,4).toLowerCase()==="sctp"?(l=s.substr(n,4),n+=4):(l=null,d('"SCTP"')),l===null&&(l=k())))),l!==null&&(l=function(o,u){w.transport=u}(e,l)),l===null&&(n=e),l}function Ei(){var l,e,o,u,f;return u=n,l=yi(),l!==null?(f=n,e=ye(),e!==null?(o=Ci(),o!==null?e=[e,o]:(e=null,n=f)):(e=null,n=f),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=u)):(l=null,n=u),l}function yi(){var l,e;return e=n,l=ut(),l===null&&(l=Nn(),l===null&&(l=cs())),l!==null&&(l=function(o){w.host=s.substring(n,o)}(e)),l===null&&(n=e),l}function Ci(){var l,e,o,u,f,p,m;return p=n,m=n,l=g(),l=l!==null?l:"",l!==null?(e=g(),e=e!==null?e:"",e!==null?(o=g(),o=o!==null?o:"",o!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?l=[l,e,o,u,f]:(l=null,n=m)):(l=null,n=m)):(l=null,n=m)):(l=null,n=m)):(l=null,n=m),l!==null&&(l=function(v,y){w.port=parseInt(y.join(""))}(p,l)),l===null&&(n=p),l}function tr(){var l,e,o,u,f;return u=n,f=n,l=g(),l!==null?(e=g(),e=e!==null?e:"",e!==null?(o=g(),o=o!==null?o:"",o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){return parseInt(m.join(""))}(u,l)),l===null&&(n=u),l}function Ai(){var l;return l=si(),l}function ua(){var l,e,o,u,f,p;if(f=n,l=Ol(),l!==null){for(e=[],p=n,o=oe(),o!==null?(u=sr(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=oe(),o!==null?(u=sr(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function Ol(){var l,e;return e=n,l=ss(),l!==null&&(l=function(o,u){w.expires=u}(e,l)),l===null&&(n=e),l}function sr(){var l;return l=nr(),l===null&&(l=Ke()),l}function nr(){var l,e,o,u,f;return u=n,f=n,s.substr(n,9).toLowerCase()==="refresher"?(l=s.substr(n,9),n+=9):(l=null,d('"refresher"')),l!==null?(e=G(),e!==null?(s.substr(n,3).toLowerCase()==="uac"?(o=s.substr(n,3),n+=3):(o=null,d('"uac"')),o===null&&(s.substr(n,3).toLowerCase()==="uas"?(o=s.substr(n,3),n+=3):(o=null,d('"uas"'))),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.refresher=m.toLowerCase()}(u,l[2])),l===null&&(n=u),l}function Dl(){var l,e,o,u;return u=n,l=k(),l!==null?(e=x(),e!==null?(o=Nl(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function Nl(){var l,e;for(l=[],e=j(),e===null&&(e=V(),e===null&&(e=_e()));e!==null;)l.push(e),e=j(),e===null&&(e=V(),e===null&&(e=_e()));return l}function xl(){var l,e;for(l=[],e=C();e!==null;)l.push(e),e=C();return l}function ca(){var l,e,o;return o=n,s.substr(n,5)==="uuid:"?(l="uuid:",n+=5):(l=null,d('"uuid:"')),l!==null?(e=Ul(),e!==null?l=[l,e]:(l=null,n=o)):(l=null,n=o),l}function Ul(){var l,e,o,u,f,p,m,v,y,D,le;return D=n,le=n,l=jt(),l!==null?(s.charCodeAt(n)===45?(e="-",n++):(e=null,d('"-"')),e!==null?(o=Vt(),o!==null?(s.charCodeAt(n)===45?(u="-",n++):(u=null,d('"-"')),u!==null?(f=Vt(),f!==null?(s.charCodeAt(n)===45?(p="-",n++):(p=null,d('"-"')),p!==null?(m=Vt(),m!==null?(s.charCodeAt(n)===45?(v="-",n++):(v=null,d('"-"')),v!==null?(y=Ri(),y!==null?l=[l,e,o,u,f,p,m,v,y]:(l=null,n=le)):(l=null,n=le)):(l=null,n=le)):(l=null,n=le)):(l=null,n=le)):(l=null,n=le)):(l=null,n=le)):(l=null,n=le)):(l=null,n=le),l!==null&&(l=function(xe,Ot){w=s.substring(n+5,xe)}(D,l[0])),l===null&&(n=D),l}function Vt(){var l,e,o,u,f;return f=n,l=S(),l!==null?(e=S(),e!==null?(o=S(),o!==null?(u=S(),u!==null?l=[l,e,o,u]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l}function jt(){var l,e,o;return o=n,l=Vt(),l!==null?(e=Vt(),e!==null?l=[l,e]:(l=null,n=o)):(l=null,n=o),l}function Ri(){var l,e,o,u;return u=n,l=Vt(),l!==null?(e=Vt(),e!==null?(o=Vt(),o!==null?l=[l,e,o]:(l=null,n=u)):(l=null,n=u)):(l=null,n=u),l}function kl(){var l,e,o,u,f,p,m;if(f=n,p=n,l=me(),l===null&&(l=Ht()),l!==null){for(e=[],m=n,o=oe(),o!==null?(u=Ke(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);o!==null;)e.push(o),m=n,o=oe(),o!==null?(u=Ke(),u!==null?o=[o,u]:(o=null,n=m)):(o=null,n=m);e!==null?l=[l,e]:(l=null,n=p)}else l=null,n=p;return l!==null&&(l=function(v){try{w=new ds(w.uri,w.display_name,w.params)}catch{w=-1}}()),l===null&&(n=f),l}function fa(){var l,e,o,u,f,p;if(f=n,l=Ml(),l!==null){for(e=[],p=n,o=oe(),o!==null?(u=rr(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,o=oe(),o!==null?(u=rr(),u!==null?o=[o,u]:(o=null,n=p)):(o=null,n=p);e!==null?l=[l,e]:(l=null,n=f)}else l=null,n=f;return l}function Ml(){var l,e,o,u,f,p;return u=n,f=n,l=Fe(),l!==null?(p=n,s.charCodeAt(n)===64?(e="@",n++):(e=null,d('"@"')),e!==null?(o=Fe(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e=e!==null?e:"",e!==null?l=[l,e]:(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(m){w.call_id=s.substring(n,m)}(u)),l===null&&(n=u),l}function rr(){var l;return l=ir(),l===null&&(l=Ii(),l===null&&(l=bi(),l===null&&(l=Ke()))),l}function ir(){var l,e,o,u,f;return u=n,f=n,s.substr(n,6)==="to-tag"?(l="to-tag",n+=6):(l=null,d('"to-tag"')),l!==null?(e=G(),e!==null?(o=k(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.to_tag=m}(u,l[2])),l===null&&(n=u),l}function Ii(){var l,e,o,u,f;return u=n,f=n,s.substr(n,8)==="from-tag"?(l="from-tag",n+=8):(l=null,d('"from-tag"')),l!==null?(e=G(),e!==null?(o=k(),o!==null?l=[l,e,o]:(l=null,n=f)):(l=null,n=f)):(l=null,n=f),l!==null&&(l=function(p,m){w.from_tag=m}(u,l[2])),l===null&&(n=u),l}function bi(){var l,e;return e=n,s.substr(n,10)==="early-only"?(l="early-only",n+=10):(l=null,d('"early-only"')),l!==null&&(l=function(o){w.early_only=!0}()),l===null&&(n=e),l}function Pl(l){l.sort();for(var e=null,o=[],u=0;u<l.length;u++)l[u]!==e&&(o.push(l[u]),e=l[u]);return o}function da(){for(var l=1,e=1,o=!1,u=0;u<Math.max(n,r);u++){var f=s.charAt(u);f===`
|
|
75
|
+
`?(o||l++,e=1,o=!1):f==="\r"||f==="\u2028"||f==="\u2029"?(l++,e=1,o=!0):(e++,o=!1)}return{line:l,column:e}}var Ll=Cs(),ds=ju(),w={},O=a[i]();if(O===null||n!==s.length){var wi=Math.max(n,r),Oi=wi<s.length?s.charAt(wi):null,$l=da();return new this.SyntaxError(Pl(h),Oi,wi,$l.line,$l.column),-1}return w},toSource:function(){return this._source}};return t.SyntaxError=function(s,i,a,n,r){function h(d,_){var g,T;switch(d.length){case 0:g="end of input";break;case 1:g=d[0];break;default:g=d.slice(0,d.length-1).join(", ")+" or "+d[d.length-1]}return T=_?c(_):"end of input","Expected "+g+" but "+T+" found."}this.name="SyntaxError",this.expected=s,this.found=i,this.message=h(s,i),this.offset=a,this.line=n,this.column=r},t.SyntaxError.prototype=Error.prototype,t}()),La}var $a,of;function Cs(){if(of)return $a;of=1;const c=De,t=At(),s=es();return $a=class vd{static parse(a){if(a=s.parse(a,"SIP_URI"),a!==-1)return a}constructor(a,n,r,h,d={},_={}){if(!r)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=a||c.SIP,this._user=n,this._host=r,this._port=h;for(const g in d)Object.prototype.hasOwnProperty.call(d,g)&&this.setParam(g,d[g]);for(const g in _)Object.prototype.hasOwnProperty.call(_,g)&&this.setHeader(g,_[g])}get scheme(){return this._scheme}set scheme(a){this._scheme=a.toLowerCase()}get user(){return this._user}set user(a){this._user=a}get host(){return this._host}set host(a){this._host=a.toLowerCase()}get port(){return this._port}set port(a){this._port=a===0?a:parseInt(a,10)||null}setParam(a,n){a&&(this._parameters[a.toLowerCase()]=typeof n>"u"||n===null?null:n.toString())}getParam(a){if(a)return this._parameters[a.toLowerCase()]}hasParam(a){if(a)return this._parameters.hasOwnProperty(a.toLowerCase())&&!0||!1}deleteParam(a){if(a=a.toLowerCase(),this._parameters.hasOwnProperty(a)){const n=this._parameters[a];return delete this._parameters[a],n}}clearParams(){this._parameters={}}setHeader(a,n){this._headers[t.headerize(a)]=Array.isArray(n)?n:[n]}getHeader(a){if(a)return this._headers[t.headerize(a)]}hasHeader(a){if(a)return this._headers.hasOwnProperty(t.headerize(a))&&!0||!1}deleteHeader(a){if(a=t.headerize(a),this._headers.hasOwnProperty(a)){const n=this._headers[a];return delete this._headers[a],n}}clearHeaders(){this._headers={}}clone(){return new vd(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}toString(){const a=[];let n=`${this._scheme}:`;this._user&&(n+=`${t.escapeUser(this._user)}@`),n+=this._host,(this._port||this._port===0)&&(n+=`:${this._port}`);for(const r in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,r)&&(n+=`;${r}`,this._parameters[r]!==null&&(n+=`=${this._parameters[r]}`));for(const r in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,r))for(const h of this._headers[r])a.push(`${r}=${h}`);return a.length>0&&(n+=`?${a.join("&")}`),n}toAor(a){let n=`${this._scheme}:`;return this._user&&(n+=`${t.escapeUser(this._user)}@`),n+=this._host,a&&(this._port||this._port===0)&&(n+=`:${this._port}`),n}},$a}var af;function At(){if(af)return st;af=1;const c=De,t=Cs(),s=es();st.str_utf8_length=r=>unescape(encodeURIComponent(r)).length;const i=st.isFunction=r=>r!==void 0?Object.prototype.toString.call(r)==="[object Function]":!1;st.isString=r=>r!==void 0?Object.prototype.toString.call(r)==="[object String]":!1,st.isDecimal=r=>!isNaN(r)&&parseFloat(r)===parseInt(r,10),st.isEmpty=r=>r===null||r===""||r===void 0||Array.isArray(r)&&r.length===0||typeof r=="number"&&isNaN(r),st.hasMethods=function(r,...h){for(const d of h)if(i(r[d]))return!1;return!0};const a=st.createRandomToken=(r,h=32)=>{let d,_,g="";for(d=0;d<r;d++)_=Math.random()*h|0,g+=_.toString(h);return g};st.newTag=()=>a(10),st.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,h=>{const d=Math.random()*16|0;return(h==="x"?d:d&3|8).toString(16)}),st.hostType=r=>{if(r){if(r=s.parse(r,"host"),r!==-1)return r.host_type}else return};const n=st.escapeUser=r=>encodeURIComponent(decodeURIComponent(r)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/");return st.normalizeTarget=(r,h)=>{if(r){if(r instanceof t)return r;if(typeof r=="string"){const d=r.split("@");let _,g;switch(d.length){case 1:if(!h)return;_=r,g=h;break;case 2:_=d[0],g=d[1];break;default:_=d.slice(0,d.length-1).join("@"),g=d[d.length-1]}_=_.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(_)&&(_=_.replace(/[-.()]/g,"")),r=`${c.SIP}:${n(_)}@${g}`;let T;return(T=t.parse(r))?T:void 0}else return}else return},st.headerize=r=>{const h={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},d=r.toLowerCase().replace(/_/g,"-").split("-");let _="";const g=d.length;let T;for(T=0;T<g;T++)T!==0&&(_+="-"),_+=d[T].charAt(0).toUpperCase()+d[T].substring(1);return h[_]&&(_=h[_]),_},st.sipErrorCause=r=>{for(const h in c.SIP_ERROR_CAUSES)if(c.SIP_ERROR_CAUSES[h].indexOf(r)!==-1)return c.causes[h];return c.causes.SIP_FAILURE_CODE},st.getRandomTestNetIP=()=>{function r(h,d){return Math.floor(Math.random()*(d-h+1)+h)}return`192.0.2.${r(1,254)}`},st.calculateMD5=r=>{function h(Ee,Ce){return Ee<<Ce|Ee>>>32-Ce}function d(Ee,Ce){const be=Ee&2147483648,Oe=Ce&2147483648,ge=Ee&1073741824,ue=Ce&1073741824,me=(Ee&1073741823)+(Ce&1073741823);return ge&ue?me^2147483648^be^Oe:ge|ue?me&1073741824?me^3221225472^be^Oe:me^1073741824^be^Oe:me^be^Oe}function _(Ee,Ce,be){return Ee&Ce|~Ee&be}function g(Ee,Ce,be){return Ee&be|Ce&~be}function T(Ee,Ce,be){return Ee^Ce^be}function S(Ee,Ce,be){return Ce^(Ee|~be)}function E(Ee,Ce,be,Oe,ge,ue,me){return Ee=d(Ee,d(d(_(Ce,be,Oe),ge),me)),d(h(Ee,ue),Ce)}function C(Ee,Ce,be,Oe,ge,ue,me){return Ee=d(Ee,d(d(g(Ce,be,Oe),ge),me)),d(h(Ee,ue),Ce)}function A(Ee,Ce,be,Oe,ge,ue,me){return Ee=d(Ee,d(d(T(Ce,be,Oe),ge),me)),d(h(Ee,ue),Ce)}function R(Ee,Ce,be,Oe,ge,ue,me){return Ee=d(Ee,d(d(S(Ce,be,Oe),ge),me)),d(h(Ee,ue),Ce)}function F(Ee){let Ce;const be=Ee.length,Oe=be+8,ue=((Oe-Oe%64)/64+1)*16,me=new Array(ue-1);let we=0,Ne=0;for(;Ne<be;)Ce=(Ne-Ne%4)/4,we=Ne%4*8,me[Ce]=me[Ce]|Ee.charCodeAt(Ne)<<we,Ne++;return Ce=(Ne-Ne%4)/4,we=Ne%4*8,me[Ce]=me[Ce]|128<<we,me[ue-2]=be<<3,me[ue-1]=be>>>29,me}function I(Ee){let Ce="",be="",Oe,ge;for(ge=0;ge<=3;ge++)Oe=Ee>>>ge*8&255,be=`0${Oe.toString(16)}`,Ce=Ce+be.substr(be.length-2,2);return Ce}function ie(Ee){let Ce="";for(let be=0;be<Ee.length;be++){const Oe=Ee.charCodeAt(be);Oe<128?Ce+=String.fromCharCode(Oe):Oe>127&&Oe<2048?(Ce+=String.fromCharCode(Oe>>6|192),Ce+=String.fromCharCode(Oe&63|128)):(Ce+=String.fromCharCode(Oe>>12|224),Ce+=String.fromCharCode(Oe>>6&63|128),Ce+=String.fromCharCode(Oe&63|128))}return Ce}let N=[],$,ve,_e,U,x,q,j,Y,V;const Q=7,k=12,M=17,B=22,Fe=5,X=9,W=14,G=20,re=4,pe=11,Ie=16,ke=23,Ae=6,oe=10,ye=15,rt=21;for(r=ie(r),N=F(r),q=1732584193,j=4023233417,Y=2562383102,V=271733878,$=0;$<N.length;$+=16)ve=q,_e=j,U=Y,x=V,q=E(q,j,Y,V,N[$+0],Q,3614090360),V=E(V,q,j,Y,N[$+1],k,3905402710),Y=E(Y,V,q,j,N[$+2],M,606105819),j=E(j,Y,V,q,N[$+3],B,3250441966),q=E(q,j,Y,V,N[$+4],Q,4118548399),V=E(V,q,j,Y,N[$+5],k,1200080426),Y=E(Y,V,q,j,N[$+6],M,2821735955),j=E(j,Y,V,q,N[$+7],B,4249261313),q=E(q,j,Y,V,N[$+8],Q,1770035416),V=E(V,q,j,Y,N[$+9],k,2336552879),Y=E(Y,V,q,j,N[$+10],M,4294925233),j=E(j,Y,V,q,N[$+11],B,2304563134),q=E(q,j,Y,V,N[$+12],Q,1804603682),V=E(V,q,j,Y,N[$+13],k,4254626195),Y=E(Y,V,q,j,N[$+14],M,2792965006),j=E(j,Y,V,q,N[$+15],B,1236535329),q=C(q,j,Y,V,N[$+1],Fe,4129170786),V=C(V,q,j,Y,N[$+6],X,3225465664),Y=C(Y,V,q,j,N[$+11],W,643717713),j=C(j,Y,V,q,N[$+0],G,3921069994),q=C(q,j,Y,V,N[$+5],Fe,3593408605),V=C(V,q,j,Y,N[$+10],X,38016083),Y=C(Y,V,q,j,N[$+15],W,3634488961),j=C(j,Y,V,q,N[$+4],G,3889429448),q=C(q,j,Y,V,N[$+9],Fe,568446438),V=C(V,q,j,Y,N[$+14],X,3275163606),Y=C(Y,V,q,j,N[$+3],W,4107603335),j=C(j,Y,V,q,N[$+8],G,1163531501),q=C(q,j,Y,V,N[$+13],Fe,2850285829),V=C(V,q,j,Y,N[$+2],X,4243563512),Y=C(Y,V,q,j,N[$+7],W,1735328473),j=C(j,Y,V,q,N[$+12],G,2368359562),q=A(q,j,Y,V,N[$+5],re,4294588738),V=A(V,q,j,Y,N[$+8],pe,2272392833),Y=A(Y,V,q,j,N[$+11],Ie,1839030562),j=A(j,Y,V,q,N[$+14],ke,4259657740),q=A(q,j,Y,V,N[$+1],re,2763975236),V=A(V,q,j,Y,N[$+4],pe,1272893353),Y=A(Y,V,q,j,N[$+7],Ie,4139469664),j=A(j,Y,V,q,N[$+10],ke,3200236656),q=A(q,j,Y,V,N[$+13],re,681279174),V=A(V,q,j,Y,N[$+0],pe,3936430074),Y=A(Y,V,q,j,N[$+3],Ie,3572445317),j=A(j,Y,V,q,N[$+6],ke,76029189),q=A(q,j,Y,V,N[$+9],re,3654602809),V=A(V,q,j,Y,N[$+12],pe,3873151461),Y=A(Y,V,q,j,N[$+15],Ie,530742520),j=A(j,Y,V,q,N[$+2],ke,3299628645),q=R(q,j,Y,V,N[$+0],Ae,4096336452),V=R(V,q,j,Y,N[$+7],oe,1126891415),Y=R(Y,V,q,j,N[$+14],ye,2878612391),j=R(j,Y,V,q,N[$+5],rt,4237533241),q=R(q,j,Y,V,N[$+12],Ae,1700485571),V=R(V,q,j,Y,N[$+3],oe,2399980690),Y=R(Y,V,q,j,N[$+10],ye,4293915773),j=R(j,Y,V,q,N[$+1],rt,2240044497),q=R(q,j,Y,V,N[$+8],Ae,1873313359),V=R(V,q,j,Y,N[$+15],oe,4264355552),Y=R(Y,V,q,j,N[$+6],ye,2734768916),j=R(j,Y,V,q,N[$+13],rt,1309151649),q=R(q,j,Y,V,N[$+4],Ae,4149444226),V=R(V,q,j,Y,N[$+11],oe,3174756917),Y=R(Y,V,q,j,N[$+2],ye,718787259),j=R(j,Y,V,q,N[$+9],rt,3951481745),q=d(q,ve),j=d(j,_e),Y=d(Y,U),V=d(V,x);return(I(q)+I(j)+I(Y)+I(V)).toLowerCase()},st.closeMediaStream=r=>{if(r)try{let h;if(r.getTracks){h=r.getTracks();for(const d of h)d.stop()}else{h=r.getAudioTracks();for(const d of h)d.stop();h=r.getVideoTracks();for(const d of h)d.stop()}}catch{(typeof r.stop=="function"||typeof r.stop=="object")&&r.stop()}},st.cloneArray=r=>r&&r.slice()||[],st.cloneObject=(r,h={})=>r&&Object.assign({},r)||h,st}const Sd=Mt,Xm=ct,yt=De,lt=At(),uf=ju(),Zm=es(),Ha=new Xm("SIPMessage");class Jo{constructor(t,s,i,a,n,r){if(!t||!s||!i)return null;a=a||{},this.ua=i,this.headers={},this.method=t,this.ruri=s,this.body=r,this.extraHeaders=lt.cloneArray(n),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),a.route_set?this.setHeader("route",a.route_set):i.configuration.use_preloaded_route&&this.setHeader("route",`<${i.transport.sip_uri};lr>`),this.setHeader("via",""),this.setHeader("max-forwards",yt.MAX_FORWARDS);const h=a.to_uri||s,d=a.to_tag?{tag:a.to_tag}:null,_=typeof a.to_display_name<"u"?a.to_display_name:null;this.to=new uf(h,_,d),this.setHeader("to",this.to.toString());const g=a.from_uri||i.configuration.uri,T={tag:a.from_tag||lt.newTag()};let S;typeof a.from_display_name<"u"?S=a.from_display_name:i.configuration.display_name?S=i.configuration.display_name:S=null,this.from=new uf(g,S,T),this.setHeader("from",this.from.toString());const E=a.call_id||i.configuration.jssip_id+lt.createRandomToken(15);this.call_id=E,this.setHeader("call-id",E);const C=a.cseq||Math.floor(Math.random()*1e4);this.cseq=C,this.setHeader("cseq",`${C} ${t}`)}setHeader(t,s){const i=new RegExp(`^\\s*${t}\\s*:`,"i");for(let a=0;a<this.extraHeaders.length;a++)i.test(this.extraHeaders[a])&&this.extraHeaders.splice(a,1);this.headers[lt.headerize(t)]=Array.isArray(s)?s:[s]}getHeader(t){const s=this.headers[lt.headerize(t)];if(s){if(s[0])return s[0]}else{const i=new RegExp(`^\\s*${t}\\s*:`,"i");for(const a of this.extraHeaders)if(i.test(a))return a.substring(a.indexOf(":")+1).trim()}}getHeaders(t){const s=this.headers[lt.headerize(t)],i=[];if(s){for(const a of s)i.push(a);return i}else{const a=new RegExp(`^\\s*${t}\\s*:`,"i");for(const n of this.extraHeaders)a.test(n)&&i.push(n.substring(n.indexOf(":")+1).trim());return i}}hasHeader(t){if(this.headers[lt.headerize(t)])return!0;{const s=new RegExp(`^\\s*${t}\\s*:`,"i");for(const i of this.extraHeaders)if(s.test(i))return!0}return!1}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=Sd.parse(this.body||""),this.sdp)}toString(){let t=`${this.method} ${this.ruri} SIP/2.0\r
|
|
76
|
+
`;for(const a in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,a))for(const n of this.headers[a])t+=`${a}: ${n}\r
|
|
77
77
|
`;for(const a of this.extraHeaders)t+=`${a.trim()}\r
|
|
78
|
-
`;const
|
|
79
|
-
`,t+=`Supported: ${
|
|
80
|
-
`,t+=`User-Agent: ${
|
|
81
|
-
`,this.body){const a=
|
|
78
|
+
`;const s=[];switch(this.method){case yt.REGISTER:s.push("path","gruu");break;case yt.INVITE:this.ua.configuration.session_timers&&s.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&s.push("gruu"),s.push("ice","replaces");break;case yt.UPDATE:this.ua.configuration.session_timers&&s.push("timer"),s.push("ice");break}s.push("outbound");const i=this.ua.configuration.user_agent||yt.USER_AGENT;if(t+=`Allow: ${yt.ALLOWED_METHODS}\r
|
|
79
|
+
`,t+=`Supported: ${s}\r
|
|
80
|
+
`,t+=`User-Agent: ${i}\r
|
|
81
|
+
`,this.body){const a=lt.str_utf8_length(this.body);t+=`Content-Length: ${a}\r
|
|
82
82
|
\r
|
|
83
83
|
`,t+=this.body}else t+=`Content-Length: 0\r
|
|
84
84
|
\r
|
|
85
|
-
`;return t}clone(){const t=new
|
|
86
|
-
`;if(this.method===
|
|
85
|
+
`;return t}clone(){const t=new Jo(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(s){t.headers[s]=this.headers[s].slice()},this),t.body=this.body,t.extraHeaders=lt.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t}}class qu extends Jo{constructor(t,s,i,a,n){super(yt.INVITE,t,s,i,a,n),this.transaction=null}cancel(t){this.transaction.cancel(t)}clone(){const t=new qu(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(s){t.headers[s]=this.headers[s].slice()},this),t.body=this.body,t.extraHeaders=lt.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t.transaction=this.transaction,t}}class Ed{constructor(){this.data=null,this.headers=null,this.method=null,this.via=null,this.via_branch=null,this.call_id=null,this.cseq=null,this.from=null,this.from_tag=null,this.to=null,this.to_tag=null,this.body=null,this.sdp=null}addHeader(t,s){const i={raw:s};t=lt.headerize(t),this.headers[t]?this.headers[t].push(i):this.headers[t]=[i]}getHeader(t){const s=this.headers[lt.headerize(t)];if(s){if(s[0])return s[0].raw}else return}getHeaders(t){const s=this.headers[lt.headerize(t)],i=[];if(!s)return[];for(const a of s)i.push(a.raw);return i}hasHeader(t){return!!this.headers[lt.headerize(t)]}parseHeader(t,s=0){if(t=lt.headerize(t),this.headers[t]){if(s>=this.headers[t].length){Ha.debug(`not so many "${t}" headers present`);return}}else{Ha.debug(`header "${t}" not present`);return}const i=this.headers[t][s],a=i.raw;if(i.parsed)return i.parsed;const n=Zm.parse(a,t.replace(/-/g,"_"));if(n===-1){this.headers[t].splice(s,1),Ha.debug(`error parsing "${t}" header field with value "${a}"`);return}else return i.parsed=n,n}s(t,s){return this.parseHeader(t,s)}setHeader(t,s){const i={raw:s};this.headers[lt.headerize(t)]=[i]}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=Sd.parse(this.body||""),this.sdp)}toString(){return this.data}}class eg extends Ed{constructor(t){super(),this.ua=t,this.headers={},this.ruri=null,this.transport=null,this.server_transaction=null}reply(t,s,i,a,n,r){const h=[];let d=this.getHeader("To");if(t=t||null,s=s||null,!t||t<100||t>699)throw new TypeError(`Invalid status_code: ${t}`);if(s&&typeof s!="string"&&!(s instanceof String))throw new TypeError(`Invalid reason_phrase: ${s}`);s=s||yt.REASON_PHRASE[t]||"",i=lt.cloneArray(i),this.ua.configuration.extra_headers&&(i=i.concat(this.ua.configuration.extra_headers));let _=`SIP/2.0 ${t} ${s}\r
|
|
86
|
+
`;if(this.method===yt.INVITE&&t>100&&t<=200){const T=this.getHeaders("record-route");for(const S of T)_+=`Record-Route: ${S}\r
|
|
87
87
|
`}const g=this.getHeaders("via");for(const T of g)_+=`Via: ${T}\r
|
|
88
|
-
`;!this.to_tag&&t>100?d+=`;tag=${
|
|
88
|
+
`;!this.to_tag&&t>100?d+=`;tag=${lt.newTag()}`:this.to_tag&&!this.s("to").hasParam("tag")&&(d+=`;tag=${this.to_tag}`),_+=`To: ${d}\r
|
|
89
89
|
`,_+=`From: ${this.getHeader("From")}\r
|
|
90
90
|
`,_+=`Call-ID: ${this.call_id}\r
|
|
91
91
|
`,_+=`CSeq: ${this.cseq} ${this.method}\r
|
|
92
|
-
`;for(const T of
|
|
93
|
-
`;switch(this.method){case
|
|
94
|
-
`,_+=`Accept: ${
|
|
95
|
-
`):t===405?_+=`Allow: ${
|
|
96
|
-
`:t===415&&(_+=`Accept: ${
|
|
92
|
+
`;for(const T of i)_+=`${T.trim()}\r
|
|
93
|
+
`;switch(this.method){case yt.INVITE:this.ua.configuration.session_timers&&h.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&h.push("gruu"),h.push("ice","replaces");break;case yt.UPDATE:this.ua.configuration.session_timers&&h.push("timer"),a&&h.push("ice"),h.push("replaces")}if(h.push("outbound"),this.method===yt.OPTIONS?(_+=`Allow: ${yt.ALLOWED_METHODS}\r
|
|
94
|
+
`,_+=`Accept: ${yt.ACCEPTED_BODY_TYPES}\r
|
|
95
|
+
`):t===405?_+=`Allow: ${yt.ALLOWED_METHODS}\r
|
|
96
|
+
`:t===415&&(_+=`Accept: ${yt.ACCEPTED_BODY_TYPES}\r
|
|
97
97
|
`),_+=`Supported: ${h}\r
|
|
98
|
-
`,a){const T=
|
|
98
|
+
`,a){const T=lt.str_utf8_length(a);_+=`Content-Type: application/sdp\r
|
|
99
99
|
`,_+=`Content-Length: ${T}\r
|
|
100
100
|
\r
|
|
101
101
|
`,_+=a}else _+=`Content-Length: 0\r
|
|
102
102
|
\r
|
|
103
|
-
`;this.server_transaction.receiveResponse(t,_,
|
|
104
|
-
`;for(const r of
|
|
105
|
-
`;let
|
|
103
|
+
`;this.server_transaction.receiveResponse(t,_,n,r)}reply_sl(t=null,s=null){const i=this.getHeaders("via");if(!t||t<100||t>699)throw new TypeError(`Invalid status_code: ${t}`);if(s&&typeof s!="string"&&!(s instanceof String))throw new TypeError(`Invalid reason_phrase: ${s}`);s=s||yt.REASON_PHRASE[t]||"";let a=`SIP/2.0 ${t} ${s}\r
|
|
104
|
+
`;for(const r of i)a+=`Via: ${r}\r
|
|
105
|
+
`;let n=this.getHeader("To");if(!this.to_tag&&t>100?n+=`;tag=${lt.newTag()}`:this.to_tag&&!this.s("to").hasParam("tag")&&(n+=`;tag=${this.to_tag}`),a+=`To: ${n}\r
|
|
106
106
|
`,a+=`From: ${this.getHeader("From")}\r
|
|
107
107
|
`,a+=`Call-ID: ${this.call_id}\r
|
|
108
108
|
`,a+=`CSeq: ${this.cseq} ${this.method}\r
|
|
109
109
|
`,this.ua.configuration.extra_headers)for(const r of this.ua.configuration.extra_headers)a+=`${r.trim()}\r
|
|
110
110
|
`;a+=`Content-Length: 0\r
|
|
111
111
|
\r
|
|
112
|
-
`,this.transport.send(a)}}class Ym extends pd{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var yt={OutgoingRequest:Ko,InitialOutgoingInviteRequest:Vu,IncomingRequest:Km,IncomingResponse:Ym};const _r=Xe(yt),Jm=ut,ps=Ct(),Jt=new Jm("DigestAuthentication");var md=class{constructor(t){this._credentials=t,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}get(t){switch(t){case"realm":return this._realm;case"ha1":return this._ha1;default:Jt.warn('get() | cannot get "%s" parameter',t);return}}authenticate({method:t,ruri:n,body:l},a,s=null){if(this._algorithm=a.algorithm,this._realm=a.realm,this._nonce=a.nonce,this._opaque=a.opaque,this._stale=a.stale,this._algorithm){if(this._algorithm!=="MD5")return Jt.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return Jt.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return Jt.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return Jt.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return Jt.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(a.qop)if(a.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(a.qop.indexOf("auth")>-1)this._qop="auth";else return Jt.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=t,this._uri=n,this._cnonce=s||ps.createRandomToken(12),this._nc+=1;const r=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-r.length)+r,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=ps.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._ha1=this._credentials.ha1;let h,d;return this._qop==="auth"?(h=`${this._method}:${this._uri}`,d=ps.calculateMD5(h),Jt.debug('authenticate() | using qop=auth [a2:"%s"]',h),this._response=ps.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${d}`)):this._qop==="auth-int"?(h=`${this._method}:${this._uri}:${ps.calculateMD5(l||"")}`,d=ps.calculateMD5(h),Jt.debug('authenticate() | using qop=auth-int [a2:"%s"]',h),this._response=ps.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${d}`)):this._qop===null&&(h=`${this._method}:${this._uri}`,d=ps.calculateMD5(h),Jt.debug('authenticate() | using qop=null [a2:"%s"]',h),this._response=ps.calculateMD5(`${this._ha1}:${this._nonce}:${d}`)),Jt.debug("authenticate() | response generated"),!0}toString(){const t=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return t.push(`algorithm=${this._algorithm}`),t.push(`username="${this._credentials.username}"`),t.push(`realm="${this._realm}"`),t.push(`nonce="${this._nonce}"`),t.push(`uri="${this._uri}"`),t.push(`response="${this._response}"`),this._opaque&&t.push(`opaque="${this._opaque}"`),this._qop&&(t.push(`qop=${this._qop}`),t.push(`cnonce="${this._cnonce}"`),t.push(`nc=${this._ncHex}`)),`Digest ${t.join(", ")}`}};const zm=Xe(md),ms=500,Xm=4e3,af=5e3;var ju={T1:ms,T2:Xm,T4:af,TIMER_B:64*ms,TIMER_D:0*ms,TIMER_F:64*ms,TIMER_H:64*ms,TIMER_I:0*ms,TIMER_J:0*ms,TIMER_K:0*af,TIMER_L:64*ms,TIMER_M:64*ms,PROVISIONAL_RESPONSE_INTERVAL:6e4};const Li=Xe(ju),hl=ft.EventEmitter,_l=ut,zi=De,uf=yt,os=ju,cf=new _l("NonInviteClientTransaction"),Jl=new _l("InviteClientTransaction"),Qm=new _l("AckClientTransaction"),ff=new _l("NonInviteServerTransaction"),zl=new _l("InviteServerTransaction"),he={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"};class Zm extends hl{constructor(t,n,l,a){super(),this.type=he.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=n,this.request=l,this.eventHandlers=a;let s=`SIP/2.0/${n.via_transport}`;s+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",s),this.ua.newTransaction(this)}get C(){return he}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(he.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},os.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){cf.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){cf.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(t){const n=t.status_code;if(n<200)switch(this.state){case he.STATUS_TRYING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break}else switch(this.state){case he.STATUS_TRYING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_COMPLETED),clearTimeout(this.F),n===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(t),this.K=setTimeout(()=>{this.timer_K()},os.TIMER_K);break;case he.STATUS_COMPLETED:break}}}class eg extends hl{constructor(t,n,l,a){super(),this.type=he.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=n,this.request=l,this.eventHandlers=a,l.transaction=this;let s=`SIP/2.0/${n.via_transport}`;s+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",s),this.ua.newTransaction(this)}get C(){return he}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(he.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},os.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==he.STATUS_ACCEPTED&&(Jl.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){Jl.debug(`Timer M expired for transaction ${this.id}`),this.state===he.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){Jl.debug(`Timer B expired for transaction ${this.id}`),this.state===he.STATUS_CALLING&&(this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){Jl.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(t){const n=new uf.OutgoingRequest(zi.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});n.setHeader("from",this.request.getHeader("from")),n.setHeader("via",this.request.getHeader("via")),n.setHeader("to",t.getHeader("to")),this.D=setTimeout(()=>{this.timer_D()},os.TIMER_D),this.transport.send(n)}cancel(t){if(this.state!==he.STATUS_PROCEEDING)return;const n=new uf.OutgoingRequest(zi.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});n.setHeader("from",this.request.getHeader("from")),n.setHeader("via",this.request.getHeader("via")),n.setHeader("to",this.request.getHeader("to")),t&&n.setHeader("reason",t),this.transport.send(n)}receiveResponse(t){const n=t.status_code;if(n>=100&&n<=199)switch(this.state){case he.STATUS_CALLING:this.stateChanged(he.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break;case he.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(t);break}else if(n>=200&&n<=299)switch(this.state){case he.STATUS_CALLING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},os.TIMER_M),this.eventHandlers.onReceiveResponse(t);break;case he.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(t);break}else if(n>=300&&n<=699)switch(this.state){case he.STATUS_CALLING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_COMPLETED),this.sendACK(t),this.eventHandlers.onReceiveResponse(t);break;case he.STATUS_COMPLETED:this.sendACK(t);break}}}class tg extends hl{constructor(t,n,l,a){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=n,this.request=l,this.eventHandlers=a;let s=`SIP/2.0/${n.via_transport}`;s+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",s)}get C(){return he}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){Qm.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class sg extends hl{constructor(t,n,l){super(),this.type=he.NON_INVITE_SERVER,this.id=l.via_branch,this.ua=t,this.transport=n,this.request=l,this.last_response="",l.server_transaction=this,this.state=he.STATUS_TRYING,t.newTransaction(this)}get C(){return he}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_J(){ff.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,ff.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(t,n,l,a){if(t===100)switch(this.state){case he.STATUS_TRYING:this.stateChanged(he.STATUS_PROCEEDING),this.transport.send(n)||this.onTransportError();break;case he.STATUS_PROCEEDING:this.last_response=n,this.transport.send(n)?l&&l():(this.onTransportError(),a&&a());break}else if(t>=200&&t<=699)switch(this.state){case he.STATUS_TRYING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_COMPLETED),this.last_response=n,this.J=setTimeout(()=>{this.timer_J()},os.TIMER_J),this.transport.send(n)?l&&l():(this.onTransportError(),a&&a());break;case he.STATUS_COMPLETED:break}}}class ng extends hl{constructor(t,n,l){super(),this.type=he.INVITE_SERVER,this.id=l.via_branch,this.ua=t,this.transport=n,this.request=l,this.last_response="",l.server_transaction=this,this.state=he.STATUS_PROCEEDING,t.newTransaction(this),this.resendProvisionalTimer=null,l.reply(100)}get C(){return he}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_H(){zl.debug(`Timer H expired for transaction ${this.id}`),this.state===he.STATUS_COMPLETED&&zl.debug("ACK not received, dialog will be terminated"),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){zl.debug(`Timer L expired for transaction ${this.id}`),this.state===he.STATUS_ACCEPTED&&(this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,zl.debug(`transport error occurred, deleting transaction ${this.id}`),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(t,n,l,a){if(t>=100&&t<=199)switch(this.state){case he.STATUS_PROCEEDING:this.transport.send(n)||this.onTransportError(),this.last_response=n;break}if(t>100&&t<=199&&this.state===he.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},os.PROVISIONAL_RESPONSE_INTERVAL));else if(t>=200&&t<=299)switch(this.state){case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_ACCEPTED),this.last_response=n,this.L=setTimeout(()=>{this.timer_L()},os.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case he.STATUS_ACCEPTED:this.transport.send(n)?l&&l():(this.onTransportError(),a&&a());break}else if(t>=300&&t<=699)switch(this.state){case he.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(n)?(this.stateChanged(he.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},os.TIMER_H),l&&l()):(this.onTransportError(),a&&a());break}}}function rg({_transactions:c},t){let n;switch(t.method){case zi.INVITE:if(n=c.ist[t.via_branch],n){switch(n.state){case he.STATUS_PROCEEDING:n.transport.send(n.last_response);break;case he.STATUS_ACCEPTED:break}return!0}break;case zi.ACK:if(n=c.ist[t.via_branch],n){if(n.state===he.STATUS_ACCEPTED)return!1;if(n.state===he.STATUS_COMPLETED)return n.state=he.STATUS_CONFIRMED,n.I=setTimeout(()=>{n.timer_I()},os.TIMER_I),!0}else return!1;break;case zi.CANCEL:return n=c.ist[t.via_branch],n?(t.reply_sl(200),n.state!==he.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(n=c.nist[t.via_branch],n){switch(n.state){case he.STATUS_TRYING:break;case he.STATUS_PROCEEDING:case he.STATUS_COMPLETED:n.transport.send(n.last_response);break}return!0}break}}var gr={C:he,NonInviteClientTransaction:Zm,InviteClientTransaction:eg,AckClientTransaction:tg,NonInviteServerTransaction:sg,InviteServerTransaction:ng,checkTransaction:rg};const Gt=Xe(gr),ig=ut,df=De,lg=md,$a=gr,og=new ig("RequestSender"),Ha={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var Tr=class{constructor(t,n,l){this._ua=t,this._eventHandlers=l,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(const a in Ha)Object.prototype.hasOwnProperty.call(Ha,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Ha[a]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==df.BYE||this._method!==df.ACK)&&this._eventHandlers.onTransportError()}send(){const t={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:n=>{this._receiveResponse(n)}};switch(this._method){case"INVITE":this.clientTransaction=new $a.InviteClientTransaction(this._ua,this._ua.transport,this._request,t);break;case"ACK":this.clientTransaction=new $a.AckClientTransaction(this._ua,this._ua.transport,this._request,t);break;default:this.clientTransaction=new $a.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,t)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}_receiveResponse(t){let n,l;const a=t.status_code;if((a===401||a===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(t.status_code===401?(n=t.parseHeader("www-authenticate"),l="authorization"):(n=t.parseHeader("proxy-authenticate"),l="proxy-authorization"),!n){og.debug(`${t.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(t);return}if(!this._challenged||!this._staled&&n.stale===!0){if(this._auth||(this._auth=new lg({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,n)){this._eventHandlers.onReceiveResponse(t);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),n.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq",`${this._request.cseq} ${this._method}`),this._request.setHeader(l,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(t)}else this._eventHandlers.onReceiveResponse(t)}};const tl=Xe(Tr),ag=ut,Fa=Ct(),Tn=De,hf=yt,_f=Tr,$i=new ag("Registrator"),Xl=10;var ug=class{constructor(t,n){this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=Fa.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._contact+=`;reg-id=${this._reg_id}`,this._contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const l=t[n];this._extraContactParams+=`;${n}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){$i.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact};expires=${this._expires}${this._extraContactParams}`),t.push(`Expires: ${this._expires}`);const n=new hf.OutgoingRequest(Tn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),l=new _f(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,Tn.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,Tn.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){$i.debug("no Contact header in response to REGISTER, response ignored");break}const s=a.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=s.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=s.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){$i.debug("no Contact header pointing to us, response ignored");break}let h=r.getParam("expires");!h&&a.hasHeader("expires")&&(h=a.getHeader("expires")),h||(h=this._expires),h=Number(h),h<Xl&&(h=Xl);const d=h>64?h*1e3/2+Math.floor((h/2-32)*1e3*Math.random()):h*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<Xl&&(this._expires=Xl),this.register()):($i.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,Tn.causes.SIP_FAILURE_CODE));break}default:{const s=Fa.sipErrorCause(a.status_code);this._registrationFailure(a,s)}}}});this._registering=!0,l.send()}unregister(t={}){if(!this._registered){$i.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();t.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),n.push("Expires: 0");const l=new hf.OutgoingRequest(Tn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new _f(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,Tn.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,Tn.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const r=Fa.sipErrorCause(s.status_code);this._unregistered(s,r)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,n){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:n}))}_unregistered(t,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:n||null})}};class cg extends Error{constructor(t,n){super(),this.code=1,this.name="CONFIGURATION_ERROR",this.parameter=t,this.value=n,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}}class fg extends Error{constructor(t){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=t,this.message=`Invalid status: ${t}`}}class dg extends Error{constructor(t){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=t}}class hg extends Error{constructor(t){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=t}}var Cs={ConfigurationError:cg,InvalidStateError:fg,NotSupportedError:dg,NotReadyError:hg};const js=Xe(Cs),Va=De,Ql=gr,_g=Tr,ja={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var gd=class{constructor(t,n,l){this._dialog=t,this._ua=t._ua,this._request=n,this._eventHandlers=l,this._reattempt=!1,this._reattemptTimer=null;for(const a in ja)Object.prototype.hasOwnProperty.call(ja,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=ja[a]))}get request(){return this._request}send(){const t=new _g(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:n=>{this._eventHandlers.onAuthenticated(n)},onReceiveResponse:n=>{this._receiveResponse(n)}});if(t.send(),(this._request.method===Va.INVITE||this._request.method===Va.UPDATE&&this._request.body)&&t.clientTransaction.state!==Ql.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;const n=()=>{(t.clientTransaction.state===Ql.C.STATUS_ACCEPTED||t.clientTransaction.state===Ql.C.STATUS_COMPLETED||t.clientTransaction.state===Ql.C.STATUS_TERMINATED)&&(t.clientTransaction.removeListener("stateChanged",n),this._dialog.uac_pending_reply=!1)};t.clientTransaction.on("stateChanged",n)}}_receiveResponse(t){t.status_code===408||t.status_code===481?this._eventHandlers.onDialogError(t):t.method===Va.INVITE&&t.status_code===491?this._reattempt?t.status_code>=200&&t.status_code<300?this._eventHandlers.onSuccessResponse(t):t.status_code>=300&&this._eventHandlers.onErrorResponse(t):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):t.status_code>=200&&t.status_code<300?this._eventHandlers.onSuccessResponse(t):t.status_code>=300&&this._eventHandlers.onErrorResponse(t)}};const pg=Xe(gd),mg=ut,pf=yt,$s=De,Hi=gr,gg=gd,qa=Ct(),Ba=new mg("Dialog"),Hs={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var Td=class{static get C(){return Hs}constructor(t,n,l,a=Hs.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!n.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};n instanceof pf.IncomingResponse&&(a=n.status_code<200?Hs.STATUS_EARLY:Hs.STATUS_CONFIRMED);const s=n.parseHeader("contact");l==="UAS"?(this._id={call_id:n.call_id,local_tag:n.to_tag,remote_tag:n.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=n.cseq,this._local_uri=n.parseHeader("to").uri,this._remote_uri=n.parseHeader("from").uri,this._remote_target=s.uri,this._route_set=n.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):l==="UAC"&&(this._id={call_id:n.call_id,local_tag:n.from_tag,remote_tag:n.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=n.cseq,this._local_uri=n.parseHeader("from").uri,this._remote_uri=n.parseHeader("to").uri,this._remote_target=s.uri,this._route_set=n.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),Ba.debug(`new ${l} dialog created with status ${this._state===Hs.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Hs.STATUS_TERMINATED}update(t,n){this._state=Hs.STATUS_CONFIRMED,Ba.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){Ba.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Hs.STATUS_TERMINATED}sendRequest(t,n={}){const l=qa.cloneArray(n.extraHeaders),a=qa.cloneObject(n.eventHandlers),s=n.body||null,r=this._createRequest(t,l,s);return a.onAuthenticated=()=>{this._local_seqnum+=1},new gg(this,r,a).send(),r}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===$s.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===$s.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,n,l){n=qa.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=t===$s.CANCEL||t===$s.ACK?this._local_seqnum:this._local_seqnum+=1;return new pf.OutgoingRequest(t,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},n,l)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===$s.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===$s.INVITE||t.method===$s.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const n=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${n}`]),!1}else{this._uas_pending_reply=!0;const n=()=>{(t.server_transaction.state===Hi.C.STATUS_ACCEPTED||t.server_transaction.state===Hi.C.STATUS_COMPLETED||t.server_transaction.state===Hi.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",n),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",n)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Hi.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===$s.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Hi.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}};const Zl=Xe(Td);var qu={exports:{}};const Tg=ft.EventEmitter,vg=ut,Sg=De,Eg=Cs,mf=Ct(),yg=new vg("RTCSession:DTMF"),vd={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};qu.exports=class extends Tg{constructor(t){super(),this._session=t,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(t,n={}){if(t===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new Eg.InvalidStateError(this._session.status);const l=mf.cloneArray(n.extraHeaders);if(this.eventHandlers=mf.cloneObject(n.eventHandlers),typeof t=="string")t=t.toUpperCase();else if(typeof t=="number")t=t.toString();else throw new TypeError(`Invalid tone: ${t}`);if(t.match(/^[0-9A-DR#*]$/))this._tone=t;else throw new TypeError(`Invalid tone: ${t}`);this._duration=n.duration,l.push("Content-Type: application/dtmf-relay");let a=`Signal=${this._tone}\r
|
|
113
|
-
`;a+=`Duration=${this._duration}`,this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(
|
|
114
|
-
`);a.length>=1&&
|
|
115
|
-
`,1)[0],"Status_Line");if(n===-1){vn.debug(`receiveNotify() | error parsing NOTIFY body: "${t.body}"`);return}switch(!0){case/^100$/.test(n.status_code):this.emit("trying",{request:t,status_line:n});break;case/^1[0-9]{2}$/.test(n.status_code):this.emit("progress",{request:t,status_line:n});break;case/^2[0-9]{2}$/.test(n.status_code):this.emit("accepted",{request:t,status_line:n});break;default:this.emit("failed",{request:t,status_line:n});break}}_requestSucceeded(t){vn.debug("REFER succeeded"),vn.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:t})}_requestFailed(t,n){vn.debug("REFER failed"),vn.debug('emit "requestFailed"'),this.emit("requestFailed",{response:t||null,cause:n})}};const kg=Xe(Cd),Pg=ft.EventEmitter,vf=kt,Mg=ut,fe=De,Sn=Cs,Sf=gr,Ge=Ct(),Vi=ju,Lg=yt,eo=Td,$g=Tr,Mt=Sd,Ef=Ed,Hg=yd,Fg=Cd,yf=ys(),z=new Mg("RTCSession"),te={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},to=["audio","video"];var Ad=class Ru extends Pg{static get C(){return te}constructor(t){z.debug("new"),super(),this._id=null,this._ua=t,this._status=te.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._tones=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:fe.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return te}get causes(){return fe.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:case te.STATUS_INVITE_RECEIVED:case te.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case te.STATUS_ANSWERED:case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case te.STATUS_CANCELED:case te.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(t,n={},l){z.debug("connect()");const a=t,s=Ge.cloneObject(n.eventHandlers),r=Ge.cloneArray(n.extraHeaders),h=Ge.cloneObject(n.mediaConstraints,{audio:!0,video:!0}),d=n.mediaStream||null,_=Ge.cloneObject(n.pcConfig,{iceServers:[]}),g=n.rtcConstraints||null,T=n.rtcOfferConstraints||null;if(this._rtcOfferConstraints=T,this._rtcAnswerConstraints=n.rtcAnswerConstraints||null,this._data=n.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==te.STATUS_NULL)throw new Sn.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Sn.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);this._sessionTimers.enabled&&Ge.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=fe.SESSION_EXPIRES);for(const C in s)Object.prototype.hasOwnProperty.call(s,C)&&this.on(C,s[C]);this._from_tag=Ge.newTag();const S=n.anonymous||!1,E={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:S,outbound:!0}),S?(E.from_display_name="Anonymous",E.from_uri=new yf("sip","anonymous","anonymous.invalid"),r.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),r.push("Privacy: id")):n.fromUserName&&(E.from_uri=new yf("sip",n.fromUserName,this._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(E.from_display_name=n.fromDisplayName),r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&r.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Lg.InitialOutgoingInviteRequest(t,this._ua,E,r),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(_,g),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,l&&l(this),this._newRTCSession("local",this._request),this._sendInitialRequest(h,T,d)}init_incoming(t,n){z.debug("init_incoming()");let l;const a=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&a!=="application/sdp"){t.reply(415);return}if(this._status=te.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(l=t.getHeader("expires")*1e3),t.to_tag=Ge.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=te.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,fe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,fe.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),this._newRTCSession("remote",t),this._status!==te.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){z.debug("answer()");const n=this._request,l=Ge.cloneArray(t.extraHeaders),a=Ge.cloneObject(t.mediaConstraints),s=t.mediaStream||null,r=Ge.cloneObject(t.pcConfig,{iceServers:[]}),h=t.rtcConstraints||null,d=t.rtcAnswerConstraints||null,_=Ge.cloneObject(t.rtcOfferConstraints);let g,T=!1,S=!1,E=!1,C=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new Sn.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==te.STATUS_WAITING_FOR_ANSWER)throw new Sn.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Ge.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=fe.SESSION_EXPIRES),this._status=te.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),l.unshift(`Contact: ${this._contact}`);const A=n.parseSDP();Array.isArray(A.media)||(A.media=[A.media]);for(const R of A.media)R.type==="audio"&&(T=!0,(!R.direction||R.direction==="sendrecv")&&(E=!0)),R.type==="video"&&(S=!0,(!R.direction||R.direction==="sendrecv")&&(C=!0));if(s&&a.audio===!1){g=s.getAudioTracks();for(const R of g)s.removeTrack(R)}if(s&&a.video===!1){g=s.getVideoTracks();for(const R of g)s.removeTrack(R)}!s&&a.audio===void 0&&(a.audio=E),!s&&a.video===void 0&&(a.video=C),!s&&!T&&!_.offerToReceiveAudio&&(a.audio=!1),!s&&!S&&!_.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(r,h),Promise.resolve().then(()=>{if(s)return s;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(R=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),this._failed("local",null,fe.causes.USER_DENIED_MEDIA_ACCESS),z.warn('emit "getusermediafailed" [error:%o]',R),this.emit("getusermediafailed",R),new Error("getUserMedia() failed"))})}).then(R=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=R,R&&R.getTracks().forEach(V=>{this._connection.addTrack(V,R)})}).then(()=>{if(this._late_sdp)return;const R={originator:"remote",type:"offer",sdp:n.body};z.debug('emit "sdp"'),this.emit("sdp",R);const V=new RTCSessionDescription({type:"offer",sdp:R.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(V)).catch(w=>{throw n.reply(488),this._failed("system",null,fe.causes.WEBRTC_ERROR),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',w),this.emit("peerconnection:setremotedescriptionfailed",w),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(n),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",d).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")})}).then(R=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,l),n.reply(200,null,l,R,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,R),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,fe.causes.CONNECTION_ERROR)})}).catch(R=>{this._status!==te.STATUS_TERMINATED&&z.warn(R)})}terminate(t={}){z.debug("terminate()");const n=t.cause||fe.causes.BYE,l=Ge.cloneArray(t.extraHeaders),a=t.body;let s,r=t.status_code,h=t.reason_phrase;if(this._status===te.STATUS_TERMINATED)throw new Sn.InvalidStateError(this._status);switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:if(z.debug("canceling session"),r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(h=h||fe.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${h}"`),this._status===te.STATUS_NULL||this._status===te.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===te.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=te.STATUS_CANCELED,this._failed("local",null,fe.causes.CANCELED);break;case te.STATUS_WAITING_FOR_ANSWER:case te.STATUS_ANSWERED:if(z.debug("rejecting session"),r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,h,l,a),this._failed("local",null,fe.causes.REJECTED);break;case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:if(z.debug("terminating session"),h=t.reason_phrase||fe.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&l.push(`Reason: SIP ;cause=${r}; text="${h}"`),this._status===te.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Sf.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:_})=>{_===fe.ACK&&(this.sendRequest(fe.BYE,{extraHeaders:l,body:a}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Sf.C.STATUS_TERMINATED&&(this.sendRequest(fe.BYE,{extraHeaders:l,body:a}),d.terminate())}),this._ended("local",null,n),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(fe.BYE,{extraHeaders:l,body:a}),this._ended("local",null,n)}}sendDTMF(t,n={}){z.debug("sendDTMF() | tones: %s",t);let l=0,a=n.duration||null,s=n.interToneGap||null;const r=n.transportType||fe.DTMF_TRANSPORT.INFO;if(t===void 0)throw new TypeError("Not enough arguments");if(this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new Sn.InvalidStateError(this._status);if(r!==fe.DTMF_TRANSPORT.INFO&&r!==fe.DTMF_TRANSPORT.RFC2833)throw new TypeError(`invalid transportType: ${r}`);if(typeof t=="number"&&(t=t.toString()),!t||typeof t!="string"||!t.match(/^[0-9A-DR#*,]+$/i))throw new TypeError(`Invalid tones: ${t}`);if(a&&!Ge.isDecimal(a))throw new TypeError(`Invalid tone duration: ${a}`);if(a?a<Mt.C.MIN_DURATION?(z.debug(`"duration" value is lower than the minimum allowed, setting it to ${Mt.C.MIN_DURATION} milliseconds`),a=Mt.C.MIN_DURATION):a>Mt.C.MAX_DURATION?(z.debug(`"duration" value is greater than the maximum allowed, setting it to ${Mt.C.MAX_DURATION} milliseconds`),a=Mt.C.MAX_DURATION):a=Math.abs(a):a=Mt.C.DEFAULT_DURATION,n.duration=a,s&&!Ge.isDecimal(s))throw new TypeError(`Invalid interToneGap: ${s}`);if(s?s<Mt.C.MIN_INTER_TONE_GAP?(z.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${Mt.C.MIN_INTER_TONE_GAP} milliseconds`),s=Mt.C.MIN_INTER_TONE_GAP):s=Math.abs(s):s=Mt.C.DEFAULT_INTER_TONE_GAP,r===fe.DTMF_TRANSPORT.RFC2833){const d=this._getDTMFRTPSender();d&&(t=d.toneBuffer+t,d.insertDTMF(t,a,s));return}if(this._tones){this._tones+=t;return}this._tones=t,h.call(this);function h(){let d;if(this._status===te.STATUS_TERMINATED||!this._tones||l>=this._tones.length){this._tones=null;return}const _=this._tones[l];if(l+=1,_===",")d=2e3;else{const g=new Mt(this);n.eventHandlers={onFailed:()=>{this._tones=null}},g.send(_,n),d=a+s}setTimeout(h.bind(this),d)}}sendInfo(t,n,l={}){if(z.debug("sendInfo()"),this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new Sn.InvalidStateError(this._status);new Ef(this).send(t,n,l)}mute(t={audio:!0,video:!1}){z.debug("mute()");let n=!1,l=!1;this._audioMuted===!1&&t.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(l=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||l===!0)&&this._onmute({audio:n,video:l})}unmute(t={audio:!0,video:!0}){z.debug("unmute()");let n=!1,l=!1;this._audioMuted===!0&&t.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(l=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||l===!0)&&this._onunmute({audio:n,video:l})}hold(t={},n){if(z.debug("hold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const l={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}unhold(t={},n){if(z.debug("unhold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const l={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},n){z.debug("renegotiate()");const l=t.rtcOfferConstraints||null;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const a={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}),!0}refer(t,n){z.debug("refer()");const l=t;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${l}`);const a=new Fg(this);a.sendRefer(t,n);const s=a.id;return this._referSubscribers[s]=a,a.on("requestFailed",()=>{delete this._referSubscribers[s]}),a.on("accepted",()=>{delete this._referSubscribers[s]}),a.on("failed",()=>{delete this._referSubscribers[s]}),a}sendRequest(t,n){return z.debug("sendRequest()"),this._dialog.sendRequest(t,n)}receiveRequest(t){if(z.debug("receiveRequest()"),t.method===fe.CANCEL)(this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED)&&(this._status=te.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,fe.causes.CANCELED));else switch(t.method){case fe.ACK:if(this._status!==te.STATUS_WAITING_FOR_ACK)return;if(this._status=te.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:fe.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",n);const l=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(a=>{this.terminate({cause:fe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",t);break;case fe.BYE:this._status===te.STATUS_CONFIRMED||this._status===te.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,fe.causes.BYE)):this._status===te.STATUS_INVITE_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,fe.causes.BYE)):t.reply(403,"Wrong Status");break;case fe.INVITE:this._status===te.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case fe.INFO:if(this._status===te.STATUS_1XX_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED||this._status===te.STATUS_WAITING_FOR_ACK||this._status===te.STATUS_CONFIRMED){const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;n&&n.match(/^application\/dtmf-relay/i)?new Mt(this).init_incoming(t):n!==void 0?new Ef(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case fe.UPDATE:this._status===te.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case fe.REFER:this._status===te.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case fe.NOTIFY:this._status===te.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){z.warn("onTransportError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.CONNECTION_ERROR,cause:fe.causes.CONNECTION_ERROR})}onRequestTimeout(){z.warn("onRequestTimeout()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:fe.causes.REQUEST_TIMEOUT,cause:fe.causes.REQUEST_TIMEOUT})}onDialogError(){z.warn("onDialogError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.DIALOG_ERROR,cause:fe.causes.DIALOG_ERROR})}newDTMF(t){z.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){z.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(z.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(z.debug("_isReadyToReOffer() | session not established yet"),!1):(z.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(z.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(z.debug("close() | closing local MediaStream"),Ge.closeMediaStream(this._localMediaStream)),this._status!==te.STATUS_TERMINATED){if(this._status=te.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){z.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,n){let l=Vi.T1;function a(){this._status===te.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],n),l<Vi.T2&&(l=l*2,l>Vi.T2&&(l=Vi.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),l))}this._timers.invite2xxTimer=setTimeout(a.bind(this),l)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ACK&&(z.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(fe.BYE),this._ended("remote",null,fe.causes.NO_ACK))},Vi.TIMER_H)}_createRTCConnection(t,n){this._connection=new RTCPeerConnection(t,n),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:fe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:fe.causes.RTP_TIMEOUT})}),z.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,n){if(z.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const l=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?l.createOffer(n).catch(a=>(z.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):l.createAnswer(n).catch(a=>(z.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>l.setLocalDescription(a).catch(s=>(this._rtcReady=!0,z.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s)))).then(()=>{const a=n&&n.iceRestart;if(l.iceGatheringState==="complete"&&!a||l.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:l.localDescription.sdp};return z.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let r=!1,h,d;this._iceReady=!1;const _=()=>{l.removeEventListener("icecandidate",h),l.removeEventListener("icegatheringstatechange",d),r=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:t,sdp:l.localDescription.sdp};z.debug('emit "sdp"'),this.emit("sdp",g),s(g.sdp)};l.addEventListener("icecandidate",h=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:_}):r||_()}),l.addEventListener("icegatheringstatechange",d=()=>{l.iceGatheringState==="complete"&&!r&&_()})})})}_createDialog(t,n,l){const a=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+a+s;let h=this._earlyDialogs[r];if(l)return h?!0:(h=new eo(this,t,n,eo.C.STATUS_EARLY),h.error?(z.debug(h.error),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=h,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,h)return h.update(t,n),this._dialog=h,delete this._earlyDialogs[r],!0;const d=new eo(this,t,n);return d.error?(z.debug(d.error),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(t){z.debug("receiveReinvite()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(h={}){a=!0;const d=h.status_code||403,_=h.reason_phrase||"",g=Ge.cloneArray(h.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,_,g)}if(this.emit("reinvite",l),a)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(h=>{r.call(this,h)}).catch(()=>{t.reply(500)});return}if(n!=="application/sdp"){z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(h=>{this._status!==te.STATUS_TERMINATED&&r.call(this,h)}).catch(h=>{z.warn(h)});function r(h){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),this._late_sdp&&(h=this._mangleOffer(h)),t.reply(200,null,d,h,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,h),this._setACKTimer()}),typeof l.callback=="function"&&l.callback()}}_receiveUpdate(t){z.debug("receiveUpdate()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(h={}){a=!0;const d=h.status_code||403,_=h.reason_phrase||"",g=Ge.cloneArray(h.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,_,g)}if(this.emit("update",l),a)return;if(!t.body){r.call(this,null);return}if(n!=="application/sdp"){z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(h=>{this._status!==te.STATUS_TERMINATED&&r.call(this,h)}).catch(h=>{z.warn(h)});function r(h){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),t.reply(200,null,d,h),typeof l.callback=="function"&&l.callback()}}_processInDialogSdpOffer(t){z.debug("_processInDialogSdpOffer()");const n=t.parseSDP();let l=!1;for(const r of n.media){if(to.indexOf(r.type)===-1)continue;const h=r.direction||n.direction||"sendrecv";if(h==="sendonly"||h==="inactive")l=!0;else{l=!1;break}}const a={originator:"remote",type:"offer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",a);const s=new RTCSessionDescription({type:"offer",sdp:a.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(r=>{throw t.reply(488),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',r),this.emit("peerconnection:setremotedescriptionfailed",r),r})}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&l===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&l===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(r=>{throw t.reply(500),z.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',r),r})}).catch(r=>{z.warn("_processInDialogSdpOffer() failed [error: %o]",r)}),this._connectionPromiseQueue}_receiveRefer(t){if(z.debug("receiveRefer()"),!t.refer_to){z.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==fe.SIP){z.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const n=new Hg(this,t.cseq);z.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,r)=>{l.call(this,s,r)},reject:()=>{a.call(this)}});function l(s,r={}){if(s=typeof s=="function"?s:null,this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const h=new Ru(this._ua);if(h.on("progress",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),h.on("accepted",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),h.on("_failed",({message:d,cause:_})=>{d?n.notify(d.status_code,d.reason_phrase):n.notify(487,_)}),t.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));r.extraHeaders=Ge.cloneArray(r.extraHeaders),r.extraHeaders.push(`Replaces: ${d}`)}h.connect(t.refer_to.uri.toAor(),r,s)}function a(){n.notify(603)}}_receiveNotify(t){switch(z.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let n,l;if(t.event.params&&t.event.params.id)n=t.event.params.id,l=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)l=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!l){t.reply(481,"Subscription does not exist");return}l.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){z.debug("receiveReplaces()");function n(a){if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const s=new Ru(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,a)}function l(){z.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:a=>{n.call(this,a)},reject:()=>{l.call(this)}})}_sendInitialRequest(t,n,l){const a=new $g(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(l)return l;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(t).catch(s=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,fe.causes.USER_DENIED_MEDIA_ACCESS),z.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(r=>{this._connection.addTrack(r,s)}),this._connecting(this._request),this._createLocalDescription("offer",n).catch(r=>{throw this._failed("local",null,fe.causes.WEBRTC_ERROR),r})}).then(s=>{if(this._is_canceled||this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._request.body=s,this._status=te.STATUS_INVITE_SENT,z.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(s=>{this._status!==te.STATUS_TERMINATED&&z.warn(s)})}_getDTMFRTPSender(){const t=this._connection.getSenders().find(n=>n.track&&n.track.kind==="audio");if(!(t&&t.dtmf)){z.warn("sendDTMF() | no local audio track to send DTMF with");return}return t.dtmf}_receiveInviteResponse(t){if(z.debug("receiveInviteResponse()"),this._dialog&&t.status_code>=200&&t.status_code<=299)if(this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(fe.ACK);return}else{const n=new eo(this,t,"UAC");if(n.error!==void 0){z.debug(n.error);return}this.sendRequest(fe.ACK),this.sendRequest(fe.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==te.STATUS_INVITE_SENT&&this._status!==te.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(t.status_code):this._status=te.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){z.debug("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=te.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const n={originator:"remote",type:"answer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",n);const l=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>this._progress("remote",t)).catch(a=>{z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(this._status=te.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,fe.causes.MISSING_SDP),this._failed("remote",t,fe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const n={originator:"remote",type:"answer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",n);const l=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(t,500,a.toString()),this._failed("local",t,fe.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(l).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(fe.ACK),this._confirmed("local",null)}).catch(a=>{this._acceptAndTerminate(t,488,"Not Acceptable Here"),this._failed("remote",t,fe.causes.BAD_MEDIA_DESCRIPTION),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})});break}default:{const n=Ge.sipErrorCause(t.status_code);this._failed("remote",t,n)}}}_sendReinvite(t={}){z.debug("sendReinvite()");const n=Ge.cloneArray(t.extraHeaders),l=Ge.cloneObject(t.eventHandlers),a=t.rtcOfferConstraints||this._rtcOfferConstraints||null;let s=!1;n.push(`Contact: ${this._contact}`),n.push("Content-Type: application/sdp"),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(d=>{d=this._mangleOffer(d);const _={originator:"local",type:"offer",sdp:d};z.debug('emit "sdp"'),this.emit("sdp",_),this.sendRequest(fe.INVITE,{extraHeaders:n,body:d,eventHandlers:{onSuccessResponse:g=>{r.call(this,g),s=!0},onErrorResponse:g=>{h.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{h()});function r(d){if(this._status===te.STATUS_TERMINATED||(this.sendRequest(fe.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){h.call(this);return}}else{h.call(this);return}const _={originator:"remote",type:"answer",sdp:d.body};z.debug('emit "sdp"'),this.emit("sdp",_);const g=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{l.succeeded&&l.succeeded(d)}).catch(T=>{h.call(this),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function h(d){l.failed&&l.failed(d)}}_sendUpdate(t={}){z.debug("sendUpdate()");const n=Ge.cloneArray(t.extraHeaders),l=Ge.cloneObject(t.eventHandlers),a=t.rtcOfferConstraints||this._rtcOfferConstraints||null,s=t.sdpOffer||!1;let r=!1;n.push(`Contact: ${this._contact}`),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),s?(n.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(_=>{_=this._mangleOffer(_);const g={originator:"local",type:"offer",sdp:_};z.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest(fe.UPDATE,{extraHeaders:n,body:_,eventHandlers:{onSuccessResponse:T=>{h.call(this,T),r=!0},onErrorResponse:T=>{d.call(this,T)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{d.call(this)})):this.sendRequest(fe.UPDATE,{extraHeaders:n,eventHandlers:{onSuccessResponse:_=>{h.call(this,_)},onErrorResponse:_=>{d.call(this,_)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function h(_){if(this._status!==te.STATUS_TERMINATED&&!r)if(this._handleSessionTimersInIncomingResponse(_),s){if(_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const g={originator:"remote",type:"answer",sdp:_.body};z.debug('emit "sdp"'),this.emit("sdp",g);const T=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(T)).then(()=>{l.succeeded&&l.succeeded(_)}).catch(S=>{d.call(this),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),this.emit("peerconnection:setremotedescriptionfailed",S)})}else l.succeeded&&l.succeeded(_)}function d(_){l.failed&&l.failed(_)}}_acceptAndTerminate(t,n,l){z.debug("acceptAndTerminate()");const a=[];n&&(l=l||fe.REASON_PHRASE[n]||"",a.push(`Reason: SIP ;cause=${n}; text="${l}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(fe.ACK),this.sendRequest(fe.BYE,{extraHeaders:a})),this._status=te.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=vf.parse(t),this._localHold&&!this._remoteHold){z.debug("mangleOffer() | me on hold, mangling offer");for(const n of t.media)to.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="sendonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="sendonly")}else if(this._localHold&&this._remoteHold){z.debug("mangleOffer() | both on hold, mangling offer");for(const n of t.media)to.indexOf(n.type)!==-1&&(n.direction="inactive")}else if(this._remoteHold){z.debug("mangleOffer() | remote on hold, mangling offer");for(const n of t.media)to.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="recvonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="recvonly")}return vf.write(t)}_setLocalMediaStatus(){let t=!0,n=!0;(this._localHold||this._remoteHold)&&(t=!1,n=!1),this._audioMuted&&(t=!1),this._videoMuted&&(n=!1),this._toggleMuteAudio(!t),this._toggleMuteVideo(!n)}_handleSessionTimersInIncomingRequest(t,n){if(!this._sessionTimers.enabled)return;let l;t.session_expires&&t.session_expires>=fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,l=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,l="uas"),n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${l}`),this._sessionTimers.refresher=l==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,n=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}_runSessionTimer(){const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&this._isReadyToReOffer()&&(z.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===fe.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&(z.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:fe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const n=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="audio");for(const l of n)l.track.enabled=!t}_toggleMuteVideo(t){const n=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="video");for(const l of n)l.track.enabled=!t}_newRTCSession(t,n){z.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:t,session:this,request:n})}_connecting(t){z.debug("session connecting"),z.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,n){z.debug("session progress"),z.debug('emit "progress"'),this.emit("progress",{originator:t,response:n||null})}_accepted(t,n){z.debug("session accepted"),this._start_time=new Date,z.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){z.debug("session confirmed"),this._is_confirmed=!0,z.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,l){z.debug("session ended"),this._end_time=new Date,this._close(),z.debug('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:l})}_failed(t,n,l){z.debug("session failed"),z.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:n||null,cause:l}),this._close(),z.debug('emit "failed"'),this.emit("failed",{originator:t,message:n||null,cause:l})}_onhold(t){z.debug("session onhold"),this._setLocalMediaStatus(),z.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){z.debug("session onunhold"),this._setLocalMediaStatus(),z.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:n}){z.debug("session onmute"),this._setLocalMediaStatus(),z.debug('emit "muted"'),this.emit("muted",{audio:t,video:n})}_onunmute({audio:t,video:n}){z.debug("session onunmute"),this._setLocalMediaStatus(),z.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:n})}};const Vg=Xe(Ad),jg=ft.EventEmitter,qg=ut,Wa=De,Bg=yt,ji=Ct(),Gg=Tr,Cf=Cs,Wg=ys(),so=new qg("Message");var Kg=class extends jg{constructor(t){super(),this._ua=t,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(t,n,l={}){const a=t;if(t===void 0||n===void 0)throw new TypeError("Not enough arguments");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);const s=ji.cloneArray(l.extraHeaders),r=ji.cloneObject(l.eventHandlers),h=l.contentType||"text/plain",d={};l.fromUserName&&(d.from_uri=new Wg("sip",l.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),l.fromDisplayName&&(d.from_display_name=l.fromDisplayName);for(const g in r)Object.prototype.hasOwnProperty.call(r,g)&&this.on(g,r[g]);s.push(`Content-Type: ${h}`),this._request=new Bg.OutgoingRequest(Wa.MESSAGE,t,this._ua,d,s),n&&(this._request.body=n);const _=new Gg(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:g=>{this._receiveResponse(g)}});this._newMessage("local",this._request),_.send()}init_incoming(t){this._request=t,this._newMessage("remote",t),this._is_replied||(this._is_replied=!0,t.reply(200)),this._close()}accept(t={}){const n=ji.cloneArray(t.extraHeaders),l=t.body;if(this._direction!=="incoming")throw new Cf.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,n,l)}reject(t={}){const n=t.status_code||480,l=t.reason_phrase,a=ji.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new Cf.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._is_replied=!0,this._request.reply(n,l,a,s)}_receiveResponse(t){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._succeeded("remote",t);break;default:{const n=ji.sipErrorCause(t.status_code);this._failed("remote",t,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,Wa.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,Wa.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(t,n){t==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):t==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newMessage(this,{originator:t,message:this,request:n})}_failed(t,n,l){so.debug("MESSAGE failed"),this._close(),so.debug('emit "failed"'),this.emit("failed",{originator:t,response:n||null,cause:l})}_succeeded(t,n){so.debug("MESSAGE succeeded"),this._close(),so.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:n})}};const Yg=ft.EventEmitter,Jg=ut,Ka=De,zg=yt,qi=Ct(),Xg=Tr,Af=Cs,no=new Jg("Options");var Qg=class extends Yg{constructor(t){super(),this._ua=t,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(t,n,l={}){const a=t;if(t===void 0)throw new TypeError("A target is required for OPTIONS");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);const s=qi.cloneArray(l.extraHeaders),r=qi.cloneObject(l.eventHandlers),h=l.contentType||"application/sdp";for(const _ in r)Object.prototype.hasOwnProperty.call(r,_)&&this.on(_,r[_]);s.push(`Content-Type: ${h}`),this._request=new zg.OutgoingRequest(Ka.OPTIONS,t,this._ua,null,s),n&&(this._request.body=n);const d=new Xg(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:_=>{this._receiveResponse(_)}});this._newOptions("local",this._request),d.send()}init_incoming(t){this._request=t,this._newOptions("remote",t),this._is_replied||(this._is_replied=!0,t.reply(200)),this._close()}accept(t={}){const n=qi.cloneArray(t.extraHeaders),l=t.body;if(this._direction!=="incoming")throw new Af.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,n,l)}reject(t={}){const n=t.status_code||480,l=t.reason_phrase,a=qi.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new Af.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._is_replied=!0,this._request.reply(n,l,a,s)}_receiveResponse(t){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._succeeded("remote",t);break;default:{const n=qi.sipErrorCause(t.status_code);this._failed("remote",t,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,Ka.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,Ka.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(t,n){t==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):t==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newOptions(this,{originator:t,message:this,request:n})}_failed(t,n,l){no.debug("OPTIONS failed"),this._close(),no.debug('emit "failed"'),this.emit("failed",{originator:t,response:n||null,cause:l})}_succeeded(t,n){no.debug("OPTIONS succeeded"),this._close(),no.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:n})}},Bu={};const Zg=ut,Ya=Ct(),eT=Zt(),Bi=new Zg("Socket");Bu.isSocket=c=>{if(Array.isArray(c))return!1;if(typeof c>"u")return Bi.warn("undefined JsSIP.Socket instance"),!1;try{if(!Ya.isString(c.url))throw Bi.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!Ya.isString(c.via_transport))throw Bi.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(eT.parse(c.sip_uri,"SIP_URI")===-1)throw Bi.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(t=>{if(!Ya.isFunction(c[t]))throw Bi.warn(`missing or invalid JsSIP.Socket method: ${t}`),new Error(`Missing or invalid JsSIP.Socket method: ${t}`)})}catch{return!1}return!0};const tT=ut,sT=Bu,Rf=De,xt=new tT("Transport"),qt={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:Rf.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:Rf.CONNECTION_RECOVERY_MAX_INTERVAL}};var Rd=class{constructor(t,n=qt.recovery_options){xt.debug("new()"),this.status=qt.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=n,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(l){xt.warn(`cannot use TextDecoder: ${l}`)}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(l){if(!sT.isSocket(l.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(l.weight&&!Number(l.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:l.socket,weight:l.weight||0,status:qt.SOCKET_STATUS_READY})},this),this._getSocket()}get via_transport(){return this.socket.via_transport}get url(){return this.socket.url}get sip_uri(){return this.socket.sip_uri}connect(){if(xt.debug("connect()"),this.isConnected()){xt.debug("Transport is already connected");return}else if(this.isConnecting()){xt.debug("Transport is connecting");return}this.close_requested=!1,this.status=qt.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}disconnect(){xt.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=qt.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=()=>{},this.socket.ondisconnect=()=>{},this.socket.ondata=()=>{},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}send(t){if(xt.debug("send()"),!this.isConnected())return xt.warn("unable to send message, transport is not connected"),!1;const n=t.toString();return xt.debug(`sending message:
|
|
112
|
+
`,this.transport.send(a)}}class tg extends Ed{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var Ct={OutgoingRequest:Jo,InitialOutgoingInviteRequest:qu,IncomingRequest:eg,IncomingResponse:tg};const pr=Xe(Ct),sg=ct,ms=At(),zt=new sg("DigestAuthentication");var yd=class{constructor(t){this._credentials=t,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}get(t){switch(t){case"realm":return this._realm;case"ha1":return this._ha1;default:zt.warn('get() | cannot get "%s" parameter',t);return}}authenticate({method:t,ruri:s,body:i},a,n=null){if(this._algorithm=a.algorithm,this._realm=a.realm,this._nonce=a.nonce,this._opaque=a.opaque,this._stale=a.stale,this._algorithm){if(this._algorithm!=="MD5")return zt.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return zt.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return zt.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return zt.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return zt.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(a.qop)if(a.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(a.qop.indexOf("auth")>-1)this._qop="auth";else return zt.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=t,this._uri=s,this._cnonce=n||ms.createRandomToken(12),this._nc+=1;const r=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-r.length)+r,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=ms.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._ha1=this._credentials.ha1;let h,d;return this._qop==="auth"?(h=`${this._method}:${this._uri}`,d=ms.calculateMD5(h),zt.debug('authenticate() | using qop=auth [a2:"%s"]',h),this._response=ms.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${d}`)):this._qop==="auth-int"?(h=`${this._method}:${this._uri}:${ms.calculateMD5(i||"")}`,d=ms.calculateMD5(h),zt.debug('authenticate() | using qop=auth-int [a2:"%s"]',h),this._response=ms.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${d}`)):this._qop===null&&(h=`${this._method}:${this._uri}`,d=ms.calculateMD5(h),zt.debug('authenticate() | using qop=null [a2:"%s"]',h),this._response=ms.calculateMD5(`${this._ha1}:${this._nonce}:${d}`)),zt.debug("authenticate() | response generated"),!0}toString(){const t=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return t.push(`algorithm=${this._algorithm}`),t.push(`username="${this._credentials.username}"`),t.push(`realm="${this._realm}"`),t.push(`nonce="${this._nonce}"`),t.push(`uri="${this._uri}"`),t.push(`response="${this._response}"`),this._opaque&&t.push(`opaque="${this._opaque}"`),this._qop&&(t.push(`qop=${this._qop}`),t.push(`cnonce="${this._cnonce}"`),t.push(`nc=${this._ncHex}`)),`Digest ${t.join(", ")}`}};const ng=Xe(yd),gs=500,rg=4e3,cf=5e3;var Bu={T1:gs,T2:rg,T4:cf,TIMER_B:64*gs,TIMER_D:0*gs,TIMER_F:64*gs,TIMER_H:64*gs,TIMER_I:0*gs,TIMER_J:0*gs,TIMER_K:0*cf,TIMER_L:64*gs,TIMER_M:64*gs,PROVISIONAL_RESPONSE_INTERVAL:6e4};const $i=Xe(Bu),_l=dt.EventEmitter,pl=ct,Qi=De,ff=Ct,as=Bu,df=new pl("NonInviteClientTransaction"),zl=new pl("InviteClientTransaction"),ig=new pl("AckClientTransaction"),hf=new pl("NonInviteServerTransaction"),Ql=new pl("InviteServerTransaction"),he={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"};class lg extends _l{constructor(t,s,i,a){super(),this.type=he.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=s,this.request=i,this.eventHandlers=a;let n=`SIP/2.0/${s.via_transport}`;n+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",n),this.ua.newTransaction(this)}get C(){return he}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(he.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},as.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){df.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){df.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(t){const s=t.status_code;if(s<200)switch(this.state){case he.STATUS_TRYING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break}else switch(this.state){case he.STATUS_TRYING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_COMPLETED),clearTimeout(this.F),s===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(t),this.K=setTimeout(()=>{this.timer_K()},as.TIMER_K);break;case he.STATUS_COMPLETED:break}}}class og extends _l{constructor(t,s,i,a){super(),this.type=he.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=s,this.request=i,this.eventHandlers=a,i.transaction=this;let n=`SIP/2.0/${s.via_transport}`;n+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",n),this.ua.newTransaction(this)}get C(){return he}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(he.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},as.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==he.STATUS_ACCEPTED&&(zl.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){zl.debug(`Timer M expired for transaction ${this.id}`),this.state===he.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){zl.debug(`Timer B expired for transaction ${this.id}`),this.state===he.STATUS_CALLING&&(this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){zl.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(t){const s=new ff.OutgoingRequest(Qi.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});s.setHeader("from",this.request.getHeader("from")),s.setHeader("via",this.request.getHeader("via")),s.setHeader("to",t.getHeader("to")),this.D=setTimeout(()=>{this.timer_D()},as.TIMER_D),this.transport.send(s)}cancel(t){if(this.state!==he.STATUS_PROCEEDING)return;const s=new ff.OutgoingRequest(Qi.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});s.setHeader("from",this.request.getHeader("from")),s.setHeader("via",this.request.getHeader("via")),s.setHeader("to",this.request.getHeader("to")),t&&s.setHeader("reason",t),this.transport.send(s)}receiveResponse(t){const s=t.status_code;if(s>=100&&s<=199)switch(this.state){case he.STATUS_CALLING:this.stateChanged(he.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break;case he.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(t);break}else if(s>=200&&s<=299)switch(this.state){case he.STATUS_CALLING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},as.TIMER_M),this.eventHandlers.onReceiveResponse(t);break;case he.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(t);break}else if(s>=300&&s<=699)switch(this.state){case he.STATUS_CALLING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_COMPLETED),this.sendACK(t),this.eventHandlers.onReceiveResponse(t);break;case he.STATUS_COMPLETED:this.sendACK(t);break}}}class ag extends _l{constructor(t,s,i,a){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=s,this.request=i,this.eventHandlers=a;let n=`SIP/2.0/${s.via_transport}`;n+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",n)}get C(){return he}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){ig.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class ug extends _l{constructor(t,s,i){super(),this.type=he.NON_INVITE_SERVER,this.id=i.via_branch,this.ua=t,this.transport=s,this.request=i,this.last_response="",i.server_transaction=this,this.state=he.STATUS_TRYING,t.newTransaction(this)}get C(){return he}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_J(){hf.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,hf.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(t,s,i,a){if(t===100)switch(this.state){case he.STATUS_TRYING:this.stateChanged(he.STATUS_PROCEEDING),this.transport.send(s)||this.onTransportError();break;case he.STATUS_PROCEEDING:this.last_response=s,this.transport.send(s)?i&&i():(this.onTransportError(),a&&a());break}else if(t>=200&&t<=699)switch(this.state){case he.STATUS_TRYING:case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_COMPLETED),this.last_response=s,this.J=setTimeout(()=>{this.timer_J()},as.TIMER_J),this.transport.send(s)?i&&i():(this.onTransportError(),a&&a());break;case he.STATUS_COMPLETED:break}}}class cg extends _l{constructor(t,s,i){super(),this.type=he.INVITE_SERVER,this.id=i.via_branch,this.ua=t,this.transport=s,this.request=i,this.last_response="",i.server_transaction=this,this.state=he.STATUS_PROCEEDING,t.newTransaction(this),this.resendProvisionalTimer=null,i.reply(100)}get C(){return he}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_H(){Ql.debug(`Timer H expired for transaction ${this.id}`),this.state===he.STATUS_COMPLETED&&Ql.debug("ACK not received, dialog will be terminated"),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){Ql.debug(`Timer L expired for transaction ${this.id}`),this.state===he.STATUS_ACCEPTED&&(this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,Ql.debug(`transport error occurred, deleting transaction ${this.id}`),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(he.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(t,s,i,a){if(t>=100&&t<=199)switch(this.state){case he.STATUS_PROCEEDING:this.transport.send(s)||this.onTransportError(),this.last_response=s;break}if(t>100&&t<=199&&this.state===he.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},as.PROVISIONAL_RESPONSE_INTERVAL));else if(t>=200&&t<=299)switch(this.state){case he.STATUS_PROCEEDING:this.stateChanged(he.STATUS_ACCEPTED),this.last_response=s,this.L=setTimeout(()=>{this.timer_L()},as.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case he.STATUS_ACCEPTED:this.transport.send(s)?i&&i():(this.onTransportError(),a&&a());break}else if(t>=300&&t<=699)switch(this.state){case he.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(s)?(this.stateChanged(he.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},as.TIMER_H),i&&i()):(this.onTransportError(),a&&a());break}}}function fg({_transactions:c},t){let s;switch(t.method){case Qi.INVITE:if(s=c.ist[t.via_branch],s){switch(s.state){case he.STATUS_PROCEEDING:s.transport.send(s.last_response);break;case he.STATUS_ACCEPTED:break}return!0}break;case Qi.ACK:if(s=c.ist[t.via_branch],s){if(s.state===he.STATUS_ACCEPTED)return!1;if(s.state===he.STATUS_COMPLETED)return s.state=he.STATUS_CONFIRMED,s.I=setTimeout(()=>{s.timer_I()},as.TIMER_I),!0}else return!1;break;case Qi.CANCEL:return s=c.ist[t.via_branch],s?(t.reply_sl(200),s.state!==he.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(s=c.nist[t.via_branch],s){switch(s.state){case he.STATUS_TRYING:break;case he.STATUS_PROCEEDING:case he.STATUS_COMPLETED:s.transport.send(s.last_response);break}return!0}break}}var Tr={C:he,NonInviteClientTransaction:lg,InviteClientTransaction:og,AckClientTransaction:ag,NonInviteServerTransaction:ug,InviteServerTransaction:cg,checkTransaction:fg};const Wt=Xe(Tr),dg=ct,_f=De,hg=yd,Fa=Tr,_g=new dg("RequestSender"),Va={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var vr=class{constructor(t,s,i){this._ua=t,this._eventHandlers=i,this._method=s.method,this._request=s,this._auth=null,this._challenged=!1,this._staled=!1;for(const a in Va)Object.prototype.hasOwnProperty.call(Va,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Va[a]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==_f.BYE||this._method!==_f.ACK)&&this._eventHandlers.onTransportError()}send(){const t={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:s=>{this._receiveResponse(s)}};switch(this._method){case"INVITE":this.clientTransaction=new Fa.InviteClientTransaction(this._ua,this._ua.transport,this._request,t);break;case"ACK":this.clientTransaction=new Fa.AckClientTransaction(this._ua,this._ua.transport,this._request,t);break;default:this.clientTransaction=new Fa.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,t)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}_receiveResponse(t){let s,i;const a=t.status_code;if((a===401||a===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(t.status_code===401?(s=t.parseHeader("www-authenticate"),i="authorization"):(s=t.parseHeader("proxy-authenticate"),i="proxy-authorization"),!s){_g.debug(`${t.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(t);return}if(!this._challenged||!this._staled&&s.stale===!0){if(this._auth||(this._auth=new hg({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,s)){this._eventHandlers.onReceiveResponse(t);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),s.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq",`${this._request.cseq} ${this._method}`),this._request.setHeader(i,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(t)}else this._eventHandlers.onReceiveResponse(t)}};const sl=Xe(vr),pg=ct,ja=At(),vn=De,pf=Ct,mf=vr,Hi=new pg("Registrator"),Xl=10;var mg=class{constructor(t,s){this._reg_id=1,this._ua=t,this._transport=s,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=ja.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._contact+=`;reg-id=${this._reg_id}`,this._contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s)){const i=t[s];this._extraContactParams+=`;${s}`,i&&(this._extraContactParams+=`=${i}`)}}register(){if(this._registering){Hi.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact};expires=${this._expires}${this._extraContactParams}`),t.push(`Expires: ${this._expires}`);const s=new pf.OutgoingRequest(vn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),i=new mf(this._ua,s,{onRequestTimeout:()=>{this._registrationFailure(null,vn.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,vn.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){Hi.debug("no Contact header in response to REGISTER, response ignored");break}const n=a.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=n.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=n.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){Hi.debug("no Contact header pointing to us, response ignored");break}let h=r.getParam("expires");!h&&a.hasHeader("expires")&&(h=a.getHeader("expires")),h||(h=this._expires),h=Number(h),h<Xl&&(h=Xl);const d=h>64?h*1e3/2+Math.floor((h/2-32)*1e3*Math.random()):h*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<Xl&&(this._expires=Xl),this.register()):(Hi.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,vn.causes.SIP_FAILURE_CODE));break}default:{const n=ja.sipErrorCause(a.status_code);this._registrationFailure(a,n)}}}});this._registering=!0,i.send()}unregister(t={}){if(!this._registered){Hi.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const s=this._extraHeaders.slice();t.all?s.push(`Contact: *${this._extraContactParams}`):s.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),s.push("Expires: 0");const i=new pf.OutgoingRequest(vn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},s);new mf(this._ua,i,{onRequestTimeout:()=>{this._unregistered(null,vn.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,vn.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:n=>{switch(!0){case/^1[0-9]{2}$/.test(n.status_code):break;case/^2[0-9]{2}$/.test(n.status_code):this._unregistered(n);break;default:{const r=ja.sipErrorCause(n.status_code);this._unregistered(n,r)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,s){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:s}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:s}))}_unregistered(t,s){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:s||null})}};class gg extends Error{constructor(t,s){super(),this.code=1,this.name="CONFIGURATION_ERROR",this.parameter=t,this.value=s,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}}class Tg extends Error{constructor(t){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=t,this.message=`Invalid status: ${t}`}}class vg extends Error{constructor(t){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=t}}class Sg extends Error{constructor(t){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=t}}var As={ConfigurationError:gg,InvalidStateError:Tg,NotSupportedError:vg,NotReadyError:Sg};const qs=Xe(As),qa=De,Zl=Tr,Eg=vr,Ba={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var Cd=class{constructor(t,s,i){this._dialog=t,this._ua=t._ua,this._request=s,this._eventHandlers=i,this._reattempt=!1,this._reattemptTimer=null;for(const a in Ba)Object.prototype.hasOwnProperty.call(Ba,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Ba[a]))}get request(){return this._request}send(){const t=new Eg(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:s=>{this._eventHandlers.onAuthenticated(s)},onReceiveResponse:s=>{this._receiveResponse(s)}});if(t.send(),(this._request.method===qa.INVITE||this._request.method===qa.UPDATE&&this._request.body)&&t.clientTransaction.state!==Zl.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;const s=()=>{(t.clientTransaction.state===Zl.C.STATUS_ACCEPTED||t.clientTransaction.state===Zl.C.STATUS_COMPLETED||t.clientTransaction.state===Zl.C.STATUS_TERMINATED)&&(t.clientTransaction.removeListener("stateChanged",s),this._dialog.uac_pending_reply=!1)};t.clientTransaction.on("stateChanged",s)}}_receiveResponse(t){t.status_code===408||t.status_code===481?this._eventHandlers.onDialogError(t):t.method===qa.INVITE&&t.status_code===491?this._reattempt?t.status_code>=200&&t.status_code<300?this._eventHandlers.onSuccessResponse(t):t.status_code>=300&&this._eventHandlers.onErrorResponse(t):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):t.status_code>=200&&t.status_code<300?this._eventHandlers.onSuccessResponse(t):t.status_code>=300&&this._eventHandlers.onErrorResponse(t)}};const yg=Xe(Cd),Cg=ct,gf=Ct,Hs=De,Fi=Tr,Ag=Cd,Ga=At(),Wa=new Cg("Dialog"),Fs={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var Ad=class{static get C(){return Fs}constructor(t,s,i,a=Fs.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!s.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};s instanceof gf.IncomingResponse&&(a=s.status_code<200?Fs.STATUS_EARLY:Fs.STATUS_CONFIRMED);const n=s.parseHeader("contact");i==="UAS"?(this._id={call_id:s.call_id,local_tag:s.to_tag,remote_tag:s.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=s.cseq,this._local_uri=s.parseHeader("to").uri,this._remote_uri=s.parseHeader("from").uri,this._remote_target=n.uri,this._route_set=s.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):i==="UAC"&&(this._id={call_id:s.call_id,local_tag:s.from_tag,remote_tag:s.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=s.cseq,this._local_uri=s.parseHeader("from").uri,this._remote_uri=s.parseHeader("to").uri,this._remote_target=n.uri,this._route_set=s.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),Wa.debug(`new ${i} dialog created with status ${this._state===Fs.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Fs.STATUS_TERMINATED}update(t,s){this._state=Fs.STATUS_CONFIRMED,Wa.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),s==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){Wa.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Fs.STATUS_TERMINATED}sendRequest(t,s={}){const i=Ga.cloneArray(s.extraHeaders),a=Ga.cloneObject(s.eventHandlers),n=s.body||null,r=this._createRequest(t,i,n);return a.onAuthenticated=()=>{this._local_seqnum+=1},new Ag(this,r,a).send(),r}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===Hs.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===Hs.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,s,i){s=Ga.cloneArray(s),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=t===Hs.CANCEL||t===Hs.ACK?this._local_seqnum:this._local_seqnum+=1;return new gf.OutgoingRequest(t,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},s,i)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===Hs.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===Hs.INVITE||t.method===Hs.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const s=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${s}`]),!1}else{this._uas_pending_reply=!0;const s=()=>{(t.server_transaction.state===Fi.C.STATUS_ACCEPTED||t.server_transaction.state===Fi.C.STATUS_COMPLETED||t.server_transaction.state===Fi.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",s),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",s)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Fi.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===Hs.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Fi.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}};const eo=Xe(Ad);var Gu={exports:{}};const Rg=dt.EventEmitter,Ig=ct,bg=De,wg=As,Tf=At(),Og=new Ig("RTCSession:DTMF"),Rd={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};Gu.exports=class extends Rg{constructor(t){super(),this._session=t,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(t,s={}){if(t===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new wg.InvalidStateError(this._session.status);const i=Tf.cloneArray(s.extraHeaders);if(this.eventHandlers=Tf.cloneObject(s.eventHandlers),typeof t=="string")t=t.toUpperCase();else if(typeof t=="number")t=t.toString();else throw new TypeError(`Invalid tone: ${t}`);if(t.match(/^[0-9A-DR#*]$/))this._tone=t;else throw new TypeError(`Invalid tone: ${t}`);this._duration=s.duration,i.push("Content-Type: application/dtmf-relay");let a=`Signal=${this._tone}\r
|
|
113
|
+
`;a+=`Duration=${this._duration}`,this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(bg.INFO,{extraHeaders:i,eventHandlers:{onSuccessResponse:n=>{this.emit("succeeded",{originator:"remote",response:n})},onErrorResponse:n=>{this.eventHandlers.onFailed&&this.eventHandlers.onFailed(),this.emit("failed",{originator:"remote",response:n})},onRequestTimeout:()=>{this._session.onRequestTimeout()},onTransportError:()=>{this._session.onTransportError()},onDialogError:()=>{this._session.onDialogError()}},body:a})}init_incoming(t){const s=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,i=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;if(this._direction="incoming",this._request=t,t.reply(200),t.body){const a=t.body.split(`
|
|
114
|
+
`);a.length>=1&&s.test(a[0])&&(this._tone=a[0].replace(s,"$2")),a.length>=2&&i.test(a[1])&&(this._duration=parseInt(a[1].replace(i,"$2"),10))}this._duration||(this._duration=Rd.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:t}):Og.debug("invalid INFO DTMF received, discarded")}};Gu.exports.C=Rd;var Id=Gu.exports;const Dg=Xe(Id),Ng=dt.EventEmitter,xg=De,Ug=As,kg=At();var bd=class extends Ng{constructor(t){super(),this._session=t,this._direction=null,this._contentType=null,this._body=null}get contentType(){return this._contentType}get body(){return this._body}send(t,s,i={}){if(this._direction="outgoing",t===void 0)throw new TypeError("Not enough arguments");if(this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new Ug.InvalidStateError(this._session.status);this._contentType=t,this._body=s;const a=kg.cloneArray(i.extraHeaders);a.push(`Content-Type: ${t}`),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(xg.INFO,{extraHeaders:a,eventHandlers:{onSuccessResponse:n=>{this.emit("succeeded",{originator:"remote",response:n})},onErrorResponse:n=>{this.emit("failed",{originator:"remote",response:n})},onTransportError:()=>{this._session.onTransportError()},onRequestTimeout:()=>{this._session.onRequestTimeout()},onDialogError:()=>{this._session.onDialogError()}},body:s})}init_incoming(t){this._direction="incoming",this.request=t,t.reply(200),this._contentType=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,this._body=t.body,this._session.newInfo({originator:"remote",info:this,request:t})}};const Iu=Xe(bd),Mg=ct,vf=De,Pg=new Mg("RTCSession:ReferNotifier"),Ka={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300};var wd=class{constructor(t,s,i){this._session=t,this._id=s,this._expires=i||Ka.expires,this._active=!0,this.notify(100)}notify(t,s){if(Pg.debug("notify()"),this._active===!1)return;s=s||vf.REASON_PHRASE[t]||"";let i;t>=200?i="terminated;reason=noresource":i=`active;expires=${this._expires}`,this._session.sendRequest(vf.NOTIFY,{extraHeaders:[`Event: ${Ka.event_type};id=${this._id}`,`Subscription-State: ${i}`,`Content-Type: ${Ka.body_type}`],body:`SIP/2.0 ${t} ${s}`,eventHandlers:{onErrorResponse(){this._active=!1}}})}};const Lg=Xe(wd),$g=dt.EventEmitter,Hg=ct,Vi=De,Fg=es(),Sf=At(),Sn=new Hg("RTCSession:ReferSubscriber");var Od=class extends $g{constructor(t){super(),this._id=null,this._session=t}get id(){return this._id}sendRefer(t,s={}){Sn.debug("sendRefer()");const i=Sf.cloneArray(s.extraHeaders),a=Sf.cloneObject(s.eventHandlers);for(const d in a)Object.prototype.hasOwnProperty.call(a,d)&&this.on(d,a[d]);let n=null;s.replaces&&(n=s.replaces._request.call_id,n+=`;to-tag=${s.replaces._to_tag}`,n+=`;from-tag=${s.replaces._from_tag}`,n=encodeURIComponent(n));const r=`Refer-To: <${t}${n?`?Replaces=${n}`:""}>`;if(i.push(r),!i.some(d=>d.toLowerCase().startsWith("referred-by:"))){const d=`Referred-By: <${this._session._ua._configuration.uri._scheme}:${this._session._ua._configuration.uri._user}@${this._session._ua._configuration.uri._host}>`;i.push(d)}i.push(`Contact: ${this._session.contact}`);const h=this._session.sendRequest(Vi.REFER,{extraHeaders:i,eventHandlers:{onSuccessResponse:d=>{this._requestSucceeded(d)},onErrorResponse:d=>{this._requestFailed(d,Vi.causes.REJECTED)},onTransportError:()=>{this._requestFailed(null,Vi.causes.CONNECTION_ERROR)},onRequestTimeout:()=>{this._requestFailed(null,Vi.causes.REQUEST_TIMEOUT)},onDialogError:()=>{this._requestFailed(null,Vi.causes.DIALOG_ERROR)}}});this._id=h.cseq}receiveNotify(t){if(Sn.debug("receiveNotify()"),!t.body)return;const s=Fg.parse(t.body.trim().split(`\r
|
|
115
|
+
`,1)[0],"Status_Line");if(s===-1){Sn.debug(`receiveNotify() | error parsing NOTIFY body: "${t.body}"`);return}switch(!0){case/^100$/.test(s.status_code):this.emit("trying",{request:t,status_line:s});break;case/^1[0-9]{2}$/.test(s.status_code):this.emit("progress",{request:t,status_line:s});break;case/^2[0-9]{2}$/.test(s.status_code):this.emit("accepted",{request:t,status_line:s});break;default:this.emit("failed",{request:t,status_line:s});break}}_requestSucceeded(t){Sn.debug("REFER succeeded"),Sn.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:t})}_requestFailed(t,s){Sn.debug("REFER failed"),Sn.debug('emit "requestFailed"'),this.emit("requestFailed",{response:t||null,cause:s})}};const Vg=Xe(Od),jg=dt.EventEmitter,Ef=Mt,qg=ct,fe=De,En=As,yf=Tr,We=At(),ji=Bu,Bg=Ct,to=Ad,Gg=vr,Lt=Id,Cf=bd,Wg=wd,Kg=Od,Af=Cs(),z=new qg("RTCSession"),te={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},so=["audio","video"];var Dd=class bu extends jg{static get C(){return te}constructor(t){z.debug("new"),super(),this._id=null,this._ua=t,this._status=te.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._tones=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:fe.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return te}get causes(){return fe.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:case te.STATUS_INVITE_RECEIVED:case te.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case te.STATUS_ANSWERED:case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case te.STATUS_CANCELED:case te.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(t,s={},i){z.debug("connect()");const a=t,n=We.cloneObject(s.eventHandlers),r=We.cloneArray(s.extraHeaders),h=We.cloneObject(s.mediaConstraints,{audio:!0,video:!0}),d=s.mediaStream||null,_=We.cloneObject(s.pcConfig,{iceServers:[]}),g=s.rtcConstraints||null,T=s.rtcOfferConstraints||null;if(this._rtcOfferConstraints=T,this._rtcAnswerConstraints=s.rtcAnswerConstraints||null,this._data=s.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==te.STATUS_NULL)throw new En.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new En.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);this._sessionTimers.enabled&&We.isDecimal(s.sessionTimersExpires)&&(s.sessionTimersExpires>=fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=s.sessionTimersExpires:this._sessionTimers.defaultExpires=fe.SESSION_EXPIRES);for(const C in n)Object.prototype.hasOwnProperty.call(n,C)&&this.on(C,n[C]);this._from_tag=We.newTag();const S=s.anonymous||!1,E={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:S,outbound:!0}),S?(E.from_display_name="Anonymous",E.from_uri=new Af("sip","anonymous","anonymous.invalid"),r.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),r.push("Privacy: id")):s.fromUserName&&(E.from_uri=new Af("sip",s.fromUserName,this._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),s.fromDisplayName&&(E.from_display_name=s.fromDisplayName),r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&r.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Bg.InitialOutgoingInviteRequest(t,this._ua,E,r),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(_,g),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,i&&i(this),this._newRTCSession("local",this._request),this._sendInitialRequest(h,T,d)}init_incoming(t,s){z.debug("init_incoming()");let i;const a=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&a!=="application/sdp"){t.reply(415);return}if(this._status=te.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(i=t.getHeader("expires")*1e3),t.to_tag=We.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=te.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,fe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),i&&(this._timers.expiresTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,fe.causes.EXPIRES))},i)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,s&&s(this),this._newRTCSession("remote",t),this._status!==te.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){z.debug("answer()");const s=this._request,i=We.cloneArray(t.extraHeaders),a=We.cloneObject(t.mediaConstraints),n=t.mediaStream||null,r=We.cloneObject(t.pcConfig,{iceServers:[]}),h=t.rtcConstraints||null,d=t.rtcAnswerConstraints||null,_=We.cloneObject(t.rtcOfferConstraints);let g,T=!1,S=!1,E=!1,C=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new En.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==te.STATUS_WAITING_FOR_ANSWER)throw new En.InvalidStateError(this._status);if(this._sessionTimers.enabled&&We.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=fe.SESSION_EXPIRES),this._status=te.STATUS_ANSWERED,!this._createDialog(s,"UAS")){s.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),i.unshift(`Contact: ${this._contact}`);const A=s.parseSDP();Array.isArray(A.media)||(A.media=[A.media]);for(const R of A.media)R.type==="audio"&&(T=!0,(!R.direction||R.direction==="sendrecv")&&(E=!0)),R.type==="video"&&(S=!0,(!R.direction||R.direction==="sendrecv")&&(C=!0));if(n&&a.audio===!1){g=n.getAudioTracks();for(const R of g)n.removeTrack(R)}if(n&&a.video===!1){g=n.getVideoTracks();for(const R of g)n.removeTrack(R)}!n&&a.audio===void 0&&(a.audio=E),!n&&a.video===void 0&&(a.video=C),!n&&!T&&!_.offerToReceiveAudio&&(a.audio=!1),!n&&!S&&!_.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(r,h),Promise.resolve().then(()=>{if(n)return n;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(R=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(s.reply(480),this._failed("local",null,fe.causes.USER_DENIED_MEDIA_ACCESS),z.warn('emit "getusermediafailed" [error:%o]',R),this.emit("getusermediafailed",R),new Error("getUserMedia() failed"))})}).then(R=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=R,R&&R.getTracks().forEach(F=>{this._connection.addTrack(F,R)})}).then(()=>{if(this._late_sdp)return;const R={originator:"remote",type:"offer",sdp:s.body};z.debug('emit "sdp"'),this.emit("sdp",R);const F=new RTCSessionDescription({type:"offer",sdp:R.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(F)).catch(I=>{throw s.reply(488),this._failed("system",null,fe.causes.WEBRTC_ERROR),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',I),this.emit("peerconnection:setremotedescriptionfailed",I),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(s),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw s.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",d).catch(()=>{throw s.reply(500),new Error("_createLocalDescription() failed")})}).then(R=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(s,i),s.reply(200,null,i,R,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(s,R),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,fe.causes.CONNECTION_ERROR)})}).catch(R=>{this._status!==te.STATUS_TERMINATED&&z.warn(R)})}terminate(t={}){z.debug("terminate()");const s=t.cause||fe.causes.BYE,i=We.cloneArray(t.extraHeaders),a=t.body;let n,r=t.status_code,h=t.reason_phrase;if(this._status===te.STATUS_TERMINATED)throw new En.InvalidStateError(this._status);switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:if(z.debug("canceling session"),r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(h=h||fe.REASON_PHRASE[r]||"",n=`SIP ;cause=${r} ;text="${h}"`),this._status===te.STATUS_NULL||this._status===te.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=n):this._status===te.STATUS_1XX_RECEIVED&&this._request.cancel(n),this._status=te.STATUS_CANCELED,this._failed("local",null,fe.causes.CANCELED);break;case te.STATUS_WAITING_FOR_ANSWER:case te.STATUS_ANSWERED:if(z.debug("rejecting session"),r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,h,i,a),this._failed("local",null,fe.causes.REJECTED);break;case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:if(z.debug("terminating session"),h=t.reason_phrase||fe.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&i.push(`Reason: SIP ;cause=${r}; text="${h}"`),this._status===te.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==yf.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:_})=>{_===fe.ACK&&(this.sendRequest(fe.BYE,{extraHeaders:i,body:a}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===yf.C.STATUS_TERMINATED&&(this.sendRequest(fe.BYE,{extraHeaders:i,body:a}),d.terminate())}),this._ended("local",null,s),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(fe.BYE,{extraHeaders:i,body:a}),this._ended("local",null,s)}}sendDTMF(t,s={}){z.debug("sendDTMF() | tones: %s",t);let i=0,a=s.duration||null,n=s.interToneGap||null;const r=s.transportType||fe.DTMF_TRANSPORT.INFO;if(t===void 0)throw new TypeError("Not enough arguments");if(this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new En.InvalidStateError(this._status);if(r!==fe.DTMF_TRANSPORT.INFO&&r!==fe.DTMF_TRANSPORT.RFC2833)throw new TypeError(`invalid transportType: ${r}`);if(typeof t=="number"&&(t=t.toString()),!t||typeof t!="string"||!t.match(/^[0-9A-DR#*,]+$/i))throw new TypeError(`Invalid tones: ${t}`);if(a&&!We.isDecimal(a))throw new TypeError(`Invalid tone duration: ${a}`);if(a?a<Lt.C.MIN_DURATION?(z.debug(`"duration" value is lower than the minimum allowed, setting it to ${Lt.C.MIN_DURATION} milliseconds`),a=Lt.C.MIN_DURATION):a>Lt.C.MAX_DURATION?(z.debug(`"duration" value is greater than the maximum allowed, setting it to ${Lt.C.MAX_DURATION} milliseconds`),a=Lt.C.MAX_DURATION):a=Math.abs(a):a=Lt.C.DEFAULT_DURATION,s.duration=a,n&&!We.isDecimal(n))throw new TypeError(`Invalid interToneGap: ${n}`);if(n?n<Lt.C.MIN_INTER_TONE_GAP?(z.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${Lt.C.MIN_INTER_TONE_GAP} milliseconds`),n=Lt.C.MIN_INTER_TONE_GAP):n=Math.abs(n):n=Lt.C.DEFAULT_INTER_TONE_GAP,r===fe.DTMF_TRANSPORT.RFC2833){const d=this._getDTMFRTPSender();d&&(t=d.toneBuffer+t,d.insertDTMF(t,a,n));return}if(this._tones){this._tones+=t;return}this._tones=t,h.call(this);function h(){let d;if(this._status===te.STATUS_TERMINATED||!this._tones||i>=this._tones.length){this._tones=null;return}const _=this._tones[i];if(i+=1,_===",")d=2e3;else{const g=new Lt(this);s.eventHandlers={onFailed:()=>{this._tones=null}},g.send(_,s),d=a+n}setTimeout(h.bind(this),d)}}sendInfo(t,s,i={}){if(z.debug("sendInfo()"),this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new En.InvalidStateError(this._status);new Cf(this).send(t,s,i)}mute(t={audio:!0,video:!1}){z.debug("mute()");let s=!1,i=!1;this._audioMuted===!1&&t.audio&&(s=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(i=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(s===!0||i===!0)&&this._onmute({audio:s,video:i})}unmute(t={audio:!0,video:!0}){z.debug("unmute()");let s=!1,i=!1;this._audioMuted===!0&&t.audio&&(s=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(i=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(s===!0||i===!0)&&this._onunmute({audio:s,video:i})}hold(t={},s){if(z.debug("hold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const i={succeeded:()=>{s&&s()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:i,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:i,extraHeaders:t.extraHeaders}),!0}unhold(t={},s){if(z.debug("unhold()"),this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const i={succeeded:()=>{s&&s()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:i,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:i,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},s){z.debug("renegotiate()");const i=t.rtcOfferConstraints||null;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const a={succeeded:()=>{s&&s()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:i,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:i,extraHeaders:t.extraHeaders}),!0}refer(t,s){z.debug("refer()");const i=t;if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${i}`);const a=new Kg(this);a.sendRefer(t,s);const n=a.id;return this._referSubscribers[n]=a,a.on("requestFailed",()=>{delete this._referSubscribers[n]}),a.on("accepted",()=>{delete this._referSubscribers[n]}),a.on("failed",()=>{delete this._referSubscribers[n]}),a}sendRequest(t,s){return z.debug("sendRequest()"),this._dialog.sendRequest(t,s)}receiveRequest(t){if(z.debug("receiveRequest()"),t.method===fe.CANCEL)(this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED)&&(this._status=te.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,fe.causes.CANCELED));else switch(t.method){case fe.ACK:if(this._status!==te.STATUS_WAITING_FOR_ACK)return;if(this._status=te.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:fe.causes.MISSING_SDP,status_code:400});break}const s={originator:"remote",type:"answer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",s);const i=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(a=>{this.terminate({cause:fe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",t);break;case fe.BYE:this._status===te.STATUS_CONFIRMED||this._status===te.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,fe.causes.BYE)):this._status===te.STATUS_INVITE_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,fe.causes.BYE)):t.reply(403,"Wrong Status");break;case fe.INVITE:this._status===te.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case fe.INFO:if(this._status===te.STATUS_1XX_RECEIVED||this._status===te.STATUS_WAITING_FOR_ANSWER||this._status===te.STATUS_ANSWERED||this._status===te.STATUS_WAITING_FOR_ACK||this._status===te.STATUS_CONFIRMED){const s=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;s&&s.match(/^application\/dtmf-relay/i)?new Lt(this).init_incoming(t):s!==void 0?new Cf(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case fe.UPDATE:this._status===te.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case fe.REFER:this._status===te.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case fe.NOTIFY:this._status===te.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){z.warn("onTransportError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.CONNECTION_ERROR,cause:fe.causes.CONNECTION_ERROR})}onRequestTimeout(){z.warn("onRequestTimeout()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:fe.causes.REQUEST_TIMEOUT,cause:fe.causes.REQUEST_TIMEOUT})}onDialogError(){z.warn("onDialogError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.DIALOG_ERROR,cause:fe.causes.DIALOG_ERROR})}newDTMF(t){z.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){z.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(z.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(z.debug("_isReadyToReOffer() | session not established yet"),!1):(z.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(z.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(z.debug("close() | closing local MediaStream"),We.closeMediaStream(this._localMediaStream)),this._status!==te.STATUS_TERMINATED){if(this._status=te.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){z.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,s){let i=ji.T1;function a(){this._status===te.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],s),i<ji.T2&&(i=i*2,i>ji.T2&&(i=ji.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),i))}this._timers.invite2xxTimer=setTimeout(a.bind(this),i)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ACK&&(z.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(fe.BYE),this._ended("remote",null,fe.causes.NO_ACK))},ji.TIMER_H)}_createRTCConnection(t,s){this._connection=new RTCPeerConnection(t,s),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:fe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:fe.causes.RTP_TIMEOUT})}),z.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,s){if(z.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const i=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?i.createOffer(s).catch(a=>(z.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):i.createAnswer(s).catch(a=>(z.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>i.setLocalDescription(a).catch(n=>(this._rtcReady=!0,z.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',n),this.emit("peerconnection:setlocaldescriptionfailed",n),Promise.reject(n)))).then(()=>{const a=s&&s.iceRestart;if(i.iceGatheringState==="complete"&&!a||i.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const n={originator:"local",type:t,sdp:i.localDescription.sdp};return z.debug('emit "sdp"'),this.emit("sdp",n),Promise.resolve(n.sdp)}return new Promise(n=>{let r=!1,h,d;this._iceReady=!1;const _=()=>{i.removeEventListener("icecandidate",h),i.removeEventListener("icegatheringstatechange",d),r=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:t,sdp:i.localDescription.sdp};z.debug('emit "sdp"'),this.emit("sdp",g),n(g.sdp)};i.addEventListener("icecandidate",h=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:_}):r||_()}),i.addEventListener("icegatheringstatechange",d=()=>{i.iceGatheringState==="complete"&&!r&&_()})})})}_createDialog(t,s,i){const a=s==="UAS"?t.to_tag:t.from_tag,n=s==="UAS"?t.from_tag:t.to_tag,r=t.call_id+a+n;let h=this._earlyDialogs[r];if(i)return h?!0:(h=new to(this,t,s,to.C.STATUS_EARLY),h.error?(z.debug(h.error),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=h,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,h)return h.update(t,s),this._dialog=h,delete this._earlyDialogs[r],!0;const d=new to(this,t,s);return d.error?(z.debug(d.error),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(t){z.debug("receiveReinvite()");const s=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,i={request:t,callback:void 0,reject:n.bind(this)};let a=!1;function n(h={}){a=!0;const d=h.status_code||403,_=h.reason_phrase||"",g=We.cloneArray(h.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,_,g)}if(this.emit("reinvite",i),a)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(h=>{r.call(this,h)}).catch(()=>{t.reply(500)});return}if(s!=="application/sdp"){z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(h=>{this._status!==te.STATUS_TERMINATED&&r.call(this,h)}).catch(h=>{z.warn(h)});function r(h){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),this._late_sdp&&(h=this._mangleOffer(h)),t.reply(200,null,d,h,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,h),this._setACKTimer()}),typeof i.callback=="function"&&i.callback()}}_receiveUpdate(t){z.debug("receiveUpdate()");const s=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,i={request:t,callback:void 0,reject:n.bind(this)};let a=!1;function n(h={}){a=!0;const d=h.status_code||403,_=h.reason_phrase||"",g=We.cloneArray(h.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,_,g)}if(this.emit("update",i),a)return;if(!t.body){r.call(this,null);return}if(s!=="application/sdp"){z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(h=>{this._status!==te.STATUS_TERMINATED&&r.call(this,h)}).catch(h=>{z.warn(h)});function r(h){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),t.reply(200,null,d,h),typeof i.callback=="function"&&i.callback()}}_processInDialogSdpOffer(t){z.debug("_processInDialogSdpOffer()");const s=t.parseSDP();let i=!1;for(const r of s.media){if(so.indexOf(r.type)===-1)continue;const h=r.direction||s.direction||"sendrecv";if(h==="sendonly"||h==="inactive")i=!0;else{i=!1;break}}const a={originator:"remote",type:"offer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",a);const n=new RTCSessionDescription({type:"offer",sdp:a.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(n).catch(r=>{throw t.reply(488),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',r),this.emit("peerconnection:setremotedescriptionfailed",r),r})}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&i===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&i===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(r=>{throw t.reply(500),z.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',r),r})}).catch(r=>{z.warn("_processInDialogSdpOffer() failed [error: %o]",r)}),this._connectionPromiseQueue}_receiveRefer(t){if(z.debug("receiveRefer()"),!t.refer_to){z.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==fe.SIP){z.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const s=new Wg(this,t.cseq);z.debug('emit "refer"'),this.emit("refer",{request:t,accept:(n,r)=>{i.call(this,n,r)},reject:()=>{a.call(this)}});function i(n,r={}){if(n=typeof n=="function"?n:null,this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const h=new bu(this._ua);if(h.on("progress",({response:d})=>{s.notify(d.status_code,d.reason_phrase)}),h.on("accepted",({response:d})=>{s.notify(d.status_code,d.reason_phrase)}),h.on("_failed",({message:d,cause:_})=>{d?s.notify(d.status_code,d.reason_phrase):s.notify(487,_)}),t.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));r.extraHeaders=We.cloneArray(r.extraHeaders),r.extraHeaders.push(`Replaces: ${d}`)}h.connect(t.refer_to.uri.toAor(),r,n)}function a(){s.notify(603)}}_receiveNotify(t){switch(z.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let s,i;if(t.event.params&&t.event.params.id)s=t.event.params.id,i=this._referSubscribers[s];else if(Object.keys(this._referSubscribers).length===1)i=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!i){t.reply(481,"Subscription does not exist");return}i.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){z.debug("receiveReplaces()");function s(a){if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const n=new bu(this._ua);n.on("confirmed",()=>{this.terminate()}),n.init_incoming(t,a)}function i(){z.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:a=>{s.call(this,a)},reject:()=>{i.call(this)}})}_sendInitialRequest(t,s,i){const a=new Gg(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:n=>{this._request=n},onReceiveResponse:n=>{this._receiveInviteResponse(n)}});Promise.resolve().then(()=>{if(i)return i;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(t).catch(n=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,fe.causes.USER_DENIED_MEDIA_ACCESS),z.warn('emit "getusermediafailed" [error:%o]',n),this.emit("getusermediafailed",n),n)})}).then(n=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=n,n&&n.getTracks().forEach(r=>{this._connection.addTrack(r,n)}),this._connecting(this._request),this._createLocalDescription("offer",s).catch(r=>{throw this._failed("local",null,fe.causes.WEBRTC_ERROR),r})}).then(n=>{if(this._is_canceled||this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._request.body=n,this._status=te.STATUS_INVITE_SENT,z.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(n=>{this._status!==te.STATUS_TERMINATED&&z.warn(n)})}_getDTMFRTPSender(){const t=this._connection.getSenders().find(s=>s.track&&s.track.kind==="audio");if(!(t&&t.dtmf)){z.warn("sendDTMF() | no local audio track to send DTMF with");return}return t.dtmf}_receiveInviteResponse(t){if(z.debug("receiveInviteResponse()"),this._dialog&&t.status_code>=200&&t.status_code<=299)if(this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(fe.ACK);return}else{const s=new to(this,t,"UAC");if(s.error!==void 0){z.debug(s.error);return}this.sendRequest(fe.ACK),this.sendRequest(fe.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==te.STATUS_INVITE_SENT&&this._status!==te.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(t.status_code):this._status=te.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){z.debug("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=te.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const s={originator:"remote",type:"answer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",s);const i=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).then(()=>this._progress("remote",t)).catch(a=>{z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(this._status=te.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,fe.causes.MISSING_SDP),this._failed("remote",t,fe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const s={originator:"remote",type:"answer",sdp:t.body};z.debug('emit "sdp"'),this.emit("sdp",s);const i=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(a=>this._connection.setLocalDescription(a)).catch(a=>{this._acceptAndTerminate(t,500,a.toString()),this._failed("local",t,fe.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(i).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(fe.ACK),this._confirmed("local",null)}).catch(a=>{this._acceptAndTerminate(t,488,"Not Acceptable Here"),this._failed("remote",t,fe.causes.BAD_MEDIA_DESCRIPTION),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})});break}default:{const s=We.sipErrorCause(t.status_code);this._failed("remote",t,s)}}}_sendReinvite(t={}){z.debug("sendReinvite()");const s=We.cloneArray(t.extraHeaders),i=We.cloneObject(t.eventHandlers),a=t.rtcOfferConstraints||this._rtcOfferConstraints||null;let n=!1;s.push(`Contact: ${this._contact}`),s.push("Content-Type: application/sdp"),this._sessionTimers.running&&s.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(d=>{d=this._mangleOffer(d);const _={originator:"local",type:"offer",sdp:d};z.debug('emit "sdp"'),this.emit("sdp",_),this.sendRequest(fe.INVITE,{extraHeaders:s,body:d,eventHandlers:{onSuccessResponse:g=>{r.call(this,g),n=!0},onErrorResponse:g=>{h.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{h()});function r(d){if(this._status===te.STATUS_TERMINATED||(this.sendRequest(fe.ACK),n))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){h.call(this);return}}else{h.call(this);return}const _={originator:"remote",type:"answer",sdp:d.body};z.debug('emit "sdp"'),this.emit("sdp",_);const g=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{i.succeeded&&i.succeeded(d)}).catch(T=>{h.call(this),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function h(d){i.failed&&i.failed(d)}}_sendUpdate(t={}){z.debug("sendUpdate()");const s=We.cloneArray(t.extraHeaders),i=We.cloneObject(t.eventHandlers),a=t.rtcOfferConstraints||this._rtcOfferConstraints||null,n=t.sdpOffer||!1;let r=!1;s.push(`Contact: ${this._contact}`),this._sessionTimers.running&&s.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),n?(s.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(_=>{_=this._mangleOffer(_);const g={originator:"local",type:"offer",sdp:_};z.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest(fe.UPDATE,{extraHeaders:s,body:_,eventHandlers:{onSuccessResponse:T=>{h.call(this,T),r=!0},onErrorResponse:T=>{d.call(this,T)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{d.call(this)})):this.sendRequest(fe.UPDATE,{extraHeaders:s,eventHandlers:{onSuccessResponse:_=>{h.call(this,_)},onErrorResponse:_=>{d.call(this,_)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function h(_){if(this._status!==te.STATUS_TERMINATED&&!r)if(this._handleSessionTimersInIncomingResponse(_),n){if(_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const g={originator:"remote",type:"answer",sdp:_.body};z.debug('emit "sdp"'),this.emit("sdp",g);const T=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(T)).then(()=>{i.succeeded&&i.succeeded(_)}).catch(S=>{d.call(this),z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),this.emit("peerconnection:setremotedescriptionfailed",S)})}else i.succeeded&&i.succeeded(_)}function d(_){i.failed&&i.failed(_)}}_acceptAndTerminate(t,s,i){z.debug("acceptAndTerminate()");const a=[];s&&(i=i||fe.REASON_PHRASE[s]||"",a.push(`Reason: SIP ;cause=${s}; text="${i}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(fe.ACK),this.sendRequest(fe.BYE,{extraHeaders:a})),this._status=te.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=Ef.parse(t),this._localHold&&!this._remoteHold){z.debug("mangleOffer() | me on hold, mangling offer");for(const s of t.media)so.indexOf(s.type)!==-1&&(s.direction?s.direction==="sendrecv"?s.direction="sendonly":s.direction==="recvonly"&&(s.direction="inactive"):s.direction="sendonly")}else if(this._localHold&&this._remoteHold){z.debug("mangleOffer() | both on hold, mangling offer");for(const s of t.media)so.indexOf(s.type)!==-1&&(s.direction="inactive")}else if(this._remoteHold){z.debug("mangleOffer() | remote on hold, mangling offer");for(const s of t.media)so.indexOf(s.type)!==-1&&(s.direction?s.direction==="sendrecv"?s.direction="recvonly":s.direction==="recvonly"&&(s.direction="inactive"):s.direction="recvonly")}return Ef.write(t)}_setLocalMediaStatus(){let t=!0,s=!0;(this._localHold||this._remoteHold)&&(t=!1,s=!1),this._audioMuted&&(t=!1),this._videoMuted&&(s=!1),this._toggleMuteAudio(!t),this._toggleMuteVideo(!s)}_handleSessionTimersInIncomingRequest(t,s){if(!this._sessionTimers.enabled)return;let i;t.session_expires&&t.session_expires>=fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,i=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,i="uas"),s.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${i}`),this._sessionTimers.refresher=i==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let s;t.session_expires&&t.session_expires>=fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,s=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,s="uac"),this._sessionTimers.refresher=s==="uac",this._runSessionTimer()}_runSessionTimer(){const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&this._isReadyToReOffer()&&(z.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===fe.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&(z.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:fe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const s=this._connection.getSenders().filter(i=>i.track&&i.track.kind==="audio");for(const i of s)i.track.enabled=!t}_toggleMuteVideo(t){const s=this._connection.getSenders().filter(i=>i.track&&i.track.kind==="video");for(const i of s)i.track.enabled=!t}_newRTCSession(t,s){z.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:t,session:this,request:s})}_connecting(t){z.debug("session connecting"),z.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,s){z.debug("session progress"),z.debug('emit "progress"'),this.emit("progress",{originator:t,response:s||null})}_accepted(t,s){z.debug("session accepted"),this._start_time=new Date,z.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:s||null})}_confirmed(t,s){z.debug("session confirmed"),this._is_confirmed=!0,z.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:s||null})}_ended(t,s,i){z.debug("session ended"),this._end_time=new Date,this._close(),z.debug('emit "ended"'),this.emit("ended",{originator:t,message:s||null,cause:i})}_failed(t,s,i){z.debug("session failed"),z.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:s||null,cause:i}),this._close(),z.debug('emit "failed"'),this.emit("failed",{originator:t,message:s||null,cause:i})}_onhold(t){z.debug("session onhold"),this._setLocalMediaStatus(),z.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){z.debug("session onunhold"),this._setLocalMediaStatus(),z.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:s}){z.debug("session onmute"),this._setLocalMediaStatus(),z.debug('emit "muted"'),this.emit("muted",{audio:t,video:s})}_onunmute({audio:t,video:s}){z.debug("session onunmute"),this._setLocalMediaStatus(),z.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:s})}};const Yg=Xe(Dd),Jg=dt.EventEmitter,zg=ct,Ya=De,Qg=Ct,qi=At(),Xg=vr,Rf=As,Zg=Cs(),no=new zg("Message");var eT=class extends Jg{constructor(t){super(),this._ua=t,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(t,s,i={}){const a=t;if(t===void 0||s===void 0)throw new TypeError("Not enough arguments");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);const n=qi.cloneArray(i.extraHeaders),r=qi.cloneObject(i.eventHandlers),h=i.contentType||"text/plain",d={};i.fromUserName&&(d.from_uri=new Zg("sip",i.fromUserName,this._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),i.fromDisplayName&&(d.from_display_name=i.fromDisplayName);for(const g in r)Object.prototype.hasOwnProperty.call(r,g)&&this.on(g,r[g]);n.push(`Content-Type: ${h}`),this._request=new Qg.OutgoingRequest(Ya.MESSAGE,t,this._ua,d,n),s&&(this._request.body=s);const _=new Xg(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:g=>{this._receiveResponse(g)}});this._newMessage("local",this._request),_.send()}init_incoming(t){this._request=t,this._newMessage("remote",t),this._is_replied||(this._is_replied=!0,t.reply(200)),this._close()}accept(t={}){const s=qi.cloneArray(t.extraHeaders),i=t.body;if(this._direction!=="incoming")throw new Rf.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,s,i)}reject(t={}){const s=t.status_code||480,i=t.reason_phrase,a=qi.cloneArray(t.extraHeaders),n=t.body;if(this._direction!=="incoming")throw new Rf.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._is_replied=!0,this._request.reply(s,i,a,n)}_receiveResponse(t){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._succeeded("remote",t);break;default:{const s=qi.sipErrorCause(t.status_code);this._failed("remote",t,s);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,Ya.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,Ya.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(t,s){t==="remote"?(this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from):t==="local"&&(this._direction="outgoing",this._local_identity=s.from,this._remote_identity=s.to),this._ua.newMessage(this,{originator:t,message:this,request:s})}_failed(t,s,i){no.debug("MESSAGE failed"),this._close(),no.debug('emit "failed"'),this.emit("failed",{originator:t,response:s||null,cause:i})}_succeeded(t,s){no.debug("MESSAGE succeeded"),this._close(),no.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:s})}};const tT=dt.EventEmitter,sT=ct,Ja=De,nT=Ct,Bi=At(),rT=vr,If=As,ro=new sT("Options");var iT=class extends tT{constructor(t){super(),this._ua=t,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(t,s,i={}){const a=t;if(t===void 0)throw new TypeError("A target is required for OPTIONS");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);const n=Bi.cloneArray(i.extraHeaders),r=Bi.cloneObject(i.eventHandlers),h=i.contentType||"application/sdp";for(const _ in r)Object.prototype.hasOwnProperty.call(r,_)&&this.on(_,r[_]);n.push(`Content-Type: ${h}`),this._request=new nT.OutgoingRequest(Ja.OPTIONS,t,this._ua,null,n),s&&(this._request.body=s);const d=new rT(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:_=>{this._receiveResponse(_)}});this._newOptions("local",this._request),d.send()}init_incoming(t){this._request=t,this._newOptions("remote",t),this._is_replied||(this._is_replied=!0,t.reply(200)),this._close()}accept(t={}){const s=Bi.cloneArray(t.extraHeaders),i=t.body;if(this._direction!=="incoming")throw new If.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,s,i)}reject(t={}){const s=t.status_code||480,i=t.reason_phrase,a=Bi.cloneArray(t.extraHeaders),n=t.body;if(this._direction!=="incoming")throw new If.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(s<300||s>=700)throw new TypeError(`Invalid status_code: ${s}`);this._is_replied=!0,this._request.reply(s,i,a,n)}_receiveResponse(t){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._succeeded("remote",t);break;default:{const s=Bi.sipErrorCause(t.status_code);this._failed("remote",t,s);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,Ja.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,Ja.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(t,s){t==="remote"?(this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from):t==="local"&&(this._direction="outgoing",this._local_identity=s.from,this._remote_identity=s.to),this._ua.newOptions(this,{originator:t,message:this,request:s})}_failed(t,s,i){ro.debug("OPTIONS failed"),this._close(),ro.debug('emit "failed"'),this.emit("failed",{originator:t,response:s||null,cause:i})}_succeeded(t,s){ro.debug("OPTIONS succeeded"),this._close(),ro.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:s})}},Wu={};const lT=ct,za=At(),oT=es(),Gi=new lT("Socket");Wu.isSocket=c=>{if(Array.isArray(c))return!1;if(typeof c>"u")return Gi.warn("undefined JsSIP.Socket instance"),!1;try{if(!za.isString(c.url))throw Gi.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!za.isString(c.via_transport))throw Gi.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(oT.parse(c.sip_uri,"SIP_URI")===-1)throw Gi.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(t=>{if(!za.isFunction(c[t]))throw Gi.warn(`missing or invalid JsSIP.Socket method: ${t}`),new Error(`Missing or invalid JsSIP.Socket method: ${t}`)})}catch{return!1}return!0};const aT=ct,uT=Wu,bf=De,Ut=new aT("Transport"),Bt={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:bf.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:bf.CONNECTION_RECOVERY_MAX_INTERVAL}};var Nd=class{constructor(t,s=Bt.recovery_options){Ut.debug("new()"),this.status=Bt.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=s,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(i){Ut.warn(`cannot use TextDecoder: ${i}`)}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(i){if(!uT.isSocket(i.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(i.weight&&!Number(i.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:i.socket,weight:i.weight||0,status:Bt.SOCKET_STATUS_READY})},this),this._getSocket()}get via_transport(){return this.socket.via_transport}get url(){return this.socket.url}get sip_uri(){return this.socket.sip_uri}connect(){if(Ut.debug("connect()"),this.isConnected()){Ut.debug("Transport is already connected");return}else if(this.isConnecting()){Ut.debug("Transport is connecting");return}this.close_requested=!1,this.status=Bt.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}disconnect(){Ut.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=Bt.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=()=>{},this.socket.ondisconnect=()=>{},this.socket.ondata=()=>{},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}send(t){if(Ut.debug("send()"),!this.isConnected())return Ut.warn("unable to send message, transport is not connected"),!1;const s=t.toString();return Ut.debug(`sending message:
|
|
116
116
|
|
|
117
|
-
${
|
|
118
|
-
`),this.socket.send(
|
|
119
|
-
`){
|
|
117
|
+
${s}
|
|
118
|
+
`),this.socket.send(s)}isConnected(){return this.status===Bt.STATUS_CONNECTED}isConnecting(){return this.status===Bt.STATUS_CONNECTING}_reconnect(){this.recover_attempts+=1;let t=Math.floor(Math.random()*Math.pow(2,this.recover_attempts)+1);t<this.recovery_options.min_interval?t=this.recovery_options.min_interval:t>this.recovery_options.max_interval&&(t=this.recovery_options.max_interval),Ut.debug(`reconnection attempt: ${this.recover_attempts}. next connection attempt in ${t} seconds`),this.recovery_timer=setTimeout(()=>{!this.close_requested&&!(this.isConnected()||this.isConnecting())&&(this._getSocket(),this.connect())},t*1e3)}_getSocket(){let t=[];if(this.sockets.forEach(i=>{i.status!==Bt.SOCKET_STATUS_ERROR&&(t.length===0?t.push(i):i.weight>t[0].weight?t=[i]:i.weight===t[0].weight&&t.push(i))}),t.length===0){this.sockets.forEach(i=>{i.status=Bt.SOCKET_STATUS_READY}),this._getSocket();return}const s=Math.floor(Math.random()*t.length);this.socket=t[s].socket}_onConnect(){this.recover_attempts=0,this.status=Bt.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}_onDisconnect(t,s,i){this.status=Bt.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:t,code:s,reason:i}),!this.close_requested&&(this.sockets.forEach(function(a){this.socket===a.socket&&(a.status=Bt.SOCKET_STATUS_ERROR)},this),this._reconnect(t))}_onData(t){if(t===`\r
|
|
119
|
+
`){Ut.debug("received message with CRLF Keep Alive response");return}else if(typeof t!="string"){try{this.textDecoder?t=this.textDecoder.decode(t):t=String.fromCharCode.apply(null,new Uint8Array(t))}catch{Ut.debug("received binary message failed to be converted into string, message discarded");return}Ut.debug(`received binary message:
|
|
120
120
|
|
|
121
121
|
${t}
|
|
122
|
-
`)}else
|
|
122
|
+
`)}else Ut.debug(`received text message:
|
|
123
123
|
|
|
124
124
|
${t}
|
|
125
|
-
`);this.ondata({transport:this,message:t})}};const
|
|
126
|
-
`);if(a===-1){
|
|
127
|
-
`,
|
|
128
|
-
`;for(const a of t)
|
|
129
|
-
`;
|
|
130
|
-
`,
|
|
131
|
-
`,
|
|
132
|
-
`,
|
|
133
|
-
`,
|
|
134
|
-
`,wd.send(l)}const TT=Xe(Od);var nl={};const fr=Ct(),Cn=De,Ja=Zt(),bf=ys(),za=Bu,Xa=Cs;nl.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:Cn.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:Cn.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:Cn.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${fr.createRandomToken(12)}.invalid`};const io={mandatory:{sockets(c){const t=[];if(za.isSocket(c))t.push({socket:c});else if(Array.isArray(c)&&c.length)for(const n of c)Object.prototype.hasOwnProperty.call(n,"socket")&&za.isSocket(n.socket)?t.push(n):za.isSocket(n)&&t.push({socket:n});else return;return t},uri(c){/^sip:/i.test(c)||(c=`${Cn.SIP}:${c}`);const t=bf.parse(c);if(t)return t.user?t:void 0}},optional:{authorization_user(c){if(Ja.parse(`"${c}"`,"quoted_string")!==-1)return c},authorization_jwt(c){if(typeof c=="string")return c},user_agent(c){if(typeof c=="string")return c},connection_recovery_max_interval(c){if(fr.isDecimal(c)){const t=Number(c);if(t>0)return t}},connection_recovery_min_interval(c){if(fr.isDecimal(c)){const t=Number(c);if(t>0)return t}},contact_uri(c){if(typeof c=="string"){const t=Ja.parse(c,"SIP_URI");if(t!==-1)return t}},display_name(c){return c},instance_id(c){if(/^uuid:/i.test(c)&&(c=c.substr(5)),Ja.parse(c,"uuid")!==-1)return c},no_answer_timeout(c){if(fr.isDecimal(c)){const t=Number(c);if(t>0)return t}},session_timers(c){if(typeof c=="boolean")return c},session_timers_refresh_method(c){if(typeof c=="string"&&(c=c.toUpperCase(),c===Cn.INVITE||c===Cn.UPDATE))return c},session_timers_force_refresher(c){if(typeof c=="boolean")return c},password(c){return String(c)},realm(c){return String(c)},ha1(c){return String(c)},register(c){if(typeof c=="boolean")return c},register_expires(c){if(fr.isDecimal(c)){const t=Number(c);if(t>0)return t}},registrar_server(c){/^sip:/i.test(c)||(c=`${Cn.SIP}:${c}`);const t=bf.parse(c);if(t)return t.user?void 0:t},use_preloaded_route(c){if(typeof c=="boolean")return c},extra_headers(c){const t=[];if(Array.isArray(c)&&c.length)for(const n of c)typeof n=="string"&&t.push(n);else return;return t}}};nl.load=(c,t)=>{for(const n in io.mandatory)if(t.hasOwnProperty(n)){const l=t[n],a=io.mandatory[n](l);if(a!==void 0)c[n]=a;else throw new Xa.ConfigurationError(n,l)}else throw new Xa.ConfigurationError(n);for(const n in io.optional)if(t.hasOwnProperty(n)){const l=t[n];if(fr.isEmpty(l))continue;const a=io.optional[n](l);if(a!==void 0)c[n]=a;else throw new Xa.ConfigurationError(n,l)}};const vT=ft.EventEmitter,ST=ut,mt=De,ET=ug,wf=Ad,Of=Kg,Df=Qg,Qa=gr,yT=Rd,lo=Ct(),CT=Cs,AT=ys(),RT=Id,Za=yt,IT=Od,eu=nl,qe=new ST("UA"),vt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var Dd=class extends vT{static get C(){return vt}constructor(t){if(qe.debug("new() [configuration:%o]",t),super(),this._cache={credentials:{}},this._configuration=Object.assign({},eu.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=vt.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,t===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(t)}catch(n){throw this._status=vt.STATUS_NOT_READY,this._error=vt.CONFIGURATION_ERROR,n}this._registrator=new ET(this)}get C(){return vt}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){qe.debug("start()"),this._status===vt.STATUS_INIT?this._transport.connect():this._status===vt.STATUS_USER_CLOSED?(qe.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=vt.STATUS_INIT,this._transport.connect()):this._status===vt.STATUS_READY?qe.debug("UA is in READY status, not restarted"):qe.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){qe.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(t){qe.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(t)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(t,n){qe.debug("call()");const l=new wf(this);return l.connect(t,n),l}sendMessage(t,n,l){qe.debug("sendMessage()");const a=new Of(this);return a.send(t,n,l),a}sendOptions(t,n,l){qe.debug("sendOptions()");const a=new Df(this);return a.send(t,n,l),a}terminateSessions(t){qe.debug("terminateSessions()");for(const n in this._sessions)this._sessions[n].isEnded()||this._sessions[n].terminate(t)}stop(){if(qe.debug("stop()"),this._dynConfiguration={},this._status===vt.STATUS_USER_CLOSED){qe.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const l in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,l)){qe.debug(`closing session ${l}`);try{this._sessions[l].terminate()}catch{}}for(const l in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,l))try{this._applicants[l].close()}catch{}this._status=vt.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(t){return lo.normalizeTarget(t,this._configuration.hostport_params)}get(t){switch(t){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:qe.warn('get() | cannot get "%s" parameter in runtime',t);return}}set(t,n){switch(t){case"authorization_user":{this._configuration.authorization_user=String(n);break}case"password":{this._configuration.password=String(n);break}case"realm":{this._configuration.realm=String(n);break}case"ha1":{this._configuration.ha1=String(n),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(n);break}case"display_name":{this._configuration.display_name=n;break}default:return qe.warn('set() | cannot set "%s" parameter in runtime',t),!1}return!0}newTransaction(t){this._transactions[t.type][t.id]=t,this.emit("newTransaction",{transaction:t})}destroyTransaction(t){delete this._transactions[t.type][t.id],this.emit("transactionDestroyed",{transaction:t})}newDialog(t){this._dialogs[t.id]=t}destroyDialog(t){delete this._dialogs[t.id]}newMessage(t,n){this._applicants[t]=t,this.emit("newMessage",n)}newOptions(t,n){this._applicants[t]=t,this.emit("newOptions",n)}destroyMessage(t){delete this._applicants[t]}newRTCSession(t,n){this._sessions[t.id]=t,this.emit("newRTCSession",n)}destroyRTCSession(t){delete this._sessions[t.id]}registered(t){this.emit("registered",t)}unregistered(t){this.emit("unregistered",t)}registrationFailed(t){this.emit("registrationFailed",t)}receiveRequest(t){const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){qe.debug("Request-URI does not point to us"),t.method!==mt.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===mt.SIPS){t.reply_sl(416);return}if(Qa.checkTransaction(this,t))return;if(n===mt.INVITE?new Qa.InviteServerTransaction(this,this._transport,t):n!==mt.ACK&&n!==mt.CANCEL&&new Qa.NonInviteServerTransaction(this,this._transport,t),n===mt.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new Df(this).init_incoming(t)}else if(n===mt.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new Of(this).init_incoming(t)}else if(n===mt.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let l,a;if(t.to_tag)l=this._findDialog(t.call_id,t.from_tag,t.to_tag),l?l.receiveRequest(t):n===mt.NOTIFY?(a=this._findSession(t),a?a.receiveRequest(t):(qe.debug("received NOTIFY request for a non existent subscription"),t.reply(481,"Subscription does not exist"))):n!==mt.ACK&&t.reply(481);else switch(n){case mt.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const s=t.replaces;l=this._findDialog(s.call_id,s.from_tag,s.to_tag),l?(a=l.owner,a.isEnded()?t.reply(603):a.receiveRequest(t)):t.reply(481)}else a=new wf(this),a.init_incoming(t);else qe.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case mt.BYE:t.reply(481);break;case mt.CANCEL:a=this._findSession(t),a?a.receiveRequest(t):qe.debug("received CANCEL request for a non existent session");break;case mt.ACK:break;case mt.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}_findSession({call_id:t,from_tag:n,to_tag:l}){const a=t+n,s=this._sessions[a],r=t+l,h=this._sessions[r];return s||h||null}_findDialog(t,n,l){let a=t+n+l,s=this._dialogs[a];return s||(a=t+l+n,s=this._dialogs[a],s||null)}_loadConfig(t){try{eu.load(this._configuration,t)}catch(a){throw a}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=lo.newUUID()),this._configuration.jssip_id=lo.createRandomToken(5);const n=this._configuration.uri.clone();n.user=null,this._configuration.hostport_params=n.toString().replace(/^sip:/i,"");try{this._transport=new yT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=bT.bind(this),this._transport.onconnect=wT.bind(this),this._transport.ondisconnect=OT.bind(this),this._transport.ondata=DT.bind(this)}catch(a){throw qe.warn(a),new CT.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const a=this._configuration.uri.clone();a.user=null,a.clearParams(),a.clearHeaders(),this._configuration.registrar_server=a}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new AT("sip",lo.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(a={}){const s=a.anonymous||null,r=a.outbound||null;let h="<";return s?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),r&&(s?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const l=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(l.indexOf(a)!==-1?Object.defineProperty(this._configuration,a,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,a,{writable:!1,configurable:!1}));qe.debug("configuration parameters after validation:");for(const a in this._configuration)if(Object.prototype.hasOwnProperty.call(eu.settings,a))switch(a){case"uri":case"registrar_server":qe.debug(`- ${a}: ${this._configuration[a]}`);break;case"password":case"ha1":case"authorization_jwt":qe.debug(`- ${a}: NOT SHOWN`);break;default:qe.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}};function bT(c){this.emit("connecting",c)}function wT(c){this._status!==vt.STATUS_USER_CLOSED&&(this._status=vt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function OT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const l in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],l)&&this._transactions[n][l].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==vt.STATUS_USER_CLOSED&&(this._status=vt.STATUS_NOT_READY,this._error=vt.NETWORK_ERROR)}function DT(c){const t=c.transport;let n=c.message;if(n=RT.parseMessage(n,this),!!n&&!(this._status===vt.STATUS_USER_CLOSED&&n instanceof Za.IncomingRequest)&&IT(n,this,t)){if(n instanceof Za.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Za.IncomingResponse){let l;switch(n.method){case mt.INVITE:l=this._transactions.ict[n.via_branch],l&&l.receiveResponse(n);break;case mt.ACK:break;default:l=this._transactions.nict[n.via_branch],l&&l.receiveResponse(n);break}}}}const NT=Xe(Dd);var _t=[];for(var tu=0;tu<256;++tu)_t.push((tu+256).toString(16).slice(1));function xT(c,t=0){return(_t[c[t+0]]+_t[c[t+1]]+_t[c[t+2]]+_t[c[t+3]]+"-"+_t[c[t+4]]+_t[c[t+5]]+"-"+_t[c[t+6]]+_t[c[t+7]]+"-"+_t[c[t+8]]+_t[c[t+9]]+"-"+_t[c[t+10]]+_t[c[t+11]]+_t[c[t+12]]+_t[c[t+13]]+_t[c[t+14]]+_t[c[t+15]]).toLowerCase()}var oo,UT=new Uint8Array(16);function kT(){if(!oo&&(oo=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!oo))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return oo(UT)}var PT=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Nf={randomUUID:PT};function xf(c,t,n){if(Nf.randomUUID&&!t&&!c)return Nf.randomUUID();c=c||{};var l=c.random||(c.rng||kT)();if(l[6]=l[6]&15|64,l[8]=l[8]&63|128,t){n=n||0;for(var a=0;a<16;++a)t[n+a]=l[a];return t}return xT(l)}var Pe=Ct();const Ts=Xe(Pe),su=new Wo("Dialog"),Fs={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class ao{static get C(){return Fs}constructor(t,n,l,a=Fs.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,n instanceof yt.IncomingResponse&&(a=n.status_code<200?Fs.STATUS_EARLY:Fs.STATUS_CONFIRMED),l==="UAS"){this._id={call_id:n.call_id,local_tag:n.to_tag,remote_tag:n.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=n.cseq,this._local_uri=n.parseHeader("to").uri,this._remote_uri=n.parseHeader("from").uri;let s=n.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=n.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(l==="UAC"){this._id={call_id:n.call_id,local_tag:n.from_tag,remote_tag:n.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=n.cseq,this._local_uri=n.parseHeader("from").uri,this._remote_uri=n.parseHeader("to").uri;let s=n.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=n.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),su.debug(`new ${l} dialog created with status ${this._state===Fs.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Fs.STATUS_TERMINATED}update(t,n){this._state=Fs.STATUS_CONFIRMED,su.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){su.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Fs.STATUS_TERMINATED}sendRequest(t,n={}){const l=Ts.cloneArray(n.extraHeaders),a=Ts.cloneObject(n.eventHandlers),s=n.body||null,r=this._createRequest(t,l,s);return a.onAuthenticated=()=>{this._local_seqnum+=1},new pg(this,r,a).send(),r}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===$.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===$.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,n,l){n=Ts.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=t===$.CANCEL||t===$.ACK?this._local_seqnum:this._local_seqnum+=1;return new yt.OutgoingRequest(t,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},n,l)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===$.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===$.INVITE||t.method===$.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const n=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${n}`]),!1}else{this._uas_pending_reply=!0;const n=()=>{(t.server_transaction.state===Gt.C.STATUS_ACCEPTED||t.server_transaction.state===Gt.C.STATUS_COMPLETED||t.server_transaction.state===Gt.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",n),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",n)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Gt.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===$.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Gt.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}}class MT{constructor(t,n){Kt(this,"plugin",null);Kt(this,"rtcpPeer",null);Kt(this,"handleId",0);Kt(this,"info",null);Kt(this,"joinResult",null);Kt(this,"state",{});Kt(this,"stream",null);Kt(this,"loaded",!1);Kt(this,"aTracks",[]);Kt(this,"vTracks",[]);this.info=t,this.plugin=n,this.rtcpPeer=new RTCPeerConnection({iceServers:[]})}get memberInfo(){return{stream:this.stream,joinResult:this.joinResult,sender:this.handleId,type:"subscriber",name:this.info.display,state:this.state,id:this.handleId}}updateMemberState(t){var n;this.state={...this.state,...t||{}},(n=this.plugin)==null||n.session.emit("member:update",this.memberInfo)}updateMemberStateFromMessage(t){var s,r,h,d;const n=(r=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:r.newStatePublisher,a=((d=(h=t==null?void 0:t.plugindata)==null?void 0:h.data)==null?void 0:d.publisher_state).find(_=>_.id===n);this.updateMemberState(a==null?void 0:a.state)}hangup(){this.rtcpPeer&&(this.rtcpPeer.close(),this.rtcpPeer=null),this.stream&&this.stream.getTracks().forEach(t=>{t.stop()})}}class Qt{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(t){return Qt.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(l=>l.kind===t):[]}static async getMicrophoneList(){return(await Qt.getDevices("audioinput")).map((n,l)=>({...n,deviceId:n.deviceId,label:n.label||`microphone ${l+1}`,kind:n.kind,groupId:n.groupId}))}static async getSpeakerList(){return(await Qt.getDevices("audiooutput")).map((n,l)=>({...n,deviceId:n.deviceId,label:n.label||`speaker ${l+1}`,kind:n.kind,groupId:n.groupId}))}static async getCameraList(){return(await Qt.getDevices("videoinput")).map((n,l)=>({...n,deviceId:n.deviceId,label:n.label||`camera ${l+1}`,kind:n.kind,groupId:n.groupId}))}static stopStreamTracks(t){t&&t.getTracks().forEach(n=>{n.stop()})}static async getMediaFromInputs({videoInput:t,audioInput:n}){let l,a;t==="default"?l=!0:t&&t!=="default"&&(l={deviceId:{exact:t}}),n==="default"?a=!0:n&&n!=="default"&&(a={deviceId:{exact:n}});const s={audio:a,video:l};return Qt.getUserMedia(s)}static async getUserMedia(t){return await navigator.mediaDevices.getUserMedia(t)}static async changeAudioOutput(t,n){if(!(!t||!n))if(typeof t.sinkId<"u")try{await t.setSinkId(n)}catch(l){let a=l;l.name==="SecurityError"&&(a=`You need to use HTTPS for selecting audio output device: ${l}`),console.error(a)}else console.warn("Browser does not support output device selection.")}static toggleAudioMute(t){const n=t.getAudioTracks();if(n.length!==0)return n.forEach(l=>{l.enabled=!l.enabled}),n[0].enabled}static toggleVideoMute(t){const n=t.getVideoTracks();if(n.length!==0)return n.forEach(l=>{l.enabled=!l.enabled}),n[0].enabled}static async getStream(t={video:!0,audio:!0}){try{const n=await navigator.mediaDevices.getUserMedia(t);let l=n.getTracks();return t.video?l=n.getVideoTracks():t.audio&&(l=n.getAudioTracks()),l.length===0?{stream:n,track:null}:{stream:n,track:l[0]}}catch(n){return console.warn(n),{stream:null,track:null}}}}var LT=ys();const Rn=Xe(LT),Ut={LEAVE:"Leave",DETACH:"Detach",AUDIO_CHANGE:"AudioChange",VIDEO_CHANGE:"VideoChange",STATE:"State",ICE:"Ice",CONFIGURE:"Configure",TRICKLE:"Trickle",SUBSCRIBER:"Subscriber",PUBLISHER:"Publisher"},Z=new Wo("JanusSession"),$T="/opt/recordings/",se={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},uo=["audio","video"];class Ho extends ft.EventEmitter{static get C(){return se}constructor(t){Z.debug("new"),super(),this._id=null,this._ua=t,this._status=se.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:$.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._candidates=[],this.publishers=[],this.private_id=null,this.memberList={},this.myFeedList=[],this.display_name="",this.stunServers=[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}],this.opaque_id=this.generateOpaqueId(),this.screen_share_opaque_id=this.generateOpaqueId(),this._data={},this.isAudioOn=!0,this.isVideoOn=!0,this.mediaConstraints={}}get C(){return se}get causes(){return $.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case se.STATUS_NULL:case se.STATUS_INVITE_SENT:case se.STATUS_1XX_RECEIVED:case se.STATUS_INVITE_RECEIVED:case se.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case se.STATUS_ANSWERED:case se.STATUS_WAITING_FOR_ACK:case se.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case se.STATUS_CANCELED:case se.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(t){return`PTYPE: ${t}`}generateOpaqueId(){return`videoroomtest-${xf().replace(/-/g,"").slice(0,12)}`}connect(t,n,l={},a){Z.debug("connect()"),this.display_name=n;const s=t,r=Pe.cloneObject(l.eventHandlers),h=Pe.cloneArray(l.extraHeaders),d=Pe.cloneObject(l.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={...d};const _=l.mediaStream||null,g=Pe.cloneObject(l.pcConfig,{iceServers:[]}),T=l.rtcConstraints||null,S=l.rtcOfferConstraints||null;if(this._rtcOfferConstraints=S,this._rtcAnswerConstraints=l.rtcAnswerConstraints||null,this._data=l.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==se.STATUS_NULL)throw new js.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new js.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),this.room_id=t.user,this.target=t,!t)throw new TypeError(`Invalid target: ${s}`);this._sessionTimers.enabled&&Pe.isDecimal(l.sessionTimersExpires)&&(l.sessionTimersExpires>=$.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=l.sessionTimersExpires:this._sessionTimers.defaultExpires=$.SESSION_EXPIRES);for(const A in r)Object.prototype.hasOwnProperty.call(r,A)&&this.on(A,r[A]);this._from_tag=Pe.newTag();const E=l.anonymous||!1,C={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:E,outbound:!0}),E?(C.from_display_name="Anonymous",C.from_uri=new Rn("sip","anonymous","anonymous.invalid"),h.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),h.push("Privacy: id")):l.fromUserName&&(C.from_uri=new Rn("sip",l.fromUserName,this._ua.configuration.uri.host),h.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),l.fromDisplayName&&(C.from_display_name=l.fromDisplayName),h.push(`Contact: ${this._contact}`),h.push("Content-Type: application/json"),this._sessionTimers.enabled&&h.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new yt.InitialOutgoingInviteRequest(t,this._ua,C,h),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(g,T),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,a&&a(this),this._newJanusSession("local",this._request),this._sendInitialRequest(d,S,_)}_overrideSenderTracks(t,n){t.getTracks().forEach(l=>{n.getSenders().forEach(async s=>{s.track.kind===l.kind&&(l.kind==="audio"&&!this.isAudioOn&&(l.enabled=!1),l.kind==="video"&&!this.isVideoOn&&(l.enabled=!1),await s.replaceTrack(l))})})}init_incoming(t,n){Z.debug("init_incoming()");let l;const a=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&a!=="application/sdp"){t.reply(415);return}if(this._status=se.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(l=t.getHeader("expires")*1e3),t.to_tag=Pe.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=se.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,$.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===se.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,$.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),this._newJanusSession("remote",t),this._status!==se.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){Z.debug("answer()");const n=this._request,l=Pe.cloneArray(t.extraHeaders),a=Pe.cloneObject(t.mediaConstraints),s=t.mediaStream||null,r=Pe.cloneObject(t.pcConfig,{iceServers:[]}),h=t.rtcConstraints||null,d=t.rtcAnswerConstraints||null,_=Pe.cloneObject(t.rtcOfferConstraints);let g,T=!1,S=!1,E=!1,C=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new js.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==se.STATUS_WAITING_FOR_ANSWER)throw new js.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Pe.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=$.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=$.SESSION_EXPIRES),this._status=se.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),l.unshift(`Contact: ${this._contact}`);const A=n.parseSDP();Array.isArray(A.media)||(A.media=[A.media]);for(const R of A.media)R.type==="audio"&&(T=!0,(!R.direction||R.direction==="sendrecv")&&(E=!0)),R.type==="video"&&(S=!0,(!R.direction||R.direction==="sendrecv")&&(C=!0));if(s&&a.audio===!1){g=s.getAudioTracks();for(const R of g)s.removeTrack(R)}if(s&&a.video===!1){g=s.getVideoTracks();for(const R of g)s.removeTrack(R)}!s&&a.audio===void 0&&(a.audio=E),!s&&a.video===void 0&&(a.video=C),!s&&!T&&!_.offerToReceiveAudio&&(a.audio=!1),!s&&!S&&!_.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(r,h),Promise.resolve().then(()=>{if(s)return s;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(R=>{throw this._status===se.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),this._failed("local",null,$.causes.USER_DENIED_MEDIA_ACCESS),Z.warn('emit "getusermediafailed" [error:%o]',R),this.emit("getusermediafailed",R),new Error("getUserMedia() failed"))})}).then(R=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=R,R&&R.getTracks().forEach(V=>{this._connection.addTrack(V,R)})}).then(()=>{if(this._late_sdp)return;const R={originator:"remote",type:"offer",sdp:n.body};Z.debug('emit "sdp"'),this.emit("sdp",R);const V=new RTCSessionDescription({type:"offer",sdp:R.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(V)).catch(w=>{throw n.reply(488),this._failed("system",null,$.causes.WEBRTC_ERROR),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',w),this.emit("peerconnection:setremotedescriptionfailed",w),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(n),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",d).catch(()=>{throw n.reply(500),new Error("_createLocalDescription() failed")})}).then(R=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,l),n.reply(200,null,l,R,()=>{this._status=se.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,R),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,$.causes.CONNECTION_ERROR)})}).catch(R=>{this._status!==se.STATUS_TERMINATED&&Z.warn(R)})}terminate(t={}){Z.debug("terminate()");const n=t.cause||$.causes.BYE,l=Pe.cloneArray(t.extraHeaders),a=t.body;let s,r=t.status_code,h=t.reason_phrase;if(this._status===se.STATUS_TERMINATED)throw new js.InvalidStateError(this._status);switch(this._status){case se.STATUS_NULL:case se.STATUS_INVITE_SENT:case se.STATUS_1XX_RECEIVED:if(Z.debug("canceling session"),r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(h=h||$.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${h}"`),this._status===se.STATUS_NULL||this._status===se.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===se.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=se.STATUS_CANCELED,this._failed("local",null,$.causes.CANCELED);break;case se.STATUS_WAITING_FOR_ANSWER:case se.STATUS_ANSWERED:if(Z.debug("rejecting session"),r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,h,l,a),this._failed("local",null,$.causes.REJECTED);break;case se.STATUS_WAITING_FOR_ACK:case se.STATUS_CONFIRMED:if(Z.debug("terminating session"),h=t.reason_phrase||$.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&l.push(`Reason: SIP ;cause=${r}; text="${h}"`),this._status===se.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Gt.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:_})=>{_===$.ACK&&(this.sendRequest($.BYE,{extraHeaders:l,body:a}),d.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Gt.C.STATUS_TERMINATED&&(this.sendRequest($.BYE,{extraHeaders:l,body:a}),d.terminate(),this.closeSession())}),this._ended("local",null,n),this._dialog=d,this._ua.newDialog(d)}else{const d={janus:"leave"},_=["Content-Type: application/json",this.getPTypeHeader(Ut.LEAVE)];this.sendRequest($.BYE,{extraHeaders:_,body:JSON.stringify(d)}),this.closeSession(),this._ended("local",null,n)}}}configureMedia(t){this.isAudioOn=t.audio,this.isVideoOn=t.video}enableAudio(t){const n={janus:"message",body:{audio:t},handle_id:this.handle_id,session_id:this.session_id},l=["Content-Type: application/json",this.getPTypeHeader(Ut.AUDIO_CHANGE)];this.sendRequest($.INFO,{extraHeaders:l,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async a=>{a.status_code===200&&(this._ua.emit("changeAudioState",t),this.sendStateMessage({audio:t}))}}})}startAudio(){Qt.toggleAudioMute(this.stream),this._toggleMuteAudio(!1),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Qt.toggleAudioMute(this.stream),this._toggleMuteAudio(!0),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(t){const n={janus:"message",body:{video:t},handle_id:this.handle_id,session_id:this.session_id},l=["Content-Type: application/json",this.getPTypeHeader(Ut.VIDEO_CHANGE)];this.sendRequest($.INFO,{extraHeaders:l,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async a=>{a.status_code===200&&(this._ua.emit("changeVideoState",t),this.sendStateMessage({video:t}))}}})}startVideo(){Qt.toggleVideoMute(this.stream),this._toggleMuteVideo(!1),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Qt.toggleVideoMute(this.stream),this._toggleMuteVideo(!0),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(t){const n={janus:"message",body:{request:"state",data:t},handle_id:this.handle_id,session_id:this.session_id},l=["Content-Type: application/json",this.getPTypeHeader(Ut.STATE)];this.sendRequest($.INFO,{extraHeaders:l,body:JSON.stringify(n)})}sendInfo(t,n,l={}){if(Z.debug("sendInfo()"),this._status!==se.STATUS_CONFIRMED&&this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_1XX_RECEIVED)throw new js.InvalidStateError(this._status);new Au(this).send(t,n,l)}mute(t={audio:!0,video:!1}){Z.debug("mute()");let n=!1,l=!1;this._audioMuted===!1&&t.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(l=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||l===!0)&&this._onmute({audio:n,video:l})}unmute(t={audio:!0,video:!0}){Z.debug("unmute()");let n=!1,l=!1;this._audioMuted===!0&&t.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(l=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||l===!0)&&this._onunmute({audio:n,video:l})}hold(t={},n){if(Z.debug("hold()"),this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const l={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:$.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}unhold(t={},n){if(Z.debug("unhold()"),this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const l={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:$.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},n){Z.debug("renegotiate()");const l=t.rtcOfferConstraints||null;if(this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const a={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:$.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}),!0}refer(t,n){Z.debug("refer()");const l=t;if(this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${l}`);const a=new kg(this);a.sendRefer(t,n);const s=a.id;return this._referSubscribers[s]=a,a.on("requestFailed",()=>{delete this._referSubscribers[s]}),a.on("accepted",()=>{delete this._referSubscribers[s]}),a.on("failed",()=>{delete this._referSubscribers[s]}),a}sendRequest(t,n){return Z.debug("sendRequest()"),this._dialog.sendRequest(t,n)}receiveNotify(t){Z.debug("receiveRequest()")}receiveRequest(t){if(Z.debug("receiveRequest()"),t.method===$.CANCEL)(this._status===se.STATUS_WAITING_FOR_ANSWER||this._status===se.STATUS_ANSWERED)&&(this._status=se.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,$.causes.CANCELED));else switch(t.method){case $.ACK:if(this._status!==se.STATUS_WAITING_FOR_ACK)return;if(this._status=se.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:$.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};Z.debug('emit "sdp"'),this.emit("sdp",n);const l=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(a=>{this.terminate({cause:$.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",t);break;case $.BYE:this._status===se.STATUS_CONFIRMED||this._status===se.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,$.causes.BYE)):this._status===se.STATUS_INVITE_RECEIVED||this._status===se.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,$.causes.BYE)):t.reply(403,"Wrong Status");break;case $.INVITE:this._status===se.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case $.INFO:if(this._status===se.STATUS_1XX_RECEIVED||this._status===se.STATUS_WAITING_FOR_ANSWER||this._status===se.STATUS_ANSWERED||this._status===se.STATUS_WAITING_FOR_ACK||this._status===se.STATUS_CONFIRMED){const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;n&&n.match(/^application\/dtmf-relay/i)?new Cg(this).init_incoming(t):n!==void 0?new Au(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case $.UPDATE:this._status===se.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case $.REFER:this._status===se.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case $.NOTIFY:this._status===se.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){Z.warn("onTransportError()"),this._status!==se.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:$.causes.CONNECTION_ERROR,cause:$.causes.CONNECTION_ERROR})}onRequestTimeout(){Z.warn("onRequestTimeout()"),this._status!==se.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:$.causes.REQUEST_TIMEOUT,cause:$.causes.REQUEST_TIMEOUT})}onDialogError(){Z.warn("onDialogError()"),this._status!==se.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:$.causes.DIALOG_ERROR,cause:$.causes.DIALOG_ERROR})}newDTMF(t){Z.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){Z.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Z.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Z.debug("_isReadyToReOffer() | session not established yet"),!1):(Z.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Z.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Z.debug("close() | closing local MediaStream"),Pe.closeMediaStream(this._localMediaStream)),this._status!==se.STATUS_TERMINATED){if(this._status=se.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){Z.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,n){let l=Li.T1;function a(){this._status===se.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],n),l<Li.T2&&(l=l*2,l>Li.T2&&(l=Li.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),l))}this._timers.invite2xxTimer=setTimeout(a.bind(this),l)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===se.STATUS_WAITING_FOR_ACK&&(Z.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest($.BYE),this._ended("remote",null,$.causes.NO_ACK))},Li.TIMER_H)}_createRTCConnection(t,n){this.stunServers,this._connection=new RTCPeerConnection(t,n),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:$.causes.RTP_TIMEOUT,status_code:408,reason_phrase:$.causes.RTP_TIMEOUT})});let l;const a=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(l),l=setTimeout(()=>{this.lastTrickleReceived=!0,this.subscribeSent&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{}))},500))};this._connection.onicecandidate=a,Z.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,n){if(Z.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const l=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?l.createOffer(n).catch(a=>(Z.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):l.createAnswer(n).catch(a=>(Z.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>(this.jsepOffer=a,l.setLocalDescription(a).catch(s=>(this._rtcReady=!0,Z.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s))))).then(()=>{const a=n&&n.iceRestart;if(l.iceGatheringState==="complete"&&!a||l.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:l.localDescription.sdp};return Z.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let r=!1,h,d;this._iceReady=!1;const _=()=>{l.removeEventListener("icecandidate",h),l.removeEventListener("icegatheringstatechange",d),r=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:t,sdp:l.localDescription.sdp};Z.debug('emit "sdp"'),this.emit("sdp",g),s(g.sdp)};l.addEventListener("icecandidate",h=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:_}):r||_()}),l.addEventListener("icegatheringstatechange",d=()=>{l.iceGatheringState==="complete"&&!r&&_()})})})}_createDialog(t,n,l){const a=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+a+s;let h=this._earlyDialogs[r];if(l)return h?!0:(h=new ao(this,t,n,ao.C.STATUS_EARLY),h.error?(Z.debug(h.error),this._failed("remote",t,$.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=h,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,h)return h.update(t,n),this._dialog=h,delete this._earlyDialogs[r],!0;const d=new ao(this,t,n);return d.error?(Z.debug(d.error),this._failed("remote",t,$.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(t){Z.debug("receiveReinvite()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(h={}){a=!0;const d=h.status_code||403,_=h.reason_phrase||"",g=Pe.cloneArray(h.extraHeaders);if(this._status!==se.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,_,g)}if(this.emit("reinvite",l),a)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(h=>{r.call(this,h)}).catch(()=>{t.reply(500)});return}if(n!=="application/sdp"){Z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(h=>{this._status!==se.STATUS_TERMINATED&&r.call(this,h)}).catch(h=>{Z.warn(h)});function r(h){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),this._late_sdp&&(h=this._mangleOffer(h)),t.reply(200,null,d,h,()=>{this._status=se.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,h),this._setACKTimer()}),typeof l.callback=="function"&&l.callback()}}_receiveUpdate(t){Z.debug("receiveUpdate()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(h={}){a=!0;const d=h.status_code||403,_=h.reason_phrase||"",g=Pe.cloneArray(h.extraHeaders);if(this._status!==se.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,_,g)}if(this.emit("update",l),a)return;if(!t.body){r.call(this,null);return}if(n!=="application/sdp"){Z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(h=>{this._status!==se.STATUS_TERMINATED&&r.call(this,h)}).catch(h=>{Z.warn(h)});function r(h){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),t.reply(200,null,d,h),typeof l.callback=="function"&&l.callback()}}_processInDialogSdpOffer(t){Z.debug("_processInDialogSdpOffer()");const n=t.parseSDP();let l=!1;for(const r of n.media){if(uo.indexOf(r.type)===-1)continue;const h=r.direction||n.direction||"sendrecv";if(h==="sendonly"||h==="inactive")l=!0;else{l=!1;break}}const a={originator:"remote",type:"offer",sdp:t.body};Z.debug('emit "sdp"'),this.emit("sdp",a);const s=new RTCSessionDescription({type:"offer",sdp:a.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(r=>{throw t.reply(488),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',r),this.emit("peerconnection:setremotedescriptionfailed",r),r})}).then(()=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&l===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&l===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(r=>{throw t.reply(500),Z.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',r),r})}).catch(r=>{Z.warn("_processInDialogSdpOffer() failed [error: %o]",r)}),this._connectionPromiseQueue}_receiveRefer(t){if(Z.debug("receiveRefer()"),!t.refer_to){Z.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==$.SIP){Z.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const n=new Dg(this,t.cseq);Z.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,r)=>{l.call(this,s,r)},reject:()=>{a.call(this)}});function l(s,r={}){if(s=typeof s=="function"?s:null,this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED)return!1;const h=new Ho(this._ua);if(h.on("progress",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),h.on("accepted",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),h.on("_failed",({message:d,cause:_})=>{d?n.notify(d.status_code,d.reason_phrase):n.notify(487,_)}),t.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));r.extraHeaders=Pe.cloneArray(r.extraHeaders),r.extraHeaders.push(`Replaces: ${d}`)}h.connect(t.refer_to.uri.toAor(),r,s)}function a(){n.notify(603)}}_receiveNotify(t){switch(Z.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let n,l;if(t.event.params&&t.event.params.id)n=t.event.params.id,l=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)l=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!l){t.reply(481,"Subscription does not exist");return}l.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){Z.debug("receiveReplaces()");function n(a){if(this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED)return!1;const s=new Ho(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,a)}function l(){Z.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:a=>{n.call(this,a)},reject:()=>{l.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(t,n,l){this.ackSent=!1,this.publisherSubscribeSent=!1;const a=new tl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(l)return l;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(s=>{throw this._status===se.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,$.causes.USER_DENIED_MEDIA_ACCESS),Z.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(r=>{this._connection.addTrack(r,s)}),this._connecting(this._request),this._createLocalDescription("offer",n).catch(r=>{throw this._failed("local",null,$.causes.WEBRTC_ERROR),r})}).then(s=>{if(this._is_canceled||this._status===se.STATUS_TERMINATED)throw new Error("terminated");const r={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},h=JSON.stringify(r);this._request.body=h,this._status=se.STATUS_INVITE_SENT,Z.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(s=>{this._status!==se.STATUS_TERMINATED&&Z.warn(s)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async changeMediaConstraints(t){this.mediaConstraints={...t},await this.processPlugins(),this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}async loadStream(){const t={};this.isAudioOn?this.mediaConstraints.audio?t.audio=this.mediaConstraints.audio:t.audio=!0:t.audio=!1,this.isVideoOn?this.mediaConstraints.video?t.video=this.mediaConstraints.video:t.video=!0:t.video=!1;let n=null;try{n=await navigator.mediaDevices.getUserMedia(t)}catch{try{t.video=!1,n=await navigator.mediaDevices.getUserMedia(t)}catch{t.audio=!1,t.video=!1,n=await navigator.mediaDevices.getUserMedia(t)}}return n}addTracks(t){this._connection.getSenders().forEach(n=>{this._connection.removeTrack(n)}),t.forEach(n=>{this._connection.addTrack(n)})}getRecordFileName(){return $T+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let t=0;t<this.iceCandidates.length;t++)await this._connection.addIceCandidate(this.iceCandidates[t]);this.iceCandidates=[]}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handle_id,session_id:this.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...t},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...n]},s=["Content-Type: application/json",this.getPTypeHeader(Ut.ICE)];this.sendRequest($.INFO,{extraHeaders:s,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async r=>{this.isConfigureSent=!0;const d=r.data.split(`\r
|
|
135
|
-
`),_=d[d.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendMemberStartMessage(t,n){const l={janus:"message",body:{request:"start",room:this.room_id},handle_id:t.handleId,session_id:this.session_id,jsep:n},a=["Content-Type: application/json",this.getPTypeHeader(Ut.CONFIGURE)];this.sendRequest($.INFO,{extraHeaders:a,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{s.status_code===200&&await t.rtcpPeer.setLocalDescription(n)}}})}_sendTrickleMessage(t){const l={trickles:[...t.map(s=>({janus:"trickle",candidate:s,handle_id:this.handle_id,session_id:this.session_id}))]},a=[this.getPTypeHeader(Ut.TRICKLE)];this.sendRequest($.INFO,{extraHeaders:a,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{}}})}async _answerAttachedStream(t,n){let l=null;const a=async d=>{if(!t.rtcpPeer||t.loaded)return;{t.loaded=!0;const E={audio:!0,video:!0};await new Promise(C=>{setTimeout(C,100)}),l=await t.rtcpPeer.createAnswer(E),this._sendMemberStartMessage(t,l)}const _=d.streams[0].getAudioTracks(),g=d.streams[0].getVideoTracks(),T=[];_[0]&&T.push(_[0]),g[0]&&T.push(g[0]);const S=new MediaStream(T);t.stream=S,this._ua.emit("memberJoin",t.memberInfo)};let s,r=[];const h=d=>{t.rtcpPeer.signalingState!=="stable"&&t.rtcpPeer.signalingState!=="have-local-offer"||(r.push(d.candidate||null),clearTimeout(s),s=setTimeout(()=>{this._sendTrickleMessage(r)},500))};t.rtcpPeer=new RTCPeerConnection,t.rtcpPeer.ontrack=a,t.rtcpPeer.onicecandidate=h,t.rtcpPeer.sender=n.sender,await t.rtcpPeer.setRemoteDescription(n.jsep)}_sendJoinMemberRequest(t){const n={janus:"message",body:{request:"join",room:this.room_id,feed:t.info.id,ptype:"subscriber"},handle_id:t.handleId,session_id:this.session_id},l=[this.getPTypeHeader(Ut.SUBSCRIBER)];this.sendRequest($.SUBSCRIBE,{extraHeaders:l,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async a=>{var s,r;if(a.status_code===200){const h=JSON.parse(a.body);(r=(s=h==null?void 0:h.plugindata)==null?void 0:s.data)!=null&&r.id&&await this._answerAttachedStream(t,h)}}}})}_attachMember(t){const n={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},l=[this.getPTypeHeader(Ut.SUBSCRIBER)];this.sendRequest($.INFO,{extraHeaders:l,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async a=>{if(a.status_code===200){const r=JSON.parse(a.body).data.id;t.handleId=r,this._sendJoinMemberRequest(t)}}}})}_detachMember(t){const n={janus:"detach",handle_id:t.handleId,session_id:this.session_id},l=[this.getPTypeHeader(Ut.SUBSCRIBER)];this.sendRequest($.INFO,{extraHeaders:l,body:JSON.stringify(n)}),Qt.stopStreamTracks(t.memberInfo.stream),this._ua.emit("memberHangup",t.memberInfo)}receivePublishers(t){var l,a,s,r,h,d,_,g;const n={...this.memberList};(a=(l=t==null?void 0:t.plugindata)==null?void 0:l.data)==null||a.publishers.forEach(T=>{delete n[T.id],!this.memberList[T.id]&&!this.myFeedList.includes(T.id)&&T.clientID!==this.client_id&&(this.memberList[T.id]=new MT(T,this),this._attachMember(this.memberList[T.id]))}),((r=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:r.videoroom)==="synced"&&Object.keys(n).forEach(T=>{n[T].hangup(),delete this.memberList[T]}),this.publishers=(d=(h=t==null?void 0:t.plugindata)==null?void 0:h.data)==null?void 0:d.publishers,this.private_id=(g=(_=t==null?void 0:t.plugindata)==null?void 0:_.data)==null?void 0:g.private_id}receiveUnpublished(t){const n=this.memberList[t];n&&(n.hangup(),this._detachMember(n),delete this.memberList[t])}closeSession(){this.stream&&this.stream.getTracks().forEach(n=>{n.stop()}),Object.values(this.memberList).forEach(n=>{n.hangup(),this._detachMember(n)}),this._ua.emit("conferenceEnd",this.id)}async processPlugins(){const t=this._ua.processStreamPlugins;let n=await this.loadStream();for(const l of t)n=await l.process(n);this.stream.getTracks().forEach(l=>{this.stream.removeTrack(l),l.stop()}),n.getTracks().forEach(l=>{this.stream.addTrack(l)})}async resyncPlugins(t){const n=this._ua.processStreamPlugins.filter(l=>l.type===t);for(const l of n)l.running&&l.terminate();if(t==="video"){let l=await this.loadStream();for(const a of n)a.running&&(l=await a.start(l));this.stream.getTracks().forEach(a=>{this.stream.removeTrack(a),a.stop()}),l.getTracks().forEach(a=>{this.stream.addTrack(a)}),this._overrideSenderTracks(this.stream,this._connection),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}else{const l=this._ua.newStreamPlugins.find(h=>h.type===t);let s=l.getStream().clone();for(const h of n)h.running&&(s=await h.start(s));const r=l.getConnection();this._overrideSenderTracks(s,r),this._ua.emit("changePluginStream",{type:t,stream:s})}}stopProcessPlugins(t){const n=this._ua.processStreamPlugins.filter(l=>l.type===t);for(const l of n)l.running&&l.kill()}_receiveInviteResponse(t){if(Z.debug("receiveInviteResponse()"),this._dialog&&t.status_code>=200&&t.status_code<=299&&!this.ackSent)if(this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.ackSent=!0,this.sendRequest($.ACK);return}else{const n=new ao(this,t,"UAC");if(n.error!==void 0){Z.debug(n.error);return}this.sendRequest($.ACK),this.sendRequest($.BYE);return}if(this.ackSent&&!this.publisherSubscribeSent){const n=JSON.parse(t.body);this.setupMediaStream().then(()=>{this.session_id=n.session_id,this.handle_id=n.data.id,this.client_id=xf();const l={janus:"message",body:{request:"join",room:this.room_id,ptype:"publisher",display:this.display_name,clientID:this.client_id,opaque_id:this.opaque_id},handle_id:this.handle_id},a=[this.getPTypeHeader(Ut.PUBLISHER)];this.sendRequest($.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{var r,h,d,_;if(s.status_code===200){if(this.subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((h=(r=g.plugindata)==null?void 0:r.data)==null?void 0:h.videoroom)==="joined"&&this.myFeedList.push(g.plugindata.data.id),(_=(d=g.plugindata)==null?void 0:d.data)!=null&&_.publishers&&this.receivePublishers(g)}catch(g){console.error(g)}this.lastTrickleReceived&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{})),this._ua.emit("conferenceStart")}}}}),this.publisherSubscribeSent=!0})}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==se.STATUS_INVITE_SENT&&this._status!==se.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(t.status_code):this._status=se.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){Z.debug("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=se.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const n={originator:"remote",type:"answer",sdp:t.body};Z.debug('emit "sdp"'),this.emit("sdp",n);const l=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>this._progress("remote",t)).catch(a=>{Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(this._status=se.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,$.causes.MISSING_SDP),this._failed("remote",t,$.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;break}default:{const n=Pe.sipErrorCause(t.status_code);this._failed("remote",t,n)}}}_sendReinvite(t={}){Z.debug("sendReinvite()");const n=Pe.cloneArray(t.extraHeaders),l=Pe.cloneObject(t.eventHandlers),a=t.rtcOfferConstraints||this._rtcOfferConstraints||null;let s=!1;n.push(`Contact: ${this._contact}`),n.push("Content-Type: application/sdp"),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(d=>{d=this._mangleOffer(d);const _={originator:"local",type:"offer",sdp:d};Z.debug('emit "sdp"'),this.emit("sdp",_),this.sendRequest($.INVITE,{extraHeaders:n,body:d,eventHandlers:{onSuccessResponse:g=>{r.call(this,g),s=!0},onErrorResponse:g=>{h.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{h()});function r(d){if(this._status===se.STATUS_TERMINATED||(this.sendRequest($.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){h.call(this);return}}else{h.call(this);return}const _={originator:"remote",type:"answer",sdp:d.body};Z.debug('emit "sdp"'),this.emit("sdp",_);const g=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{l.succeeded&&l.succeeded(d)}).catch(T=>{h.call(this),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function h(d){l.failed&&l.failed(d)}}_sendUpdate(t={}){Z.debug("sendUpdate()");const n=Pe.cloneArray(t.extraHeaders),l=Pe.cloneObject(t.eventHandlers),a=t.rtcOfferConstraints||this._rtcOfferConstraints||null,s=t.sdpOffer||!1;let r=!1;n.push(`Contact: ${this._contact}`),this._sessionTimers.running&&n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),s?(n.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(_=>{_=this._mangleOffer(_);const g={originator:"local",type:"offer",sdp:_};Z.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest($.UPDATE,{extraHeaders:n,body:_,eventHandlers:{onSuccessResponse:T=>{h.call(this,T),r=!0},onErrorResponse:T=>{d.call(this,T)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{d.call(this)})):this.sendRequest($.UPDATE,{extraHeaders:n,eventHandlers:{onSuccessResponse:_=>{h.call(this,_)},onErrorResponse:_=>{d.call(this,_)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function h(_){if(this._status!==se.STATUS_TERMINATED&&!r)if(this._handleSessionTimersInIncomingResponse(_),s){if(_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const g={originator:"remote",type:"answer",sdp:_.body};Z.debug('emit "sdp"'),this.emit("sdp",g);const T=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(T)).then(()=>{l.succeeded&&l.succeeded(_)}).catch(S=>{d.call(this),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),this.emit("peerconnection:setremotedescriptionfailed",S)})}else l.succeeded&&l.succeeded(_)}function d(_){l.failed&&l.failed(_)}}_acceptAndTerminate(t,n,l){Z.debug("acceptAndTerminate()");const a=[];n&&(l=l||$.REASON_PHRASE[n]||"",a.push(`Reason: SIP ;cause=${n}; text="${l}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest($.ACK),this.sendRequest($.BYE,{extraHeaders:a})),this._status=se.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=kt.parse(t),this._localHold&&!this._remoteHold){Z.debug("mangleOffer() | me on hold, mangling offer");for(const n of t.media)uo.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="sendonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="sendonly")}else if(this._localHold&&this._remoteHold){Z.debug("mangleOffer() | both on hold, mangling offer");for(const n of t.media)uo.indexOf(n.type)!==-1&&(n.direction="inactive")}else if(this._remoteHold){Z.debug("mangleOffer() | remote on hold, mangling offer");for(const n of t.media)uo.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="recvonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="recvonly")}return kt.write(t)}_setLocalMediaStatus(){let t=!0,n=!0;(this._localHold||this._remoteHold)&&(t=!1,n=!1),this._audioMuted&&(t=!1),this._videoMuted&&(n=!1),this._toggleMuteAudio(!t),this._toggleMuteVideo(!n)}_handleSessionTimersInIncomingRequest(t,n){if(!this._sessionTimers.enabled)return;let l;t.session_expires&&t.session_expires>=$.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,l=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,l="uas"),n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${l}`),this._sessionTimers.refresher=l==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=$.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,n=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runSessionTimer()}_runSessionTimer(){const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==se.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Z.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===$.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==se.STATUS_TERMINATED&&(Z.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:$.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const n=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="audio");for(const l of n)l.track.enabled=!t}_toggleMuteVideo(t){const n=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="video");for(const l of n)l.track.enabled=!t}_newJanusSession(t,n){Z.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:t,session:this,request:n})}_connecting(t){Z.debug("session connecting"),Z.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,n){Z.debug("session progress"),Z.debug('emit "progress"'),this.emit("progress",{originator:t,response:n||null})}_accepted(t,n){Z.debug("session accepted"),this._start_time=new Date,Z.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){Z.debug("session confirmed"),this._is_confirmed=!0,Z.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,l){Z.debug("session ended"),this._end_time=new Date,this._close(),Z.debug('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:l})}_failed(t,n,l){Z.debug("session failed"),Z.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:n||null,cause:l}),this._close(),Z.debug('emit "failed"'),this.emit("failed",{originator:t,message:n||null,cause:l})}_onhold(t){Z.debug("session onhold"),this._setLocalMediaStatus(),Z.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){Z.debug("session onunhold"),this._setLocalMediaStatus(),Z.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:n}){Z.debug("session onmute"),this._setLocalMediaStatus(),Z.debug('emit "muted"'),this.emit("muted",{audio:t,video:n})}_onunmute({audio:t,video:n}){Z.debug("session onunmute"),this._setLocalMediaStatus(),Z.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:n})}}class ur{constructor(t){if(this.headers={},t.length>0){let n=!1;const l=t.split(`\r
|
|
136
|
-
`),a=
|
|
137
|
-
`;else{const r=
|
|
138
|
-
`;for(const
|
|
125
|
+
`);this.ondata({transport:this,message:t})}};const cT=Xe(Nd);var xd={};const fT=ct,wu=es(),Ou=Ct,io=new fT("Parser");xd.parseMessage=(c,t)=>{let s,i,a=c.indexOf(`\r
|
|
126
|
+
`);if(a===-1){io.warn("parseMessage() | no CRLF found, not a SIP message");return}const n=c.substring(0,a);let r=wu.parse(n,"Request_Response");if(r===-1){io.warn(`parseMessage() | error parsing first line of SIP message: "${n}"`);return}else r.status_code?(s=new Ou.IncomingResponse,s.status_code=r.status_code,s.reason_phrase=r.reason_phrase):(s=new Ou.IncomingRequest(t),s.method=r.method,s.ruri=r.uri);s.data=c;let h=a+2;for(;;){if(a=dT(c,h),a===-2){i=h+2;break}else if(a===-1){io.warn("parseMessage() | malformed message");return}if(r=hT(s,c,h,a),r!==!0){io.warn("parseMessage() |",r.error);return}h=a+2}if(s.hasHeader("content-length")){const d=s.getHeader("content-length");s.body=c.substr(i,d)}else s.body=c.substring(i);return s};function dT(c,t){let s=t,i=0,a=0;if(c.substring(s,s+2).match(/(^\r\n)/))return-2;for(;i===0;){if(a=c.indexOf(`\r
|
|
127
|
+
`,s),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?s=a+2:i=a}return i}function hT(c,t,s,i){let a;const n=t.indexOf(":",s),r=t.substring(s,n).trim(),h=t.substring(n+1,i).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",h),c.getHeaders("via").length===1?(a=c.parseHeader("Via"),a&&(c.via=a,c.via_branch=a.branch)):a=0;break;case"from":case"f":c.setHeader("from",h),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",h),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=wu.parse(h,"Record_Route"),a===-1)a=void 0;else for(const d of a)c.addHeader("record-route",h.substring(d.possition,d.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":c.setHeader("call-id",h),a=c.parseHeader("call-id"),a&&(c.call_id=h);break;case"contact":case"m":if(a=wu.parse(h,"Contact"),a===-1)a=void 0;else for(const d of a)c.addHeader("contact",h.substring(d.possition,d.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":c.setHeader("content-length",h),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",h),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",h),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof Ou.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",h),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",h),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",h),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",h),a=c.parseHeader("session-expires"),a&&(c.session_expires=a.expires,c.session_expires_refresher=a.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",h),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",h),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",h),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,h),a=0}return a===void 0?{error:`error parsing header "${r}"`}:!0}const _T=ct,Ud=De,wf=Ct,Ku=At(),Yu=new _T("sanityCheck"),pT=[AT],mT=[TT,vT,ST,ET],gT=[yT,CT];let je,ls,kd;var Md=(c,t,s)=>{je=c,ls=t,kd=s;for(const i of pT)if(i()===!1)return!1;if(je instanceof wf.IncomingRequest){for(const i of mT)if(i()===!1)return!1}else if(je instanceof wf.IncomingResponse){for(const i of gT)if(i()===!1)return!1}return!0};function TT(){if(je.s("to").uri.scheme!=="sip")return nl(416),!1}function vT(){if(!je.to_tag&&je.call_id.substr(0,5)===ls.configuration.jssip_id)return nl(482),!1}function ST(){const c=Ku.str_utf8_length(je.body),t=je.getHeader("content-length");if(c<t)return nl(400),!1}function ET(){const c=je.from_tag,t=je.call_id,s=je.cseq;let i;if(!je.to_tag)if(je.method===Ud.INVITE){if(ls._transactions.ist[je.via_branch])return!1;for(const a in ls._transactions.ist)if(Object.prototype.hasOwnProperty.call(ls._transactions.ist,a)&&(i=ls._transactions.ist[a],i.request.from_tag===c&&i.request.call_id===t&&i.request.cseq===s))return nl(482),!1}else{if(ls._transactions.nist[je.via_branch])return!1;for(const a in ls._transactions.nist)if(Object.prototype.hasOwnProperty.call(ls._transactions.nist,a)&&(i=ls._transactions.nist[a],i.request.from_tag===c&&i.request.call_id===t&&i.request.cseq===s))return nl(482),!1}}function yT(){if(je.getHeaders("via").length>1)return Yu.debug("more than one Via header field present in the response, dropping the response"),!1}function CT(){const c=Ku.str_utf8_length(je.body),t=je.getHeader("content-length");if(c<t)return Yu.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function AT(){const c=["from","to","call_id","cseq","via"];for(const t of c)if(!je.hasHeader(t))return Yu.debug(`missing mandatory header field : ${t}, dropping the response`),!1}function nl(c){const t=je.getHeaders("via");let s,i=`SIP/2.0 ${c} ${Ud.REASON_PHRASE[c]}\r
|
|
128
|
+
`;for(const a of t)i+=`Via: ${a}\r
|
|
129
|
+
`;s=je.getHeader("To"),je.to_tag||(s+=`;tag=${Ku.newTag()}`),i+=`To: ${s}\r
|
|
130
|
+
`,i+=`From: ${je.getHeader("From")}\r
|
|
131
|
+
`,i+=`Call-ID: ${je.call_id}\r
|
|
132
|
+
`,i+=`CSeq: ${je.cseq} ${je.method}\r
|
|
133
|
+
`,i+=`\r
|
|
134
|
+
`,kd.send(i)}const RT=Xe(Md);var rl={};const dr=At(),An=De,Qa=es(),Of=Cs(),Xa=Wu,Za=As;rl.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:An.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:An.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:An.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${dr.createRandomToken(12)}.invalid`};const lo={mandatory:{sockets(c){const t=[];if(Xa.isSocket(c))t.push({socket:c});else if(Array.isArray(c)&&c.length)for(const s of c)Object.prototype.hasOwnProperty.call(s,"socket")&&Xa.isSocket(s.socket)?t.push(s):Xa.isSocket(s)&&t.push({socket:s});else return;return t},uri(c){/^sip:/i.test(c)||(c=`${An.SIP}:${c}`);const t=Of.parse(c);if(t)return t.user?t:void 0}},optional:{authorization_user(c){if(Qa.parse(`"${c}"`,"quoted_string")!==-1)return c},authorization_jwt(c){if(typeof c=="string")return c},user_agent(c){if(typeof c=="string")return c},connection_recovery_max_interval(c){if(dr.isDecimal(c)){const t=Number(c);if(t>0)return t}},connection_recovery_min_interval(c){if(dr.isDecimal(c)){const t=Number(c);if(t>0)return t}},contact_uri(c){if(typeof c=="string"){const t=Qa.parse(c,"SIP_URI");if(t!==-1)return t}},display_name(c){return c},instance_id(c){if(/^uuid:/i.test(c)&&(c=c.substr(5)),Qa.parse(c,"uuid")!==-1)return c},no_answer_timeout(c){if(dr.isDecimal(c)){const t=Number(c);if(t>0)return t}},session_timers(c){if(typeof c=="boolean")return c},session_timers_refresh_method(c){if(typeof c=="string"&&(c=c.toUpperCase(),c===An.INVITE||c===An.UPDATE))return c},session_timers_force_refresher(c){if(typeof c=="boolean")return c},password(c){return String(c)},realm(c){return String(c)},ha1(c){return String(c)},register(c){if(typeof c=="boolean")return c},register_expires(c){if(dr.isDecimal(c)){const t=Number(c);if(t>0)return t}},registrar_server(c){/^sip:/i.test(c)||(c=`${An.SIP}:${c}`);const t=Of.parse(c);if(t)return t.user?void 0:t},use_preloaded_route(c){if(typeof c=="boolean")return c},extra_headers(c){const t=[];if(Array.isArray(c)&&c.length)for(const s of c)typeof s=="string"&&t.push(s);else return;return t}}};rl.load=(c,t)=>{for(const s in lo.mandatory)if(t.hasOwnProperty(s)){const i=t[s],a=lo.mandatory[s](i);if(a!==void 0)c[s]=a;else throw new Za.ConfigurationError(s,i)}else throw new Za.ConfigurationError(s);for(const s in lo.optional)if(t.hasOwnProperty(s)){const i=t[s];if(dr.isEmpty(i))continue;const a=lo.optional[s](i);if(a!==void 0)c[s]=a;else throw new Za.ConfigurationError(s,i)}};const IT=dt.EventEmitter,bT=ct,gt=De,wT=mg,Df=Dd,Nf=eT,xf=iT,eu=Tr,OT=Nd,oo=At(),DT=As,NT=Cs(),xT=xd,tu=Ct,UT=Md,su=rl,Be=new bT("UA"),St={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var Pd=class extends IT{static get C(){return St}constructor(t){if(Be.debug("new() [configuration:%o]",t),super(),this._cache={credentials:{}},this._configuration=Object.assign({},su.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=St.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,t===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(t)}catch(s){throw this._status=St.STATUS_NOT_READY,this._error=St.CONFIGURATION_ERROR,s}this._registrator=new wT(this)}get C(){return St}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){Be.debug("start()"),this._status===St.STATUS_INIT?this._transport.connect():this._status===St.STATUS_USER_CLOSED?(Be.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=St.STATUS_INIT,this._transport.connect()):this._status===St.STATUS_READY?Be.debug("UA is in READY status, not restarted"):Be.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){Be.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(t){Be.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(t)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(t,s){Be.debug("call()");const i=new Df(this);return i.connect(t,s),i}sendMessage(t,s,i){Be.debug("sendMessage()");const a=new Nf(this);return a.send(t,s,i),a}sendOptions(t,s,i){Be.debug("sendOptions()");const a=new xf(this);return a.send(t,s,i),a}terminateSessions(t){Be.debug("terminateSessions()");for(const s in this._sessions)this._sessions[s].isEnded()||this._sessions[s].terminate(t)}stop(){if(Be.debug("stop()"),this._dynConfiguration={},this._status===St.STATUS_USER_CLOSED){Be.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const i in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,i)){Be.debug(`closing session ${i}`);try{this._sessions[i].terminate()}catch{}}for(const i in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,i))try{this._applicants[i].close()}catch{}this._status=St.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(t){return oo.normalizeTarget(t,this._configuration.hostport_params)}get(t){switch(t){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:Be.warn('get() | cannot get "%s" parameter in runtime',t);return}}set(t,s){switch(t){case"authorization_user":{this._configuration.authorization_user=String(s);break}case"password":{this._configuration.password=String(s);break}case"realm":{this._configuration.realm=String(s);break}case"ha1":{this._configuration.ha1=String(s),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(s);break}case"display_name":{this._configuration.display_name=s;break}default:return Be.warn('set() | cannot set "%s" parameter in runtime',t),!1}return!0}newTransaction(t){this._transactions[t.type][t.id]=t,this.emit("newTransaction",{transaction:t})}destroyTransaction(t){delete this._transactions[t.type][t.id],this.emit("transactionDestroyed",{transaction:t})}newDialog(t){this._dialogs[t.id]=t}destroyDialog(t){delete this._dialogs[t.id]}newMessage(t,s){this._applicants[t]=t,this.emit("newMessage",s)}newOptions(t,s){this._applicants[t]=t,this.emit("newOptions",s)}destroyMessage(t){delete this._applicants[t]}newRTCSession(t,s){this._sessions[t.id]=t,this.emit("newRTCSession",s)}destroyRTCSession(t){delete this._sessions[t.id]}registered(t){this.emit("registered",t)}unregistered(t){this.emit("unregistered",t)}registrationFailed(t){this.emit("registrationFailed",t)}receiveRequest(t){const s=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){Be.debug("Request-URI does not point to us"),t.method!==gt.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===gt.SIPS){t.reply_sl(416);return}if(eu.checkTransaction(this,t))return;if(s===gt.INVITE?new eu.InviteServerTransaction(this,this._transport,t):s!==gt.ACK&&s!==gt.CANCEL&&new eu.NonInviteServerTransaction(this,this._transport,t),s===gt.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new xf(this).init_incoming(t)}else if(s===gt.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new Nf(this).init_incoming(t)}else if(s===gt.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let i,a;if(t.to_tag)i=this._findDialog(t.call_id,t.from_tag,t.to_tag),i?i.receiveRequest(t):s===gt.NOTIFY?(a=this._findSession(t),a?a.receiveRequest(t):(Be.debug("received NOTIFY request for a non existent subscription"),t.reply(481,"Subscription does not exist"))):s!==gt.ACK&&t.reply(481);else switch(s){case gt.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const n=t.replaces;i=this._findDialog(n.call_id,n.from_tag,n.to_tag),i?(a=i.owner,a.isEnded()?t.reply(603):a.receiveRequest(t)):t.reply(481)}else a=new Df(this),a.init_incoming(t);else Be.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case gt.BYE:t.reply(481);break;case gt.CANCEL:a=this._findSession(t),a?a.receiveRequest(t):Be.debug("received CANCEL request for a non existent session");break;case gt.ACK:break;case gt.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}_findSession({call_id:t,from_tag:s,to_tag:i}){const a=t+s,n=this._sessions[a],r=t+i,h=this._sessions[r];return n||h||null}_findDialog(t,s,i){let a=t+s+i,n=this._dialogs[a];return n||(a=t+i+s,n=this._dialogs[a],n||null)}_loadConfig(t){try{su.load(this._configuration,t)}catch(a){throw a}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=oo.newUUID()),this._configuration.jssip_id=oo.createRandomToken(5);const s=this._configuration.uri.clone();s.user=null,this._configuration.hostport_params=s.toString().replace(/^sip:/i,"");try{this._transport=new OT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=kT.bind(this),this._transport.onconnect=MT.bind(this),this._transport.ondisconnect=PT.bind(this),this._transport.ondata=LT.bind(this)}catch(a){throw Be.warn(a),new DT.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const a=this._configuration.uri.clone();a.user=null,a.clearParams(),a.clearHeaders(),this._configuration.registrar_server=a}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new NT("sip",oo.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(a={}){const n=a.anonymous||null,r=a.outbound||null;let h="<";return n?h+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":h+=this.pub_gruu||this.uri.toString(),r&&(n?!this.temp_gruu:!this.pub_gruu)&&(h+=";ob"),h+=">",h}};const i=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(i.indexOf(a)!==-1?Object.defineProperty(this._configuration,a,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,a,{writable:!1,configurable:!1}));Be.debug("configuration parameters after validation:");for(const a in this._configuration)if(Object.prototype.hasOwnProperty.call(su.settings,a))switch(a){case"uri":case"registrar_server":Be.debug(`- ${a}: ${this._configuration[a]}`);break;case"password":case"ha1":case"authorization_jwt":Be.debug(`- ${a}: NOT SHOWN`);break;default:Be.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}};function kT(c){this.emit("connecting",c)}function MT(c){this._status!==St.STATUS_USER_CLOSED&&(this._status=St.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function PT(c){const t=["nict","ict","nist","ist"];for(const s of t)for(const i in this._transactions[s])Object.prototype.hasOwnProperty.call(this._transactions[s],i)&&this._transactions[s][i].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==St.STATUS_USER_CLOSED&&(this._status=St.STATUS_NOT_READY,this._error=St.NETWORK_ERROR)}function LT(c){const t=c.transport;let s=c.message;if(s=xT.parseMessage(s,this),!!s&&!(this._status===St.STATUS_USER_CLOSED&&s instanceof tu.IncomingRequest)&&UT(s,this,t)){if(s instanceof tu.IncomingRequest)s.transport=t,this.receiveRequest(s);else if(s instanceof tu.IncomingResponse){let i;switch(s.method){case gt.INVITE:i=this._transactions.ict[s.via_branch],i&&i.receiveResponse(s);break;case gt.ACK:break;default:i=this._transactions.nict[s.via_branch],i&&i.receiveResponse(s);break}}}}const $T=Xe(Pd);var pt=[];for(var nu=0;nu<256;++nu)pt.push((nu+256).toString(16).slice(1));function HT(c,t=0){return(pt[c[t+0]]+pt[c[t+1]]+pt[c[t+2]]+pt[c[t+3]]+"-"+pt[c[t+4]]+pt[c[t+5]]+"-"+pt[c[t+6]]+pt[c[t+7]]+"-"+pt[c[t+8]]+pt[c[t+9]]+"-"+pt[c[t+10]]+pt[c[t+11]]+pt[c[t+12]]+pt[c[t+13]]+pt[c[t+14]]+pt[c[t+15]]).toLowerCase()}var ao,FT=new Uint8Array(16);function VT(){if(!ao&&(ao=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ao))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ao(FT)}var jT=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Uf={randomUUID:jT};function kf(c,t,s){if(Uf.randomUUID&&!t&&!c)return Uf.randomUUID();c=c||{};var i=c.random||(c.rng||VT)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){s=s||0;for(var a=0;a<16;++a)t[s+a]=i[a];return t}return HT(i)}var Me=At();const vs=Xe(Me),ru=new Yo("Dialog"),Vs={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class uo{static get C(){return Vs}constructor(t,s,i,a=Vs.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,s instanceof Ct.IncomingResponse&&(a=s.status_code<200?Vs.STATUS_EARLY:Vs.STATUS_CONFIRMED),i==="UAS"){this._id={call_id:s.call_id,local_tag:s.to_tag,remote_tag:s.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._remote_seqnum=s.cseq,this._local_uri=s.parseHeader("to").uri,this._remote_uri=s.parseHeader("from").uri;let n=s.getHeaders("to")[0].split(";")[0];n=n.match(/<([^>]*)>/)[1],this._remote_target=n,this._route_set=s.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(i==="UAC"){this._id={call_id:s.call_id,local_tag:s.from_tag,remote_tag:s.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=a,this._local_seqnum=s.cseq,this._local_uri=s.parseHeader("from").uri,this._remote_uri=s.parseHeader("to").uri;let n=s.getHeaders("to")[0].split(";")[0];n=n.match(/<([^>]*)>/)[1],this._remote_target=n,this._route_set=s.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),ru.debug(`new ${i} dialog created with status ${this._state===Vs.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Vs.STATUS_TERMINATED}update(t,s){this._state=Vs.STATUS_CONFIRMED,ru.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),s==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){ru.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Vs.STATUS_TERMINATED}sendRequest(t,s={}){const i=vs.cloneArray(s.extraHeaders),a=vs.cloneObject(s.eventHandlers),n=s.body||null,r=this._createRequest(t,i,n);return a.onAuthenticated=()=>{this._local_seqnum+=1},new yg(this,r,a).send(),r}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===H.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===H.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,s,i){s=vs.cloneArray(s),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=t===H.CANCEL||t===H.ACK?this._local_seqnum:this._local_seqnum+=1;return new Ct.OutgoingRequest(t,this._remote_target,this._ua,{cseq:a,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},s,i)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===H.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===H.INVITE||t.method===H.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const s=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${s}`]),!1}else{this._uas_pending_reply=!0;const s=()=>{(t.server_transaction.state===Wt.C.STATUS_ACCEPTED||t.server_transaction.state===Wt.C.STATUS_COMPLETED||t.server_transaction.state===Wt.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",s),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",s)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Wt.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===H.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Wt.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}}class qT{constructor(t,s){Yt(this,"plugin",null);Yt(this,"rtcpPeer",null);Yt(this,"handleId",0);Yt(this,"info",null);Yt(this,"joinResult",null);Yt(this,"state",{});Yt(this,"stream",null);Yt(this,"loaded",!1);Yt(this,"aTracks",[]);Yt(this,"vTracks",[]);this.info=t,this.plugin=s,this.rtcpPeer=new RTCPeerConnection({iceServers:[]})}get memberInfo(){return{stream:this.stream,joinResult:this.joinResult,sender:this.handleId,type:"subscriber",name:this.info.display,state:this.state,id:this.handleId}}updateMemberState(t){var s;this.state={...this.state,...t||{}},(s=this.plugin)==null||s.session.emit("member:update",this.memberInfo)}updateMemberStateFromMessage(t){var n,r,h,d;const s=(r=(n=t==null?void 0:t.plugindata)==null?void 0:n.data)==null?void 0:r.newStatePublisher,a=((d=(h=t==null?void 0:t.plugindata)==null?void 0:h.data)==null?void 0:d.publisher_state).find(_=>_.id===s);this.updateMemberState(a==null?void 0:a.state)}hangup(){this.rtcpPeer&&(this.rtcpPeer.close(),this.rtcpPeer=null),this.stream&&this.stream.getTracks().forEach(t=>{t.stop()})}}class Zt{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(t){return Zt.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind===t):[]}static async getMicrophoneList(){return(await Zt.getDevices("audioinput")).map((s,i)=>({...s,deviceId:s.deviceId,label:s.label||`microphone ${i+1}`,kind:s.kind,groupId:s.groupId}))}static async getSpeakerList(){return(await Zt.getDevices("audiooutput")).map((s,i)=>({...s,deviceId:s.deviceId,label:s.label||`speaker ${i+1}`,kind:s.kind,groupId:s.groupId}))}static async getCameraList(){return(await Zt.getDevices("videoinput")).map((s,i)=>({...s,deviceId:s.deviceId,label:s.label||`camera ${i+1}`,kind:s.kind,groupId:s.groupId}))}static stopStreamTracks(t){t&&t.getTracks().forEach(s=>{s.stop()})}static async getMediaFromInputs({videoInput:t,audioInput:s}){let i,a;t==="default"?i=!0:t&&t!=="default"&&(i={deviceId:{exact:t}}),s==="default"?a=!0:s&&s!=="default"&&(a={deviceId:{exact:s}});const n={audio:a,video:i};return Zt.getUserMedia(n)}static async getUserMedia(t){return await navigator.mediaDevices.getUserMedia(t)}static async changeAudioOutput(t,s){if(!(!t||!s))if(typeof t.sinkId<"u")try{await t.setSinkId(s)}catch(i){let a=i;i.name==="SecurityError"&&(a=`You need to use HTTPS for selecting audio output device: ${i}`),console.error(a)}else console.warn("Browser does not support output device selection.")}static toggleAudioMute(t){const s=t.getAudioTracks();if(s.length!==0)return s.forEach(i=>{i.enabled=!i.enabled}),s[0].enabled}static toggleVideoMute(t){const s=t.getVideoTracks();if(s.length!==0)return s.forEach(i=>{i.enabled=!i.enabled}),s[0].enabled}static async getStream(t={video:!0,audio:!0}){try{const s=await navigator.mediaDevices.getUserMedia(t);let i=s.getTracks();return t.video?i=s.getVideoTracks():t.audio&&(i=s.getAudioTracks()),i.length===0?{stream:s,track:null}:{stream:s,track:i[0]}}catch(s){return console.warn(s),{stream:null,track:null}}}}var BT=Cs();const In=Xe(BT),kt={LEAVE:"Leave",DETACH:"Detach",AUDIO_CHANGE:"AudioChange",VIDEO_CHANGE:"VideoChange",STATE:"State",ICE:"Ice",CONFIGURE:"Configure",TRICKLE:"Trickle",SUBSCRIBER:"Subscriber",PUBLISHER:"Publisher"},Z=new Yo("JanusSession"),GT="/opt/recordings/",se={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},co=["audio","video"];class Vo extends dt.EventEmitter{static get C(){return se}constructor(t){Z.debug("new"),super(),this._id=null,this._ua=t,this._status=se.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:H.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._candidates=[],this.publishers=[],this.private_id=null,this.memberList={},this.myFeedList=[],this.display_name="",this.stunServers=[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}],this.opaque_id=this.generateOpaqueId(),this.screen_share_opaque_id=this.generateOpaqueId(),this._data={},this.isAudioOn=!0,this.isVideoOn=!0,this.mediaConstraints={}}get C(){return se}get causes(){return H.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case se.STATUS_NULL:case se.STATUS_INVITE_SENT:case se.STATUS_1XX_RECEIVED:case se.STATUS_INVITE_RECEIVED:case se.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case se.STATUS_ANSWERED:case se.STATUS_WAITING_FOR_ACK:case se.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case se.STATUS_CANCELED:case se.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(t){return`PTYPE: ${t}`}generateOpaqueId(){return`videoroomtest-${kf().replace(/-/g,"").slice(0,12)}`}connect(t,s,i={},a){Z.debug("connect()"),this.display_name=s;const n=t,r=Me.cloneObject(i.eventHandlers),h=Me.cloneArray(i.extraHeaders),d=Me.cloneObject(i.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={...d};const _=i.mediaStream||null,g=Me.cloneObject(i.pcConfig,{iceServers:[]}),T=i.rtcConstraints||null,S=i.rtcOfferConstraints||null;if(this._rtcOfferConstraints=S,this._rtcAnswerConstraints=i.rtcAnswerConstraints||null,this._data=i.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==se.STATUS_NULL)throw new qs.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new qs.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),this.room_id=t.user,this.target=t,!t)throw new TypeError(`Invalid target: ${n}`);this._sessionTimers.enabled&&Me.isDecimal(i.sessionTimersExpires)&&(i.sessionTimersExpires>=H.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=i.sessionTimersExpires:this._sessionTimers.defaultExpires=H.SESSION_EXPIRES);for(const A in r)Object.prototype.hasOwnProperty.call(r,A)&&this.on(A,r[A]);this._from_tag=Me.newTag();const E=i.anonymous||!1,C={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:E,outbound:!0}),E?(C.from_display_name="Anonymous",C.from_uri=new In("sip","anonymous","anonymous.invalid"),h.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),h.push("Privacy: id")):i.fromUserName&&(C.from_uri=new In("sip",i.fromUserName,this._ua.configuration.uri.host),h.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),i.fromDisplayName&&(C.from_display_name=i.fromDisplayName),h.push(`Contact: ${this._contact}`),h.push("Content-Type: application/json"),this._sessionTimers.enabled&&h.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Ct.InitialOutgoingInviteRequest(t,this._ua,C,h),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(g,T),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,a&&a(this),this._newJanusSession("local",this._request),this._sendInitialRequest(d,S,_)}_overrideSenderTracks(t,s){t.getTracks().forEach(i=>{s.getSenders().forEach(async n=>{n.track.kind===i.kind&&(i.kind==="audio"&&!this.isAudioOn&&(i.enabled=!1),i.kind==="video"&&!this.isVideoOn&&(i.enabled=!1),await n.replaceTrack(i))})})}init_incoming(t,s){Z.debug("init_incoming()");let i;const a=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&a!=="application/sdp"){t.reply(415);return}if(this._status=se.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(i=t.getHeader("expires")*1e3),t.to_tag=Me.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=se.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,H.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),i&&(this._timers.expiresTimer=setTimeout(()=>{this._status===se.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,H.causes.EXPIRES))},i)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,s&&s(this),this._newJanusSession("remote",t),this._status!==se.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){Z.debug("answer()");const s=this._request,i=Me.cloneArray(t.extraHeaders),a=Me.cloneObject(t.mediaConstraints),n=t.mediaStream||null,r=Me.cloneObject(t.pcConfig,{iceServers:[]}),h=t.rtcConstraints||null,d=t.rtcAnswerConstraints||null,_=Me.cloneObject(t.rtcOfferConstraints);let g,T=!1,S=!1,E=!1,C=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new qs.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==se.STATUS_WAITING_FOR_ANSWER)throw new qs.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Me.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=H.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=H.SESSION_EXPIRES),this._status=se.STATUS_ANSWERED,!this._createDialog(s,"UAS")){s.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),i.unshift(`Contact: ${this._contact}`);const A=s.parseSDP();Array.isArray(A.media)||(A.media=[A.media]);for(const R of A.media)R.type==="audio"&&(T=!0,(!R.direction||R.direction==="sendrecv")&&(E=!0)),R.type==="video"&&(S=!0,(!R.direction||R.direction==="sendrecv")&&(C=!0));if(n&&a.audio===!1){g=n.getAudioTracks();for(const R of g)n.removeTrack(R)}if(n&&a.video===!1){g=n.getVideoTracks();for(const R of g)n.removeTrack(R)}!n&&a.audio===void 0&&(a.audio=E),!n&&a.video===void 0&&(a.video=C),!n&&!T&&!_.offerToReceiveAudio&&(a.audio=!1),!n&&!S&&!_.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(r,h),Promise.resolve().then(()=>{if(n)return n;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(R=>{throw this._status===se.STATUS_TERMINATED?new Error("terminated"):(s.reply(480),this._failed("local",null,H.causes.USER_DENIED_MEDIA_ACCESS),Z.warn('emit "getusermediafailed" [error:%o]',R),this.emit("getusermediafailed",R),new Error("getUserMedia() failed"))})}).then(R=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=R,R&&R.getTracks().forEach(F=>{this._connection.addTrack(F,R)})}).then(()=>{if(this._late_sdp)return;const R={originator:"remote",type:"offer",sdp:s.body};Z.debug('emit "sdp"'),this.emit("sdp",R);const F=new RTCSessionDescription({type:"offer",sdp:R.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(F)).catch(I=>{throw s.reply(488),this._failed("system",null,H.causes.WEBRTC_ERROR),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',I),this.emit("peerconnection:setremotedescriptionfailed",I),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(s),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw s.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",d).catch(()=>{throw s.reply(500),new Error("_createLocalDescription() failed")})}).then(R=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(s,i),s.reply(200,null,i,R,()=>{this._status=se.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(s,R),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,H.causes.CONNECTION_ERROR)})}).catch(R=>{this._status!==se.STATUS_TERMINATED&&Z.warn(R)})}terminate(t={}){Z.debug("terminate()");const s=t.cause||H.causes.BYE,i=Me.cloneArray(t.extraHeaders),a=t.body;let n,r=t.status_code,h=t.reason_phrase;if(this._status===se.STATUS_TERMINATED)throw new qs.InvalidStateError(this._status);switch(this._status){case se.STATUS_NULL:case se.STATUS_INVITE_SENT:case se.STATUS_1XX_RECEIVED:if(Z.debug("canceling session"),r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(h=h||H.REASON_PHRASE[r]||"",n=`SIP ;cause=${r} ;text="${h}"`),this._status===se.STATUS_NULL||this._status===se.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=n):this._status===se.STATUS_1XX_RECEIVED&&this._request.cancel(n),this._status=se.STATUS_CANCELED,this._failed("local",null,H.causes.CANCELED);break;case se.STATUS_WAITING_FOR_ANSWER:case se.STATUS_ANSWERED:if(Z.debug("rejecting session"),r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,h,i,a),this._failed("local",null,H.causes.REJECTED);break;case se.STATUS_WAITING_FOR_ACK:case se.STATUS_CONFIRMED:if(Z.debug("terminating session"),h=t.reason_phrase||H.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&i.push(`Reason: SIP ;cause=${r}; text="${h}"`),this._status===se.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Wt.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:_})=>{_===H.ACK&&(this.sendRequest(H.BYE,{extraHeaders:i,body:a}),d.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Wt.C.STATUS_TERMINATED&&(this.sendRequest(H.BYE,{extraHeaders:i,body:a}),d.terminate(),this.closeSession())}),this._ended("local",null,s),this._dialog=d,this._ua.newDialog(d)}else{const d={janus:"leave"},_=["Content-Type: application/json",this.getPTypeHeader(kt.LEAVE)];this.sendRequest(H.BYE,{extraHeaders:_,body:JSON.stringify(d)}),this.closeSession(),this._ended("local",null,s)}}}configureMedia(t){this.isAudioOn=t.audio,this.isVideoOn=t.video}enableAudio(t){const s={janus:"message",body:{audio:t},handle_id:this.handle_id,session_id:this.session_id},i=["Content-Type: application/json",this.getPTypeHeader(kt.AUDIO_CHANGE)];this.sendRequest(H.INFO,{extraHeaders:i,body:JSON.stringify(s),eventHandlers:{onSuccessResponse:async a=>{a.status_code===200&&(this._ua.emit("changeAudioState",t),this.sendStateMessage({audio:t}))}}})}startAudio(){Zt.toggleAudioMute(this.stream),this._toggleMuteAudio(!1),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Zt.toggleAudioMute(this.stream),this._toggleMuteAudio(!0),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(t){const s={janus:"message",body:{video:t},handle_id:this.handle_id,session_id:this.session_id},i=["Content-Type: application/json",this.getPTypeHeader(kt.VIDEO_CHANGE)];this.sendRequest(H.INFO,{extraHeaders:i,body:JSON.stringify(s),eventHandlers:{onSuccessResponse:async a=>{a.status_code===200&&(this._ua.emit("changeVideoState",t),this.sendStateMessage({video:t}))}}})}startVideo(){Zt.toggleVideoMute(this.stream),this._toggleMuteVideo(!1),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Zt.toggleVideoMute(this.stream),this._toggleMuteVideo(!0),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(t){const s={janus:"message",body:{request:"state",data:t},handle_id:this.handle_id,session_id:this.session_id},i=["Content-Type: application/json",this.getPTypeHeader(kt.STATE)];this.sendRequest(H.INFO,{extraHeaders:i,body:JSON.stringify(s)})}sendInfo(t,s,i={}){if(Z.debug("sendInfo()"),this._status!==se.STATUS_CONFIRMED&&this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_1XX_RECEIVED)throw new qs.InvalidStateError(this._status);new Iu(this).send(t,s,i)}mute(t={audio:!0,video:!1}){Z.debug("mute()");let s=!1,i=!1;this._audioMuted===!1&&t.audio&&(s=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(i=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(s===!0||i===!0)&&this._onmute({audio:s,video:i})}unmute(t={audio:!0,video:!0}){Z.debug("unmute()");let s=!1,i=!1;this._audioMuted===!0&&t.audio&&(s=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(i=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(s===!0||i===!0)&&this._onunmute({audio:s,video:i})}hold(t={},s){if(Z.debug("hold()"),this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const i={succeeded:()=>{s&&s()},failed:()=>{this.terminate({cause:H.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:i,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:i,extraHeaders:t.extraHeaders}),!0}unhold(t={},s){if(Z.debug("unhold()"),this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const i={succeeded:()=>{s&&s()},failed:()=>{this.terminate({cause:H.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:i,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:i,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},s){Z.debug("renegotiate()");const i=t.rtcOfferConstraints||null;if(this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const a={succeeded:()=>{s&&s()},failed:()=>{this.terminate({cause:H.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:i,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:i,extraHeaders:t.extraHeaders}),!0}refer(t,s){Z.debug("refer()");const i=t;if(this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${i}`);const a=new Vg(this);a.sendRefer(t,s);const n=a.id;return this._referSubscribers[n]=a,a.on("requestFailed",()=>{delete this._referSubscribers[n]}),a.on("accepted",()=>{delete this._referSubscribers[n]}),a.on("failed",()=>{delete this._referSubscribers[n]}),a}sendRequest(t,s){return Z.debug("sendRequest()"),this._dialog.sendRequest(t,s)}receiveNotify(t){Z.debug("receiveRequest()")}receiveRequest(t){if(Z.debug("receiveRequest()"),t.method===H.CANCEL)(this._status===se.STATUS_WAITING_FOR_ANSWER||this._status===se.STATUS_ANSWERED)&&(this._status=se.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,H.causes.CANCELED));else switch(t.method){case H.ACK:if(this._status!==se.STATUS_WAITING_FOR_ACK)return;if(this._status=se.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:H.causes.MISSING_SDP,status_code:400});break}const s={originator:"remote",type:"answer",sdp:t.body};Z.debug('emit "sdp"'),this.emit("sdp",s);const i=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(a=>{this.terminate({cause:H.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",t);break;case H.BYE:this._status===se.STATUS_CONFIRMED||this._status===se.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,H.causes.BYE)):this._status===se.STATUS_INVITE_RECEIVED||this._status===se.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,H.causes.BYE)):t.reply(403,"Wrong Status");break;case H.INVITE:this._status===se.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case H.INFO:if(this._status===se.STATUS_1XX_RECEIVED||this._status===se.STATUS_WAITING_FOR_ANSWER||this._status===se.STATUS_ANSWERED||this._status===se.STATUS_WAITING_FOR_ACK||this._status===se.STATUS_CONFIRMED){const s=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;s&&s.match(/^application\/dtmf-relay/i)?new Dg(this).init_incoming(t):s!==void 0?new Iu(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case H.UPDATE:this._status===se.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case H.REFER:this._status===se.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case H.NOTIFY:this._status===se.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){Z.warn("onTransportError()"),this._status!==se.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:H.causes.CONNECTION_ERROR,cause:H.causes.CONNECTION_ERROR})}onRequestTimeout(){Z.warn("onRequestTimeout()"),this._status!==se.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:H.causes.REQUEST_TIMEOUT,cause:H.causes.REQUEST_TIMEOUT})}onDialogError(){Z.warn("onDialogError()"),this._status!==se.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:H.causes.DIALOG_ERROR,cause:H.causes.DIALOG_ERROR})}newDTMF(t){Z.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){Z.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Z.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Z.debug("_isReadyToReOffer() | session not established yet"),!1):(Z.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Z.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Z.debug("close() | closing local MediaStream"),Me.closeMediaStream(this._localMediaStream)),this._status!==se.STATUS_TERMINATED){if(this._status=se.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){Z.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,s){let i=$i.T1;function a(){this._status===se.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],s),i<$i.T2&&(i=i*2,i>$i.T2&&(i=$i.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),i))}this._timers.invite2xxTimer=setTimeout(a.bind(this),i)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===se.STATUS_WAITING_FOR_ACK&&(Z.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(H.BYE),this._ended("remote",null,H.causes.NO_ACK))},$i.TIMER_H)}_createRTCConnection(t,s){this.stunServers,this._connection=new RTCPeerConnection(t,s),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:H.causes.RTP_TIMEOUT,status_code:408,reason_phrase:H.causes.RTP_TIMEOUT})});let i;const a=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(i),i=setTimeout(()=>{this.lastTrickleReceived=!0,this.subscribeSent&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{}))},500))};this._connection.onicecandidate=a,Z.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,s){if(Z.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const i=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?i.createOffer(s).catch(a=>(Z.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):i.createAnswer(s).catch(a=>(Z.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>(this.jsepOffer=a,i.setLocalDescription(a).catch(n=>(this._rtcReady=!0,Z.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',n),this.emit("peerconnection:setlocaldescriptionfailed",n),Promise.reject(n))))).then(()=>{const a=s&&s.iceRestart;if(i.iceGatheringState==="complete"&&!a||i.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const n={originator:"local",type:t,sdp:i.localDescription.sdp};return Z.debug('emit "sdp"'),this.emit("sdp",n),Promise.resolve(n.sdp)}return new Promise(n=>{let r=!1,h,d;this._iceReady=!1;const _=()=>{i.removeEventListener("icecandidate",h),i.removeEventListener("icegatheringstatechange",d),r=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:t,sdp:i.localDescription.sdp};Z.debug('emit "sdp"'),this.emit("sdp",g),n(g.sdp)};i.addEventListener("icecandidate",h=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:_}):r||_()}),i.addEventListener("icegatheringstatechange",d=()=>{i.iceGatheringState==="complete"&&!r&&_()})})})}_createDialog(t,s,i){const a=s==="UAS"?t.to_tag:t.from_tag,n=s==="UAS"?t.from_tag:t.to_tag,r=t.call_id+a+n;let h=this._earlyDialogs[r];if(i)return h?!0:(h=new uo(this,t,s,uo.C.STATUS_EARLY),h.error?(Z.debug(h.error),this._failed("remote",t,H.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=h,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,h)return h.update(t,s),this._dialog=h,delete this._earlyDialogs[r],!0;const d=new uo(this,t,s);return d.error?(Z.debug(d.error),this._failed("remote",t,H.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(t){Z.debug("receiveReinvite()");const s=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,i={request:t,callback:void 0,reject:n.bind(this)};let a=!1;function n(h={}){a=!0;const d=h.status_code||403,_=h.reason_phrase||"",g=Me.cloneArray(h.extraHeaders);if(this._status!==se.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,_,g)}if(this.emit("reinvite",i),a)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(h=>{r.call(this,h)}).catch(()=>{t.reply(500)});return}if(s!=="application/sdp"){Z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(h=>{this._status!==se.STATUS_TERMINATED&&r.call(this,h)}).catch(h=>{Z.warn(h)});function r(h){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),this._late_sdp&&(h=this._mangleOffer(h)),t.reply(200,null,d,h,()=>{this._status=se.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,h),this._setACKTimer()}),typeof i.callback=="function"&&i.callback()}}_receiveUpdate(t){Z.debug("receiveUpdate()");const s=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,i={request:t,callback:void 0,reject:n.bind(this)};let a=!1;function n(h={}){a=!0;const d=h.status_code||403,_=h.reason_phrase||"",g=Me.cloneArray(h.extraHeaders);if(this._status!==se.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,_,g)}if(this.emit("update",i),a)return;if(!t.body){r.call(this,null);return}if(s!=="application/sdp"){Z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(h=>{this._status!==se.STATUS_TERMINATED&&r.call(this,h)}).catch(h=>{Z.warn(h)});function r(h){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),t.reply(200,null,d,h),typeof i.callback=="function"&&i.callback()}}_processInDialogSdpOffer(t){Z.debug("_processInDialogSdpOffer()");const s=t.parseSDP();let i=!1;for(const r of s.media){if(co.indexOf(r.type)===-1)continue;const h=r.direction||s.direction||"sendrecv";if(h==="sendonly"||h==="inactive")i=!0;else{i=!1;break}}const a={originator:"remote",type:"offer",sdp:t.body};Z.debug('emit "sdp"'),this.emit("sdp",a);const n=new RTCSessionDescription({type:"offer",sdp:a.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(n).catch(r=>{throw t.reply(488),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',r),this.emit("peerconnection:setremotedescriptionfailed",r),r})}).then(()=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&i===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&i===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(r=>{throw t.reply(500),Z.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',r),r})}).catch(r=>{Z.warn("_processInDialogSdpOffer() failed [error: %o]",r)}),this._connectionPromiseQueue}_receiveRefer(t){if(Z.debug("receiveRefer()"),!t.refer_to){Z.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==H.SIP){Z.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const s=new Lg(this,t.cseq);Z.debug('emit "refer"'),this.emit("refer",{request:t,accept:(n,r)=>{i.call(this,n,r)},reject:()=>{a.call(this)}});function i(n,r={}){if(n=typeof n=="function"?n:null,this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED)return!1;const h=new Vo(this._ua);if(h.on("progress",({response:d})=>{s.notify(d.status_code,d.reason_phrase)}),h.on("accepted",({response:d})=>{s.notify(d.status_code,d.reason_phrase)}),h.on("_failed",({message:d,cause:_})=>{d?s.notify(d.status_code,d.reason_phrase):s.notify(487,_)}),t.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));r.extraHeaders=Me.cloneArray(r.extraHeaders),r.extraHeaders.push(`Replaces: ${d}`)}h.connect(t.refer_to.uri.toAor(),r,n)}function a(){s.notify(603)}}_receiveNotify(t){switch(Z.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let s,i;if(t.event.params&&t.event.params.id)s=t.event.params.id,i=this._referSubscribers[s];else if(Object.keys(this._referSubscribers).length===1)i=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!i){t.reply(481,"Subscription does not exist");return}i.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){Z.debug("receiveReplaces()");function s(a){if(this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED)return!1;const n=new Vo(this._ua);n.on("confirmed",()=>{this.terminate()}),n.init_incoming(t,a)}function i(){Z.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:a=>{s.call(this,a)},reject:()=>{i.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(t,s,i){this.ackSent=!1,this.publisherSubscribeSent=!1;const a=new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:n=>{this._request=n},onReceiveResponse:n=>{this._receiveInviteResponse(n)}});Promise.resolve().then(()=>{if(i)return i;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(n=>{throw this._status===se.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,H.causes.USER_DENIED_MEDIA_ACCESS),Z.warn('emit "getusermediafailed" [error:%o]',n),this.emit("getusermediafailed",n),n)})}).then(n=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=n,n&&n.getTracks().forEach(r=>{this._connection.addTrack(r,n)}),this._connecting(this._request),this._createLocalDescription("offer",s).catch(r=>{throw this._failed("local",null,H.causes.WEBRTC_ERROR),r})}).then(n=>{if(this._is_canceled||this._status===se.STATUS_TERMINATED)throw new Error("terminated");const r={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},h=JSON.stringify(r);this._request.body=h,this._status=se.STATUS_INVITE_SENT,Z.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(n=>{this._status!==se.STATUS_TERMINATED&&Z.warn(n)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async changeMediaConstraints(t){this.mediaConstraints={...t},await this.processPlugins(),this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}async loadStream(){const t={};this.isAudioOn?this.mediaConstraints.audio?t.audio=this.mediaConstraints.audio:t.audio=!0:t.audio=!1,this.isVideoOn?this.mediaConstraints.video?t.video=this.mediaConstraints.video:t.video=!0:t.video=!1;let s=null;try{s=await navigator.mediaDevices.getUserMedia(t)}catch{try{t.video=!1,s=await navigator.mediaDevices.getUserMedia(t)}catch{t.audio=!1,t.video=!1,s=await navigator.mediaDevices.getUserMedia(t)}}return s}addTracks(t){this._connection.getSenders().forEach(s=>{this._connection.removeTrack(s)}),t.forEach(s=>{this._connection.addTrack(s)})}getRecordFileName(){return GT+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let t=0;t<this.iceCandidates.length;t++)await this._connection.addIceCandidate(this.iceCandidates[t]);this.iceCandidates=[]}async _sendConfigureMessage(t){const s=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handle_id,session_id:this.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...t},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...s]},n=["Content-Type: application/json",this.getPTypeHeader(kt.ICE)];this.sendRequest(H.INFO,{extraHeaders:n,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async r=>{this.isConfigureSent=!0;const d=r.data.split(`\r
|
|
135
|
+
`),_=d[d.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendMemberStartMessage(t,s){const i={janus:"message",body:{request:"start",room:this.room_id},handle_id:t.handleId,session_id:this.session_id,jsep:s},a=["Content-Type: application/json",this.getPTypeHeader(kt.CONFIGURE)];this.sendRequest(H.INFO,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async n=>{n.status_code===200&&await t.rtcpPeer.setLocalDescription(s)}}})}_sendTrickleMessage(t){const i={trickles:[...t.map(n=>({janus:"trickle",candidate:n,handle_id:this.handle_id,session_id:this.session_id}))]},a=[this.getPTypeHeader(kt.TRICKLE)];this.sendRequest(H.INFO,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async n=>{}}})}async _answerAttachedStream(t,s){let i=null;const a=async d=>{if(!t.rtcpPeer||t.loaded)return;{t.loaded=!0;const E={audio:!0,video:!0};await new Promise(C=>{setTimeout(C,100)}),i=await t.rtcpPeer.createAnswer(E),this._sendMemberStartMessage(t,i)}const _=d.streams[0].getAudioTracks(),g=d.streams[0].getVideoTracks(),T=[];_[0]&&T.push(_[0]),g[0]&&T.push(g[0]);const S=new MediaStream(T);t.stream=S,this._ua.emit("memberJoin",t.memberInfo)};let n,r=[];const h=d=>{t.rtcpPeer.signalingState!=="stable"&&t.rtcpPeer.signalingState!=="have-local-offer"||(r.push(d.candidate||null),clearTimeout(n),n=setTimeout(()=>{this._sendTrickleMessage(r)},500))};t.rtcpPeer=new RTCPeerConnection,t.rtcpPeer.ontrack=a,t.rtcpPeer.onicecandidate=h,t.rtcpPeer.sender=s.sender,await t.rtcpPeer.setRemoteDescription(s.jsep)}_sendJoinMemberRequest(t){const s={janus:"message",body:{request:"join",room:this.room_id,feed:t.info.id,ptype:"subscriber"},handle_id:t.handleId,session_id:this.session_id},i=[this.getPTypeHeader(kt.SUBSCRIBER)];this.sendRequest(H.SUBSCRIBE,{extraHeaders:i,body:JSON.stringify(s),eventHandlers:{onSuccessResponse:async a=>{var n,r;if(a.status_code===200){const h=JSON.parse(a.body);(r=(n=h==null?void 0:h.plugindata)==null?void 0:n.data)!=null&&r.id&&await this._answerAttachedStream(t,h)}}}})}_attachMember(t){const s={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},i=[this.getPTypeHeader(kt.SUBSCRIBER)];this.sendRequest(H.INFO,{extraHeaders:i,body:JSON.stringify(s),eventHandlers:{onSuccessResponse:async a=>{if(a.status_code===200){const r=JSON.parse(a.body).data.id;t.handleId=r,this._sendJoinMemberRequest(t)}}}})}_detachMember(t){const s={janus:"detach",handle_id:t.handleId,session_id:this.session_id},i=[this.getPTypeHeader(kt.SUBSCRIBER)];this.sendRequest(H.INFO,{extraHeaders:i,body:JSON.stringify(s)}),Zt.stopStreamTracks(t.memberInfo.stream),this._ua.emit("memberHangup",t.memberInfo)}receivePublishers(t){var i,a,n,r,h,d,_,g;const s={...this.memberList};(a=(i=t==null?void 0:t.plugindata)==null?void 0:i.data)==null||a.publishers.forEach(T=>{delete s[T.id],!this.memberList[T.id]&&!this.myFeedList.includes(T.id)&&T.clientID!==this.client_id&&(this.memberList[T.id]=new qT(T,this),this._attachMember(this.memberList[T.id]))}),((r=(n=t==null?void 0:t.plugindata)==null?void 0:n.data)==null?void 0:r.videoroom)==="synced"&&Object.keys(s).forEach(T=>{s[T].hangup(),delete this.memberList[T]}),this.publishers=(d=(h=t==null?void 0:t.plugindata)==null?void 0:h.data)==null?void 0:d.publishers,this.private_id=(g=(_=t==null?void 0:t.plugindata)==null?void 0:_.data)==null?void 0:g.private_id}receiveUnpublished(t){const s=this.memberList[t];s&&(s.hangup(),this._detachMember(s),delete this.memberList[t])}closeSession(){this.stream&&this.stream.getTracks().forEach(s=>{s.stop()}),Object.values(this.memberList).forEach(s=>{s.hangup(),this._detachMember(s)}),this._ua.emit("conferenceEnd",this.id)}async processPlugins(){const t=this._ua.processStreamPlugins;let s=await this.loadStream();for(const i of t)s=await i.process(s);this.stream.getTracks().forEach(i=>{this.stream.removeTrack(i),i.stop()}),s.getTracks().forEach(i=>{this.stream.addTrack(i)})}async resyncPlugins(t){const s=this._ua.processStreamPlugins.filter(i=>i.type===t);for(const i of s)i.running&&i.terminate();if(t==="video"){let i=await this.loadStream();for(const a of s)a.running&&(i=await a.start(i));this.stream.getTracks().forEach(a=>{this.stream.removeTrack(a),a.stop()}),i.getTracks().forEach(a=>{this.stream.addTrack(a)}),this._overrideSenderTracks(this.stream,this._connection),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}else{const i=this._ua.newStreamPlugins.find(h=>h.type===t);let n=i.getStream().clone();for(const h of s)h.running&&(n=await h.start(n));const r=i.getConnection();this._overrideSenderTracks(n,r),this._ua.emit("changePluginStream",{type:t,stream:n})}}stopProcessPlugins(t){const s=this._ua.processStreamPlugins.filter(i=>i.type===t);for(const i of s)i.running&&i.kill()}_receiveInviteResponse(t){if(Z.debug("receiveInviteResponse()"),this._dialog&&t.status_code>=200&&t.status_code<=299&&!this.ackSent)if(this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.ackSent=!0,this.sendRequest(H.ACK);return}else{const s=new uo(this,t,"UAC");if(s.error!==void 0){Z.debug(s.error);return}this.sendRequest(H.ACK),this.sendRequest(H.BYE);return}if(this.ackSent&&!this.publisherSubscribeSent){const s=JSON.parse(t.body);this.setupMediaStream().then(()=>{this.session_id=s.session_id,this.handle_id=s.data.id,this.client_id=kf();const i={janus:"message",body:{request:"join",room:this.room_id,ptype:"publisher",display:this.display_name,clientID:this.client_id,opaque_id:this.opaque_id},handle_id:this.handle_id},a=[this.getPTypeHeader(kt.PUBLISHER)];this.sendRequest(H.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async n=>{var r,h,d,_;if(n.status_code===200){if(this.subscribeSent=!0,n.body)try{const g=JSON.parse(n.body)||{};((h=(r=g.plugindata)==null?void 0:r.data)==null?void 0:h.videoroom)==="joined"&&this.myFeedList.push(g.plugindata.data.id),(_=(d=g.plugindata)==null?void 0:d.data)!=null&&_.publishers&&this.receivePublishers(g)}catch(g){console.error(g)}this.lastTrickleReceived&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{})),this._ua.emit("conferenceStart")}}}}),this.publisherSubscribeSent=!0})}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==se.STATUS_INVITE_SENT&&this._status!==se.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(t.status_code):this._status=se.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){Z.debug("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=se.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const s={originator:"remote",type:"answer",sdp:t.body};Z.debug('emit "sdp"'),this.emit("sdp",s);const i=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).then(()=>this._progress("remote",t)).catch(a=>{Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(this._status=se.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,H.causes.MISSING_SDP),this._failed("remote",t,H.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;break}default:{const s=Me.sipErrorCause(t.status_code);this._failed("remote",t,s)}}}_sendReinvite(t={}){Z.debug("sendReinvite()");const s=Me.cloneArray(t.extraHeaders),i=Me.cloneObject(t.eventHandlers),a=t.rtcOfferConstraints||this._rtcOfferConstraints||null;let n=!1;s.push(`Contact: ${this._contact}`),s.push("Content-Type: application/sdp"),this._sessionTimers.running&&s.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(d=>{d=this._mangleOffer(d);const _={originator:"local",type:"offer",sdp:d};Z.debug('emit "sdp"'),this.emit("sdp",_),this.sendRequest(H.INVITE,{extraHeaders:s,body:d,eventHandlers:{onSuccessResponse:g=>{r.call(this,g),n=!0},onErrorResponse:g=>{h.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{h()});function r(d){if(this._status===se.STATUS_TERMINATED||(this.sendRequest(H.ACK),n))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){h.call(this);return}}else{h.call(this);return}const _={originator:"remote",type:"answer",sdp:d.body};Z.debug('emit "sdp"'),this.emit("sdp",_);const g=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{i.succeeded&&i.succeeded(d)}).catch(T=>{h.call(this),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function h(d){i.failed&&i.failed(d)}}_sendUpdate(t={}){Z.debug("sendUpdate()");const s=Me.cloneArray(t.extraHeaders),i=Me.cloneObject(t.eventHandlers),a=t.rtcOfferConstraints||this._rtcOfferConstraints||null,n=t.sdpOffer||!1;let r=!1;s.push(`Contact: ${this._contact}`),this._sessionTimers.running&&s.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),n?(s.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",a)).then(_=>{_=this._mangleOffer(_);const g={originator:"local",type:"offer",sdp:_};Z.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest(H.UPDATE,{extraHeaders:s,body:_,eventHandlers:{onSuccessResponse:T=>{h.call(this,T),r=!0},onErrorResponse:T=>{d.call(this,T)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{d.call(this)})):this.sendRequest(H.UPDATE,{extraHeaders:s,eventHandlers:{onSuccessResponse:_=>{h.call(this,_)},onErrorResponse:_=>{d.call(this,_)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function h(_){if(this._status!==se.STATUS_TERMINATED&&!r)if(this._handleSessionTimersInIncomingResponse(_),n){if(_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const g={originator:"remote",type:"answer",sdp:_.body};Z.debug('emit "sdp"'),this.emit("sdp",g);const T=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(T)).then(()=>{i.succeeded&&i.succeeded(_)}).catch(S=>{d.call(this),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),this.emit("peerconnection:setremotedescriptionfailed",S)})}else i.succeeded&&i.succeeded(_)}function d(_){i.failed&&i.failed(_)}}_acceptAndTerminate(t,s,i){Z.debug("acceptAndTerminate()");const a=[];s&&(i=i||H.REASON_PHRASE[s]||"",a.push(`Reason: SIP ;cause=${s}; text="${i}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(H.ACK),this.sendRequest(H.BYE,{extraHeaders:a})),this._status=se.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=Mt.parse(t),this._localHold&&!this._remoteHold){Z.debug("mangleOffer() | me on hold, mangling offer");for(const s of t.media)co.indexOf(s.type)!==-1&&(s.direction?s.direction==="sendrecv"?s.direction="sendonly":s.direction==="recvonly"&&(s.direction="inactive"):s.direction="sendonly")}else if(this._localHold&&this._remoteHold){Z.debug("mangleOffer() | both on hold, mangling offer");for(const s of t.media)co.indexOf(s.type)!==-1&&(s.direction="inactive")}else if(this._remoteHold){Z.debug("mangleOffer() | remote on hold, mangling offer");for(const s of t.media)co.indexOf(s.type)!==-1&&(s.direction?s.direction==="sendrecv"?s.direction="recvonly":s.direction==="recvonly"&&(s.direction="inactive"):s.direction="recvonly")}return Mt.write(t)}_setLocalMediaStatus(){let t=!0,s=!0;(this._localHold||this._remoteHold)&&(t=!1,s=!1),this._audioMuted&&(t=!1),this._videoMuted&&(s=!1),this._toggleMuteAudio(!t),this._toggleMuteVideo(!s)}_handleSessionTimersInIncomingRequest(t,s){if(!this._sessionTimers.enabled)return;let i;t.session_expires&&t.session_expires>=H.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,i=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,i="uas"),s.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${i}`),this._sessionTimers.refresher=i==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let s;t.session_expires&&t.session_expires>=H.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,s=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,s="uac"),this._sessionTimers.refresher=s==="uac",this._runSessionTimer()}_runSessionTimer(){const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==se.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Z.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===H.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==se.STATUS_TERMINATED&&(Z.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:H.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const s=this._connection.getSenders().filter(i=>i.track&&i.track.kind==="audio");for(const i of s)i.track.enabled=!t}_toggleMuteVideo(t){const s=this._connection.getSenders().filter(i=>i.track&&i.track.kind==="video");for(const i of s)i.track.enabled=!t}_newJanusSession(t,s){Z.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:t,session:this,request:s})}_connecting(t){Z.debug("session connecting"),Z.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,s){Z.debug("session progress"),Z.debug('emit "progress"'),this.emit("progress",{originator:t,response:s||null})}_accepted(t,s){Z.debug("session accepted"),this._start_time=new Date,Z.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:s||null})}_confirmed(t,s){Z.debug("session confirmed"),this._is_confirmed=!0,Z.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:s||null})}_ended(t,s,i){Z.debug("session ended"),this._end_time=new Date,this._close(),Z.debug('emit "ended"'),this.emit("ended",{originator:t,message:s||null,cause:i})}_failed(t,s,i){Z.debug("session failed"),Z.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:s||null,cause:i}),this._close(),Z.debug('emit "failed"'),this.emit("failed",{originator:t,message:s||null,cause:i})}_onhold(t){Z.debug("session onhold"),this._setLocalMediaStatus(),Z.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){Z.debug("session onunhold"),this._setLocalMediaStatus(),Z.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:s}){Z.debug("session onmute"),this._setLocalMediaStatus(),Z.debug('emit "muted"'),this.emit("muted",{audio:t,video:s})}_onunmute({audio:t,video:s}){Z.debug("session onunmute"),this._setLocalMediaStatus(),Z.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:s})}}class cr{constructor(t){if(this.headers={},t.length>0){let s=!1;const i=t.split(`\r
|
|
136
|
+
`),a=i.shift().split(/\s/);this.protocol=a[0],this.ident=a[1],this.code=a.length>3?parseInt(a[2]):0,this.method=a.length>3?a[3]:a[2],this.body="";for(const n of i){if(n==`-------${this.ident}$`)break;if(n===""){s=!0;continue}if(n&&s)this.body+=`${n}\r
|
|
137
|
+
`;else{const r=n.split(": ");this.addHeader(r[0],r[1].trim())}}}else this.ident=Me.createRandomToken(12),this.protocol="MSRP"}addHeader(t,s){this.headers[t]=s}getHeader(t){return this.headers[t]}toString(){let t=`${this.protocol} ${this.ident} ${this.code} ${this.method}`.replaceAll(/null\s|undefined\s/ig,"")+`\r
|
|
138
|
+
`;for(const s in this.headers)t+=`${s}: ${this.headers[s]}\r
|
|
139
139
|
`;return this.body&&(t+=`\r
|
|
140
140
|
${this.body}\r
|
|
141
141
|
`),t+=`-------${this.ident}$\r
|
|
142
|
-
`,t}}const Re={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9};class
|
|
142
|
+
`,t}}const Re={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9};class iu extends dt.EventEmitter{constructor(t){super(),this._id=null,this.my_ip="127.0.0.1",this._ua=t,this.auth_id=Me.createRandomToken(10),this._status=Re.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this._msgHistory=[],this.target_addr=[],this.my_addr=[],this.credentials={username:t._configuration.authorization_user,ha1:t._configuration.ha1,realm:t._configuration.realm},this._request=null,this.status="new",this.target="",this.message="",this._connectionPromiseQueue=Promise.resolve(),this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._tones=null,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:H.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._msrpKeepAliveTimer=null}static get C(){return Re}get direction(){return this._direction}get connection(){return this._connection}get id(){return this._id}connect(t=""){t!==""&&(this._direction="outgoing"),this.target=t;const s=this._ua.options.msrpWs?"ws":"wss";this._connection=new WebSocket(`${s}://${this._ua.options.msrpDomain||this._ua._configuration.realm}`,"msrp"),this._connection.binaryType="arraybuffer",this._connection.onopen=i=>{console.log("open",i),this.onopen()},this._connection.onclose=i=>{console.log("close",i),this.onclose()},this._connection.onmessage=i=>{console.log("msg",i),this.onmessage(i)},this._connection.onerror=i=>{console.log("error",i),this.onerror()}}_sendKeepAlive(){const t=new cr("");t.method="SEND";let s="";this.my_addr[1]&&(s=this.my_addr[1]),this.target_addr[1]&&(s+=" "+this.target_addr[1]),this.target_addr[0]&&(s+=" "+this.target_addr[0]),t.addHeader("To-Path",s),t.addHeader("From-Path",`${this.my_addr[0]}`),t.addHeader("Message-ID",Me.createRandomToken(10)),t.addHeader("Byte-Range","0-0/0"),t.addHeader("Content-Type","text/plain"),t.body="",this._connection.send(t.toString())}answer(){if(!this._createDialog(this._request,"UAS")){this._request.reply(500,"Error creating dialog");return}this._status=Re.STATUS_ANSWERED,clearTimeout(this._timers.userNoAnswerTimer),this.connect()}acceptParty(t){this._request.parseSDP(!0),this._request.reply(200,"OK",[],`v=0
|
|
143
143
|
o=- 4232740119537112802 2 IN IP4 ${this.my_ip}
|
|
144
144
|
c=IN IP4 ${this.my_ip}
|
|
145
145
|
t=0 0
|
|
146
146
|
m=message 2856 TCP/TLS/MSRP *
|
|
147
147
|
a=accept-types:text/plain text/html
|
|
148
148
|
a=path: ${t.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
|
|
149
|
-
`)}inviteParty(t){const
|
|
149
|
+
`)}inviteParty(t){const s={},i=[];s.to_uri=new In("sip",this.target,this._ua._configuration.realm),s.from_uri=new In("sip",this._ua._configuration.uri.user,this._ua._configuration.uri.host),i.push(`Contact: ${this._ua.contact.toString({outbound:!0})}`),i.push("Content-Type: application/sdp"),this._request=new Ct.InitialOutgoingInviteRequest(new In("sip",this.target,this._ua._configuration.realm).clone(),this._ua,s,i,`v=0
|
|
150
150
|
o=- 4232740119537112802 2 IN IP4 ${this.my_ip}
|
|
151
151
|
c=IN IP4 ${this.my_ip}
|
|
152
152
|
t=0 0
|
|
153
153
|
m=message 2856 TCP/TLS/MSRP *
|
|
154
154
|
a=accept-types:text/plain text/html
|
|
155
155
|
a=path:${t.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
|
|
156
|
-
`),this._newMSRPSession("local",this._request),this._from_tag||(this._from_tag=this._request.from._parameters.tag),this._id=this._request.call_id+this._from_tag,new tl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:s=>{this.onTransportError(),console.log(s)},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s),s.status_code===200&&(s.parseSDP(!0),this._status=Re.STATUS_CONFIRMED,this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Re.STATUS_INVITE_SENT}terminate(t={}){const n=t.cause||$.causes.BYE,l=Pe.cloneArray(t.extraHeaders),a=t.body;let s,r=t.status_code,h=t.reason_phrase;if(this._status===Re.STATUS_TERMINATED)throw new js.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Re.STATUS_NULL:case Re.STATUS_INVITE_SENT:case Re.STATUS_1XX_RECEIVED:if(r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(h=h||$.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${h}"`),this._status===Re.STATUS_NULL||this._status===Re.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Re.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Re.STATUS_CANCELED,this._failed("local",null,$.causes.CANCELED);break;case Re.STATUS_WAITING_FOR_ANSWER:case Re.STATUS_ANSWERED:if(r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,h,l,a),this._failed("local",null,$.causes.REJECTED);break;case Re.STATUS_WAITING_FOR_ACK:case Re.STATUS_CONFIRMED:if(h=t.reason_phrase||$.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&l.push(`Reason: SIP ;cause=${r}; text="${h}"`),this._status===Re.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Gt.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:_})=>{_===$.ACK&&(this.sendRequest($.BYE,{extraHeaders:l,body:a}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Gt.C.STATUS_TERMINATED&&(this.sendRequest($.BYE,{extraHeaders:l,body:a}),d.terminate())}),this._ended("local",null,n),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest($.BYE,{extraHeaders:l,body:a}),this._ended("local",null,n)}}sendRequest(t,n){return this._dialog.sendRequest(t,n)}authenticate(t){this.status="auth";let n=new ur("");n.method="AUTH",n.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),n.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),t&&n.addHeader("Authorization",t.toString());let l=n.toString(),a=[];for(var s=0;s<l.length;s++)a.push(l.charCodeAt(s).toString(16));this._connection.send(n.toString())}onmessage(t){const n=new ur(t.data);if(this.status==="auth"&&n.code===401){const l=this.parseAuth(n.getHeader("WWW-Authenticate")),a=new zm(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},l,Pe.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&n.code===200&&this._direction==="outgoing"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.inviteParty(n)):this.status==="auth"&&n.code===200&&this._direction==="incoming"?(this.my_addr.push(n.getHeader("To-Path")),this.my_addr.push(n.getHeader("Use-Path")),this.status="active",this.acceptParty(n),this.emit("confirmed")):n.method==="SEND"&&(this._sendOk(n),this._sendReport(n),n.direction="incoming",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)),n.code===480&&this._close()}onclose(){console.log("close")}onopen(){const t=new RTCPeerConnection({iceServers:[]});t.createDataChannel(""),t.createOffer().then(t.setLocalDescription.bind(t)),t.onicecandidate=n=>{if(!n||!n.candidate||!n.candidate.candidate)return;const l=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=n.candidate.candidate.match(l);this.my_ip=a&&a[1],t.onicecandidate=()=>{},this.authenticate(null)}}onerror(t){console.log(t)}_receiveInviteResponse(t){if(console.log("resp0000000000000",t),this._dialog&&t.status_code>=200&&t.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest($.ACK);return}else{const n=new Zl(this,t,"UAC");if(n.error!==void 0){console.log(n.error);return}this.sendRequest($.ACK),this.sendRequest($.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==Re.STATUS_INVITE_SENT&&this._status!==Re.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=Re.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){console.log("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=Re.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const l=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>this._progress("remote",t)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(console.log("maybe here???"),this._status=Re.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,$.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",t,$.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n),new RTCSessionDescription({type:"answer",sdp:n.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(l=>this._connection.setLocalDescription(l)).catch(l=>{this._acceptAndTerminate(t,500,l.toString()),console.log("failed 4"),this._failed("local",t,$.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest($.ACK),this._confirmed("local",null)});break}default:{const n=Pe.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,n)}}}sendMSRP(t){const n=new ur("");let l="";this.my_addr[1]&&(l=this.my_addr[1]),this.target_addr[1]&&(l+=" "+this.target_addr[1]),this.target_addr[0]&&(l+=" "+this.target_addr[0]),n.method="SEND",n.addHeader("To-Path",l),n.addHeader("From-Path",`${this.my_addr[0]}`),n.addHeader("Message-ID",Pe.createRandomToken(10)),n.addHeader("Byte-Range","1-25/25"),n.addHeader("Content-Type","text/plain"),n.addHeader("Success-Report","yes"),n.addHeader("Failure-Report","yes"),n.body=t;let a=n.toString();console.log(a);let s=[];for(var r=0;r<a.length;r++)s.push(a.charCodeAt(r).toString(16));console.log(s),this._connection.send(n.toString()),n.direction="outgoing",this.emit("newMessage",n),this._msgHistory.push(n),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(t){let n=t.ident,l=t.getHeader("Message-ID"),a=new ur("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",l),a.ident=n;let s=a.toString();console.log(s);let r=[];for(var h=0;h<s.length;h++)r.push(s.charCodeAt(h).toString(16));console.log(r),this._connection.send(a.toString())}_sendReport(t){let n=t.ident,l=t.getHeader("Message-ID"),a=new ur("");a.method="REPORT",a.addHeader("To-Path",`${t.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",l),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=n;let s=a.toString();console.log(s);let r=[];for(var h=0;h<s.length;h++)r.push(s.charCodeAt(h).toString(16));console.log(r),this._connection.send(a.toString())}parseAuth(t){const n={},l=t.replace("Digest","").split(",");for(const a of l){const s=a.trim().split("=");n[s[0]]=s[1].match('^"(.+)"$')[1]}return n}init_incoming(t,n){let l;const a=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&a!=="application/sdp"){t.reply(415);return}if(this._status=Re.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(l=t.getHeader("expires")*1e3),t.to_tag=Pe.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Re.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),console.log("failed 6"),this._failed("local",null,$.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Re.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,$.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,n&&n(this),t.parseSDP(!0),this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",t),this._status!==Re.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,n,l){this.emit("_failed",{originator:t,message:n||null,cause:l}),this._close(),this.emit("failed",{originator:t,message:n||null,cause:l})}_close(){if(console.log("CLOSE SESSION"),this._status!==Re.STATUS_TERMINATED){if(this._status=Re.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){console.log("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyMSRPSession(this)}}_createDialog(t,n,l){const a=n==="UAS"?t.to_tag:t.from_tag,s=n==="UAS"?t.from_tag:t.to_tag,r=t.call_id+a+s;let h=this._earlyDialogs[r];if(l)return h?!0:(h=new Zl(this,t,n,Zl.C.STATUS_EARLY),h.error?(console.log("failed 8"),this._failed("remote",t,$.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=h,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,h)return h.update(t,n),this._dialog=h,delete this._earlyDialogs[r],!0;const d=new Zl(this,t,n);return d.error?(console.log("failed 9"),this._failed("remote",t,$.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_newMSRPSession(t,n){this._ua.newMSRPSession(this,{originator:t,session:this,request:n})}_progress(t,n){this.emit("progress",{originator:t,response:n||null})}isEnded(){switch(this._status){case Re.STATUS_CANCELED:case Re.STATUS_TERMINATED:return!0;default:return!1}}_accepted(t,n){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,l){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:l})}_runKeepAliveTimer(){if(!this._sessionTimers||!this._sessionTimers.enabled||this._sessionTimers.running)return;if(this._sessionTimers.currentExpires||(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires||30),!this._sessionTimers.refresher){console.log("Not the refresher; waiting for remote keep-alive");return}const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.timer=setTimeout(()=>{if(this._connection.readyState===WebSocket.OPEN)try{this._sendKeepAlive(),console.log("Session timer: sending MSRP keep-alive")}catch(n){console.error("Failed to send keep-alive:",n)}this._sessionTimers.running=!1,this._runKeepAliveTimer()},t*1e3*.5)}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=$.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,n=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uac"),this._sessionTimers.refresher=n==="uac",this._runKeepAliveTimer()}receiveRequest(t){if(console.log("receiveRequest()"),t.method===$.CANCEL)(this._status===Re.STATUS_WAITING_FOR_ANSWER||this._status===Re.STATUS_ANSWERED)&&(this._status=Re.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",t,$.causes.CANCELED));else switch(t.method){case $.ACK:if(this._status!==Re.STATUS_WAITING_FOR_ACK)return;if(this._status=Re.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:$.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",n);const l=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(a=>{this.terminate({cause:$.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",t);break;case $.BYE:this._status===Re.STATUS_CONFIRMED||this._status===Re.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,$.causes.BYE)):this._status===Re.STATUS_INVITE_RECEIVED||this._status===Re.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,$.causes.BYE)):t.reply(403,"Wrong Status");break;case $.INVITE:this._status===Re.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case $.INFO:this._status===Re.STATUS_1XX_RECEIVED||this._status===Re.STATUS_WAITING_FOR_ANSWER||this._status===Re.STATUS_ANSWERED||this._status===Re.STATUS_WAITING_FOR_ACK||this._status===Re.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Au(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case $.UPDATE:this._status===Re.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case $.REFER:this._status===Re.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case $.NOTIFY:this._status===Re.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:$.causes.CONNECTION_ERROR,cause:$.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:$.causes.REQUEST_TIMEOUT,cause:$.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:$.causes.DIALOG_ERROR,cause:$.causes.DIALOG_ERROR})}}var HT=Zt();const wu=Xe(HT),co=new Wo("Parser"),FT=(c,t)=>{let n,l,a=c.indexOf(`\r
|
|
157
|
-
`);if(a===-1){
|
|
158
|
-
`,n),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?n=a+2:l=a}return l}function jT(c,t,n,l){let a;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),h=t.substring(s+1,l).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",h),c.getHeaders("via").length===1?(a=c.parseHeader("Via"),a&&(c.via=a,c.via_branch=a.branch)):a=0;break;case"from":case"f":c.setHeader("from",h),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",h),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=wu.parse(h,"Record_Route"),a===-1)a=void 0;else for(const d of a)c.addHeader("record-route",h.substring(d.possition,d.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":c.setHeader("call-id",h),a=c.parseHeader("call-id"),a&&(c.call_id=h);break;case"contact":case"m":if(a=wu.parse(h,"Contact"),a===-1)a=void 0;else for(const d of a)c.addHeader("contact",h.substring(d.possition,d.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":c.setHeader("content-length",h),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",h),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",h),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof _r.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",h),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",h),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",h),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",h),a=c.parseHeader("session-expires"),a&&(c.session_expires=a.expires,c.session_expires_refresher=a.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",h),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",h),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",h),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,h),a=0}return a===void 0?{error:`error parsing header "${r}"`}:!0}const qT={parseMessage:FT},Gi=new Wo("Registrator"),fo=10;class BT{constructor(t,n){this._reg_id=1,this._ua=t,this._transport=n,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=Ts.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const l=this._contact.indexOf(">");if(l!==-1){const a=this._contact.slice(0,l)+this._contact.slice(l+1,this._contact.length);this._contact=a}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const l=t[n];this._extraContactParams+=`;${n}`,l&&(this._extraContactParams+=`=${l}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const l=t[n];this._extraContactParams+=`;${n}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){Gi.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const n=new yt.OutgoingRequest($.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),l=new tl(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,$.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,$.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){Gi.debug("no Contact header in response to REGISTER, response ignored");break}const s=a.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=s.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=s.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){Gi.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let h=r.getParam("expires");!h&&a.hasHeader("expires")&&(h=a.getHeader("expires")),h||(h=this._expires),h=Number(h),h<fo&&(h=fo);const d=h>64?h*1e3/2+Math.floor((h/2-32)*1e3*Math.random()):Math.floor(h*1e3/2);this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<fo&&(this._expires=fo),this.register()):(Gi.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,$.causes.SIP_FAILURE_CODE));break}default:{const s=Ts.sipErrorCause(a.status_code);this._registrationFailure(a,s)}}}});this._registering=!0,l.send()}unregister(t={}){if(!this._registered){Gi.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();t.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),n.push("Expires: 0");const l=new yt.OutgoingRequest($.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new tl(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,$.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,$.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const r=Ts.sipErrorCause(s.status_code);this._unregistered(s,r)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,n){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:n}))}_unregistered(t,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:n||null})}}const st=console,qs={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},GT=NT;class WT extends GT{constructor(t){super(t),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new BT(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(t,n){return super.call(t,n)}joinVideoCall(t,n,l){st.debug("call()");const a=new Ho(this);return a.configureMedia({audio:!0,video:!0}),a.connect(t,n,l),a}startScreenShare(){st.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const n in this._janus_sessions)this._janus_sessions[n].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{nl.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Ts.newUUID());let n;typeof window<"u"&&typeof window.document<"u"?n=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(n=self.navigator.userAgent),n+=" "+De.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(n):n,t.onTransportCallback&&typeof t.onTransportCallback=="function"&&(this.onTransportCallback=t.onTransportCallback),this._configuration.jssip_id=Ts.createRandomToken(5);const l=this._configuration.uri.clone();l.user=null,this._configuration.hostport_params=l.toString().replace(/^sip:/i,"");try{this._transport=new nT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=KT.bind(this),this._transport.onconnect=YT.bind(this),this._transport.ondisconnect=JT.bind(this),this._transport.ondata=zT.bind(this)}catch(s){throw st.warn(s),new js.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Rn("sip",Ts.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const r=s.anonymous||null,h=s.outbound||null;let d="<";return r?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),h&&(r?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",d}};const a=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(a.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));st.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(nl.settings,s))switch(s){case"uri":case"registrar_server":st.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":st.debug(`- ${s}: NOT SHOWN`);break;default:st.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",l=>{console.log(l)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(l=>{l.setSession(t)}),this.processStreamPlugins.forEach(l=>{l.setSession(t)}),this.emit("newJanusSession",n)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(t){var s,r,h,d;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){st.debug("Request-URI does not point to us"),t.method!==De.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===De.SIPS){t.reply_sl(416);return}if(Gt.checkTransaction(this,t))return;if(n===De.INVITE?new Gt.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new Gt.NonInviteServerTransaction(this,this._transport,t),n===De.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const g=Date.now(),T=this.lastOptionsTimestamp>g-35e3,S=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>g;T&&S&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){t.reply(200);return}new ef.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new ef.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let l,a;if(t.to_tag)if(l=this._findDialog(t.call_id,t.from_tag,t.to_tag),l)l.receiveRequest(t);else if(n===De.NOTIFY)if(a=this._findSession(t),a)a.receiveRequest(t);else{if(t.body)try{const _=JSON.parse(t.body)||{};(r=(s=_.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(_),(d=(h=_.plugindata)==null?void 0:h.data)!=null&&d.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(_.plugindata.data.unpublished)}catch(_){console.error(_)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const _=t.replaces;l=this._findDialog(_.call_id,_.from_tag,_.to_tag),l?(a=l.owner,a.isEnded()?t.reply(603):a.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(a=new nu(this),a.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(a=new Vg(this),a.init_incoming(t));else st.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case De.BYE:t.reply(481);break;case De.CANCEL:a=this._findSession(t),a?a.receiveRequest(t):st.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,n){st.debug("startMSRP()",n);const l=new nu(this);return l.connect(t),l}startJanus(t,n){st.debug("startJanus()",n);const l=new nu(this);return l.connect(t),l}terminateMSRPSessions(t){st.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){st.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){st.debug("enableJanusAudio()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startAudio():this._janus_sessions[n].stopAudio())}enableJanusVideo(t){st.debug("enableJanusVideo()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||(t?this._janus_sessions[n].startVideo():this._janus_sessions[n].stopVideo())}terminateAllSessions(){for(const t in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,t)){st.debug(`closing session ${t}`);try{this._sessions[t].terminate()}catch(n){console.error(n)}}}stop(t=!0){if(st.debug("stop()"),this._dynConfiguration={},this._status===qs.STATUS_USER_CLOSED){st.debug("UA already closed");return}this._registrator.close();const n=Object.keys(this._sessions).length;t&&this.terminateAllSessions();for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){st.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(s){console.error(s)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){st.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(s){console.error(s)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(s){console.error(s)}this._status=qs.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&n===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function KT(c){this.emit("connecting",c)}function YT(c){this._status!==qs.STATUS_USER_CLOSED&&(this._status=qs.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function JT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const l in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],l)&&this._transactions[n][l].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==qs.STATUS_USER_CLOSED&&(this._status=qs.STATUS_NOT_READY,this._error=qs.NETWORK_ERROR)}function zT(c){const t=c.transport;let n=c.message;const l=n;if(n=qT.parseMessage(n,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(n,l),!!n&&!(this._status===qs.STATUS_USER_CLOSED&&n instanceof _r.IncomingRequest)&&TT(n,this,t)){if(n instanceof _r.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof _r.IncomingResponse){let a;switch(n.method){case De.INVITE:if(a=this._transactions.ict[n.via_branch],a){const s=n.status_code;if((s===100||s===180||s===183)&&this.audio&&typeof this.audio.handleSipResponseForRingback=="function"){let r=null;if(a._session&&a._session.id)r=a._session.id;else if(n.call_id&&this._sessions){const d=Object.values(this._sessions).find(_=>_._id&&_._id.includes(n.call_id)||_.id&&_.id.includes(n.call_id)||_.call_id===n.call_id);d&&(d.id||d._id)&&(r=d.id||d._id)}else n.call_id&&(r=n.call_id);r&&this.audio.handleSipResponseForRingback(r,s)}a.receiveResponse(n)}break;case De.ACK:break;default:a=this._transactions.nict[n.via_branch],a&&a.receiveResponse(n);break}}}}const XT=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer","putOnHoldTimestamp","_remote_party_display_name","_remote_party_uri_user"],QT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Uf(c){const t={};return XT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function kf(c){const t={};return QT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}async function ru(c,t,n){const l=c.createMediaStreamSource(t),a=c.createMediaStreamDestination(),s=c.createGain();return l.connect(s),s.connect(a),s.gain.value=n,a.stream}function ZT(c,t,n,l){if(Nd())return;const a=document.createElement("audio");a.id=t._id,a.className="audioTag",a.srcObject=c,a.setSinkId(n),a.volume=l,a.play(),t.audioTag=a}function Pf(c){if(!c)return null;const t=c.match(/^\s*"((?:[^"\\]|\\.)*)"/);return t?t[1].replace(/\\(.)/g,"$1"):null}function Mf(c){if(!c)return null;const t=c.match(/<?sips?:([^@>\s;]+)@/i);return t?t[1]:null}function ev(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function Nd(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const tv=ut,sv=Zt(),Dt=new tv("WebSocketInterface");var nv=class{constructor(t){Dt.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=sv.parse(t,"absoluteURI");if(n===-1)throw Dt.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Dt.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Dt.debug("connect()"),this.isConnected()){Dt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Dt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Dt.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(t){this._onError(t)}}disconnect(){Dt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Dt.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Dt.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Dt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:l}){Dt.debug(`WebSocket ${this._url} closed`),t===!1&&Dt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,l)}_onMessage({data:t}){Dt.debug("received WebSocket message"),this.ondata(t)}_onError(t){Dt.warn(`WebSocket ${this._url} error: `,t)}};const Ou=Fo,rv=De,iv=Cs,lv=Ct(),ov=Dd,av=ys(),uv=Fu(),cv=Zt(),fv=nv,dv=mr("JsSIP");dv("version %s",Ou.version);var hv={C:rv,Exceptions:iv,Utils:lv,UA:ov,URI:av,NameAddrHeader:uv,WebSocketInterface:fv,Grammar:cv,debug:mr,get name(){return Ou.title},get version(){return Ou.version}};const _v=Xe(hv);function iu(c){return c<10?`0${c}`:`${c}`}function pv(c){let t=c.hours||0,n=c.minutes||0,l=c.seconds||0;l++,l===60&&(l=0,n++,n===60&&(n=0,t++));const a=`${iu(t)}:${iu(n)}:${iu(l)}`;return{seconds:l,minutes:n,hours:t,formatted:a}}function mv(c){let t=0;for(let n=0;n<c.length;n++)t+=c[n]*c[n];return Math.sqrt(t/c.length)}async function gv(c,t,n=150){const l=t.createMediaStreamSource(c),a=t.createDelay();a.delayTime.value=n/1e3;const s=t.createGain();s.gain.value=0;const r=t.createMediaStreamDestination();return l.connect(a).connect(s).connect(r),{stream:r.stream,setSpeaking:h=>{s.gain.value=h?1:0}}}var At={};At.forEach=async(c,t,n)=>{const l=[];for(let a=0;a<c.length;a++)if(a in c){const s=Promise.resolve(c[a]).then(r=>t.call(n||globalThis,r,a,c));l.push(s)}await Promise.all(l)};At.forEachSeries=async(c,t,n)=>{for(let l=0;l<c.length;l++)l in c&&await t.call(n||globalThis,await c[l],l,c)};At.map=async(c,t,n)=>{const l=[];for(let a=0;a<c.length;a++)a in c&&(l[a]=Promise.resolve(c[a]).then(s=>t.call(n||globalThis,s,a,c)));return Promise.all(l)};At.mapSeries=async(c,t,n)=>{const l=[];for(let a=0;a<c.length;a++)a in c&&(l[a]=await t.call(n||globalThis,await c[a],a,c));return l};At.find=(c,t,n)=>new Promise((l,a)=>{if(c.length===0)return l();let s=1;for(let r=0;r<c.length;r++){const h=d=>{d?l(c[r]):s===c.length&&l(),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(h).catch(a)}});At.findSeries=async(c,t,n)=>{for(let l=0;l<c.length;l++)if(await t.call(n||globalThis,await c[l],l,c))return c[l]};At.findIndex=(c,t,n)=>new Promise((l,a)=>{if(c.length===0)return l(-1);let s=1;for(let r=0;r<c.length;r++){const h=d=>{d?l(r):s===c.length&&l(-1),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(h).catch(a)}});At.findIndexSeries=async(c,t,n)=>{for(let l=0;l<c.length;l++)if(await t.call(n||globalThis,await c[l],l,c))return l};At.some=(c,t,n)=>new Promise((l,a)=>{if(c.length===0)return l(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const h=d=>{d?l(!0):s===c.length&&l(!1),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(h).catch(a)}});At.someSeries=async(c,t,n)=>{for(let l=0;l<c.length;l++)if(l in c&&await t.call(n||globalThis,await c[l],l,c))return!0;return!1};At.every=(c,t,n)=>new Promise((l,a)=>{if(c.length===0)return l(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const h=d=>{d?s===c.length&&l(!0):l(!1),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(h).catch(a)}});At.everySeries=async(c,t,n)=>{for(let l=0;l<c.length;l++)if(l in c&&!await t.call(n||globalThis,await c[l],l,c))return!1;return!0};At.filter=(c,t,n)=>new Promise(async(l,a)=>{const s=[];for(let h=0;h<c.length;h++)h in c&&(s[h]=Promise.resolve(c[h]).then(d=>t.call(n||globalThis,d,h,c)).catch(a));const r=[];for(let h=0;h<s.length;h++)await s[h]&&r.push(await c[h]);l(r)});At.filterSeries=async(c,t,n)=>{const l=[];for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)&&l.push(await c[a]);return l};At.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let l,a;for(n!==void 0?(a=n,l=0):(a=c[0],l=1),l;l<c.length;l++)l in c&&(a=await t(await a,await c[l],l,c));return a};var xd={};(function(c){const t=At;Object.keys(t).forEach(n=>{const l=n.charAt(0).toUpperCase()+n.slice(1);c[`async${l}`]=async function(...a){return t[n](this,...a)}})})(xd);const Tv=At,vv=xd;var Sv=Object.assign(Tv,{instanceMethods:vv});const Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},lu={TRYING:100,RINGING:180,SESSION_PROGRESS:183,OK:200,MOVED_TEMPORARILY:302,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,REQUEST_TIMEOUT:408,BUSY_HERE:486,REQUEST_TERMINATED:487,INTERNAL_SERVER_ERROR:500,SERVICE_UNAVAILABLE:503,BUSY_EVERYWHERE:600,DECLINE:603};var Ev={exports:{}};(function(c){var t=function(n){var l=Object.prototype,a=l.hasOwnProperty,s=Object.defineProperty||function(Q,W,G){Q[W]=G.value},r,h=typeof Symbol=="function"?Symbol:{},d=h.iterator||"@@iterator",_=h.asyncIterator||"@@asyncIterator",g=h.toStringTag||"@@toStringTag";function T(Q,W,G){return Object.defineProperty(Q,W,{value:G,enumerable:!0,configurable:!0,writable:!0}),Q[W]}try{T({},"")}catch{T=function(W,G,re){return W[G]=re}}function S(Q,W,G,re){var _e=W&&W.prototype instanceof le?W:le,Ie=Object.create(_e.prototype),ke=new k(re||[]);return s(Ie,"_invoke",{value:Y(Q,G,ke)}),Ie}n.wrap=S;function E(Q,W,G){try{return{type:"normal",arg:Q.call(W,G)}}catch(re){return{type:"throw",arg:re}}}var C="suspendedStart",A="suspendedYield",R="executing",V="completed",w={};function le(){}function x(){}function H(){}var ve={};T(ve,d,function(){return this});var pe=Object.getPrototypeOf,P=pe&&pe(pe(B([])));P&&P!==l&&a.call(P,d)&&(ve=P);var N=H.prototype=le.prototype=Object.create(ve);x.prototype=H,s(N,"constructor",{value:H,configurable:!0}),s(H,"constructor",{value:x,configurable:!0}),x.displayName=T(H,g,"GeneratorFunction");function q(Q){["next","throw","return"].forEach(function(W){T(Q,W,function(G){return this._invoke(W,G)})})}n.isGeneratorFunction=function(Q){var W=typeof Q=="function"&&Q.constructor;return W?W===x||(W.displayName||W.name)==="GeneratorFunction":!1},n.mark=function(Q){return Object.setPrototypeOf?Object.setPrototypeOf(Q,H):(Q.__proto__=H,T(Q,g,"GeneratorFunction")),Q.prototype=Object.create(N),Q},n.awrap=function(Q){return{__await:Q}};function j(Q,W){function G(Ie,ke,Ae,oe){var ye=E(Q[Ie],Q,ke);if(ye.type==="throw")oe(ye.arg);else{var nt=ye.arg,ot=nt.value;return ot&&typeof ot=="object"&&a.call(ot,"__await")?W.resolve(ot.__await).then(function(Ee){G("next",Ee,Ae,oe)},function(Ee){G("throw",Ee,Ae,oe)}):W.resolve(ot).then(function(Ee){nt.value=Ee,Ae(nt)},function(Ee){return G("throw",Ee,Ae,oe)})}}var re;function _e(Ie,ke){function Ae(){return new W(function(oe,ye){G(Ie,ke,oe,ye)})}return re=re?re.then(Ae,Ae):Ae()}s(this,"_invoke",{value:_e})}q(j.prototype),T(j.prototype,_,function(){return this}),n.AsyncIterator=j,n.async=function(Q,W,G,re,_e){_e===void 0&&(_e=Promise);var Ie=new j(S(Q,W,G,re),_e);return n.isGeneratorFunction(W)?Ie:Ie.next().then(function(ke){return ke.done?ke.value:Ie.next()})};function Y(Q,W,G){var re=C;return function(Ie,ke){if(re===R)throw new Error("Generator is already running");if(re===V){if(Ie==="throw")throw ke;return He()}for(G.method=Ie,G.arg=ke;;){var Ae=G.delegate;if(Ae){var oe=F(Ae,G);if(oe){if(oe===w)continue;return oe}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===C)throw re=V,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=R;var ye=E(Q,W,G);if(ye.type==="normal"){if(re=G.done?V:A,ye.arg===w)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=V,G.method="throw",G.arg=ye.arg)}}}function F(Q,W){var G=W.method,re=Q.iterator[G];if(re===r)return W.delegate=null,G==="throw"&&Q.iterator.return&&(W.method="return",W.arg=r,F(Q,W),W.method==="throw")||G!=="return"&&(W.method="throw",W.arg=new TypeError("The iterator does not provide a '"+G+"' method")),w;var _e=E(re,Q.iterator,W.arg);if(_e.type==="throw")return W.method="throw",W.arg=_e.arg,W.delegate=null,w;var Ie=_e.arg;if(!Ie)return W.method="throw",W.arg=new TypeError("iterator result is not an object"),W.delegate=null,w;if(Ie.done)W[Q.resultName]=Ie.value,W.next=Q.nextLoc,W.method!=="return"&&(W.method="next",W.arg=r);else return Ie;return W.delegate=null,w}q(N),T(N,g,"Generator"),T(N,d,function(){return this}),T(N,"toString",function(){return"[object Generator]"});function X(Q){var W={tryLoc:Q[0]};1 in Q&&(W.catchLoc=Q[1]),2 in Q&&(W.finallyLoc=Q[2],W.afterLoc=Q[3]),this.tryEntries.push(W)}function U(Q){var W=Q.completion||{};W.type="normal",delete W.arg,Q.completion=W}function k(Q){this.tryEntries=[{tryLoc:"root"}],Q.forEach(X,this),this.reset(!0)}n.keys=function(Q){var W=Object(Q),G=[];for(var re in W)G.push(re);return G.reverse(),function _e(){for(;G.length;){var Ie=G.pop();if(Ie in W)return _e.value=Ie,_e.done=!1,_e}return _e.done=!0,_e}};function B(Q){if(Q){var W=Q[d];if(W)return W.call(Q);if(typeof Q.next=="function")return Q;if(!isNaN(Q.length)){var G=-1,re=function _e(){for(;++G<Q.length;)if(a.call(Q,G))return _e.value=Q[G],_e.done=!1,_e;return _e.value=r,_e.done=!0,_e};return re.next=re}}return{next:He}}n.values=B;function He(){return{value:r,done:!0}}return k.prototype={constructor:k,reset:function(Q){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(U),!Q)for(var W in this)W.charAt(0)==="t"&&a.call(this,W)&&!isNaN(+W.slice(1))&&(this[W]=r)},stop:function(){this.done=!0;var Q=this.tryEntries[0],W=Q.completion;if(W.type==="throw")throw W.arg;return this.rval},dispatchException:function(Q){if(this.done)throw Q;var W=this;function G(oe,ye){return Ie.type="throw",Ie.arg=Q,W.next=oe,ye&&(W.method="next",W.arg=r),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var _e=this.tryEntries[re],Ie=_e.completion;if(_e.tryLoc==="root")return G("end");if(_e.tryLoc<=this.prev){var ke=a.call(_e,"catchLoc"),Ae=a.call(_e,"finallyLoc");if(ke&&Ae){if(this.prev<_e.catchLoc)return G(_e.catchLoc,!0);if(this.prev<_e.finallyLoc)return G(_e.finallyLoc)}else if(ke){if(this.prev<_e.catchLoc)return G(_e.catchLoc,!0)}else if(Ae){if(this.prev<_e.finallyLoc)return G(_e.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Q,W){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&a.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var _e=re;break}}_e&&(Q==="break"||Q==="continue")&&_e.tryLoc<=W&&W<=_e.finallyLoc&&(_e=null);var Ie=_e?_e.completion:{};return Ie.type=Q,Ie.arg=W,_e?(this.method="next",this.next=_e.finallyLoc,w):this.complete(Ie)},complete:function(Q,W){if(Q.type==="throw")throw Q.arg;return Q.type==="break"||Q.type==="continue"?this.next=Q.arg:Q.type==="return"?(this.rval=this.arg=Q.arg,this.method="return",this.next="end"):Q.type==="normal"&&W&&(this.next=W),w},finish:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.finallyLoc===Q)return this.complete(G.completion,G.afterLoc),U(G),w}},catch:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.tryLoc===Q){var re=G.completion;if(re.type==="throw"){var _e=re.arg;U(G)}return _e}}throw new Error("illegal catch attempt")},delegateYield:function(Q,W,G){return this.delegate={iterator:B(Q),resultName:W,nextLoc:G},this.method==="next"&&(this.arg=r),w}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(Ev);var Ud={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(Bd,function(){var t=function(){},n="undefined",l=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function s(A,R){var V=A[R];if(typeof V.bind=="function")return V.bind(A);try{return Function.prototype.bind.call(V,A)}catch{return function(){return Function.prototype.apply.apply(V,[A,arguments])}}}function r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function h(A){return A==="debug"&&(A="log"),typeof console===n?!1:A==="trace"&&l?r:console[A]!==void 0?s(console,A):console.log!==void 0?s(console,"log"):t}function d(A,R){for(var V=0;V<a.length;V++){var w=a[V];this[w]=V<A?t:this.methodFactory(w,A,R)}this.log=this.debug}function _(A,R,V){return function(){typeof console!==n&&(d.call(this,R,V),this[A].apply(this,arguments))}}function g(A,R,V){return h(A)||_.apply(this,arguments)}function T(A,R,V){var w=this,le;R=R??"WARN";var x="loglevel";typeof A=="string"?x+=":"+A:typeof A=="symbol"&&(x=void 0);function H(N){var q=(a[N]||"silent").toUpperCase();if(!(typeof window===n||!x)){try{window.localStorage[x]=q;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+q+";"}catch{}}}function ve(){var N;if(!(typeof window===n||!x)){try{N=window.localStorage[x]}catch{}if(typeof N===n)try{var q=window.document.cookie,j=q.indexOf(encodeURIComponent(x)+"=");j!==-1&&(N=/^([^;]+)/.exec(q.slice(j))[1])}catch{}return w.levels[N]===void 0&&(N=void 0),N}}function pe(){if(!(typeof window===n||!x)){try{window.localStorage.removeItem(x);return}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}w.name=A,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=V||g,w.getLevel=function(){return le},w.setLevel=function(N,q){if(typeof N=="string"&&w.levels[N.toUpperCase()]!==void 0&&(N=w.levels[N.toUpperCase()]),typeof N=="number"&&N>=0&&N<=w.levels.SILENT){if(le=N,q!==!1&&H(N),d.call(w,N,A),typeof console===n&&N<w.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+N},w.setDefaultLevel=function(N){R=N,ve()||w.setLevel(N,!1)},w.resetLevel=function(){w.setLevel(R,!1),pe()},w.enableAll=function(N){w.setLevel(w.levels.TRACE,N)},w.disableAll=function(N){w.setLevel(w.levels.SILENT,N)};var P=ve();P==null&&(P=R),w.setLevel(P,!1)}var S=new T,E={};S.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var V=E[R];return V||(V=E[R]=new T(R,S.getLevel(),S.methodFactory)),V};var C=typeof window!==n?window.log:void 0;return S.noConflict=function(){return typeof window!==n&&window.log===S&&(window.log=C),S},S.getLoggers=function(){return E},S.default=S,S})})(Ud);var It=Ud.exports;const vs=()=>`${new Date().toISOString()} | metrics`,Ss=(c,t,n)=>`${c} | ${t} | ${n}`;It.setDefaultLevel(It.levels.TRACE);const yv=c=>{It.info(Ss(vs(),"log ",`set log level to ${c?"verbose":"info"}`)),It.setLevel(c?It.levels.TRACE:It.levels.INFO)},Cv=c=>{const t=[...Object.keys(It.levels)];t.includes(c)?(It.info(Ss(vs(),"log ",`update log level to ${c.toLowerCase()}`)),It.setLevel(c)):It.warn(Ss(vs(),"log ","Incorrect log level please choose one of "),t)},Ue=(c,t,n)=>{n?It.debug(Ss(vs(),c,t),n):It.debug(Ss(vs(),c,t))},ou=(c,t)=>{It.info(Ss(vs(),c,t))},An=(c,t)=>{It.info(Ss(vs(),c,t))},Oo=(c,t)=>{It.warn(Ss(vs(),c,t))},dr=(c,t)=>{It.error(Ss(vs(),c,t))};function Av(c){return Math.floor(Math.random()*c).toString()}function Lf(c,t){let n=t;return c.forEach(l=>{n=n.replace(l,"")}),n}function Rv(c,t){let n="";for(let l=0;l<t;l+=1)n+=c[Av(c.length)];return n}function Iv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:l=[],excludeSymbols:a=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",h=[],d=[],_=[];return t&&(a.length&&(s=Lf(a,s)),d=s.split("")),n&&(a.length&&(r=Lf(a,r)),_=r.split("")),h=[...d,..._,...l],Rv(h,c)}var bv=Iv;const Xi=Xe(bv),wv=()=>"WebRTCMetrics",Ov=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},gs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Wi={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},Dv=()=>({...{delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}}),kd={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:$e.INBOUND},Pd={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:$e.OUTBOUND},Md={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:$e.INBOUND},Ld={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:$e.OUTBOUND},Nv=c=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const n={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(l=>{n.audio[l]={...c.audio[l]}}),Object.keys(c.video).forEach(l=>{n.video[l]={...c.video[l]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},xv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Xi()}`,cid:`c-${Xi()}`,uid:`u-${Xi()}`,record:!1,ticket:!0},zt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},K={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},M={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Ki={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},au={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},uu="config ",Uv=(c,t={},n)=>{const l={...n,...t};return t.pname||Oo(uu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||Oo(uu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||Oo(uu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),l.pc=c,l},kv=(c={})=>{const t={...xv,...c};return t.name=wv(),t.version=Ov(),t},pl=(c,t,n,l=!1,a)=>{let s=c.map(r=>{if(!n)return r[t];if(!a)return r[t][n];const h=r[t][a];return h?h[n]:null});return s=s.filter(r=>l?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Gs=c=>c.reduce((t,n)=>t+n,0)/c.length,Pv=()=>`probe-${Xi()}`,Mv=()=>`coltr-${Xi()}`,$f=c=>new Promise(t=>setTimeout(t,c)),Du=(c,t,n)=>{t?c.call(t,n):c(n)},Ye=(c,t,n,l)=>{const a=pl(c,t,n,!0,l);if(a.length===0)return null;const s=a.reduce((_,g)=>_+g,0)/a.length;return s===0?null:a.map(_=>Math.abs(s-_)).reduce((_,g)=>_+g,0)/a.length*100/s},Qe=(c,t,n,l=!1,a)=>{const s=pl(c,t,n,l,a);return s.length===0?null:s.reduce((r,h)=>r+h,0)/s.length},En=(c,t,n)=>pl(c,t,n).reduce((a,s)=>a+s,0),Je=(c,t,n,l)=>{const a=pl(c,t,n,!0,l);return a.length===0?null:Math.min(...a)},ze=(c,t,n,l)=>{const a=pl(c,t,n,!1,l);return a.length===0?null:Math.max(...a)},gt=(c,t,n,l)=>{const a=c.slice().pop();if(!a)return null;if(!n)return a[t];if(!l)return a[t][n];const s=a[t][l];return s?s[n]:null},Lv=c=>c.slice().pop(),ct=(c,t,n)=>{if(!t)return null;const l={};let a=t[M.AUDIO][c];a||(a=n===$e.INBOUND?{...kd}:{...Pd}),l[M.AUDIO]=a;let s=t[M.VIDEO][c];return s||(s=n===$e.INBOUND?{...Md}:{...Ld}),l[M.VIDEO]=s,l},Yi="exporter ",$v="2.0",Hf=(c,t,n)=>{if(!c||c.length===0)return 0;const l=c[c.length-1];if(!l)return 0;const a=l[t][n];if(a){const s=a.total_rtt_ms_out,r=a.total_rtt_measure_out;return!r||!s?Qe(c,t,"delta_rtt_ms_out",!1,n):Number(s/r)}return null},Hv=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const l=n[t].total_rtt_connectivity_ms,a=n[t].total_rtt_connectivity_measure;return!a||!l?Qe(c,t,"delta_rtt_connectivity_ms"):Number(l/a)},Fv=c=>gt(c,"network","local_candidate_type")!=="relay"?`direct/${gt(c,"network","local_candidate_protocol")}`:`turn/${gt(c,"network","local_candidate_relay_protocol")}`,Vv=c=>{const t=gt(c,"network","remote_candidate_type"),n=gt(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class jv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){ou(Yi,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){ou(Yi,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(Ue(Yi,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){ou(Yi,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ue(Yi,"ticket() - generate ticket");const t=gt(this._reports,"audio","total_packets_lost_in"),n=gt(this._reports,"audio","total_packets_in"),l=gt(this._reports,"video","total_packets_lost_in"),a=gt(this._reports,"video","total_packets_in"),s={},r=Lv(this._reports);return r&&(Object.keys(r[M.AUDIO]).forEach(h=>{const d=r[M.AUDIO][h];if(s[d.ssrc]={type:M.AUDIO,direction:d.direction},d.direction===$e.INBOUND){const _={avg:Qe(this._reports,M.AUDIO,"delta_jitter_ms_in",!1,h),min:Je(this._reports,M.AUDIO,"delta_jitter_ms_in",h),max:ze(this._reports,M.AUDIO,"delta_jitter_ms_in",h),volatility:Ye(this._reports,M.AUDIO,"delta_jitter_ms_in",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Qe(this._reports,M.AUDIO,"delta_kbs_in",!1,h),min:Je(this._reports,M.AUDIO,"delta_kbs_in",h),max:ze(this._reports,M.AUDIO,"delta_kbs_in",h),volatility:Ye(this._reports,M.AUDIO,"delta_kbs_in",h),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.AUDIO,"delta_KBytes_in",!1,h),min:Je(this._reports,M.AUDIO,"delta_KBytes_in",h),max:ze(this._reports,M.AUDIO,"delta_KBytes_in",h),volatility:Ye(this._reports,M.AUDIO,"delta_KBytes_in",h),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={emodel:{avg:Qe(this._reports,M.AUDIO,"mos_emodel_in",!1,h),min:Je(this._reports,M.AUDIO,"mos_emodel_in",h),max:ze(this._reports,M.AUDIO,"mos_emodel_in",h),volatility:Ye(this._reports,M.AUDIO,"mos_emodel_in",h)},effective:{avg:Qe(this._reports,M.AUDIO,"mos_in",!1,h),min:Je(this._reports,M.AUDIO,"mos_in",h),max:ze(this._reports,M.AUDIO,"mos_in",h),volatility:Ye(this._reports,M.AUDIO,"mos_in",h)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},E=gt(this._reports,M.AUDIO,"total_packets_lost_in",h),C=gt(this._reports,M.AUDIO,"total_packets_in",h),A={lost:E,avg:Math.round((E/(E+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[h].jitter=_,s[h].mos=S,s[h].traffic=T,s[h].bitrate=g,s[h].loss=A}else{const _={avg:Qe(this._reports,M.AUDIO,"delta_jitter_ms_out",!1,h),min:Je(this._reports,M.AUDIO,"delta_jitter_ms_out",h),max:ze(this._reports,M.AUDIO,"delta_jitter_ms_out",h),volatility:Ye(this._reports,M.AUDIO,"delta_jitter_ms_out",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Qe(this._reports,M.AUDIO,"delta_kbs_out",!1,h),min:Je(this._reports,M.AUDIO,"delta_kbs_out",h),max:ze(this._reports,M.AUDIO,"delta_kbs_out",h),volatility:Ye(this._reports,M.AUDIO,"delta_kbs_out",h),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.AUDIO,"delta_KBytes_out",!1,h),min:Je(this._reports,M.AUDIO,"delta_KBytes_out",h),max:ze(this._reports,M.AUDIO,"delta_KBytes_out",h),volatility:Ye(this._reports,M.AUDIO,"delta_KBytes_out",h),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},S={avg:Hf(this._reports,M.AUDIO,h),min:Je(this._reports,M.AUDIO,"delta_rtt_ms_out",h),max:ze(this._reports,M.AUDIO,"delta_rtt_ms_out",h),volatility:Ye(this._reports,M.AUDIO,"delta_rtt_ms_out",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=gt(this._reports,M.AUDIO,"total_packets_lost_out",h),C=gt(this._reports,M.AUDIO,"total_packets_out",h),A={lost:E,avg:Math.round((E/(E+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},R={emodel:{avg:Qe(this._reports,M.AUDIO,"mos_emodel_out",!1,h),min:Je(this._reports,M.AUDIO,"mos_emodel_out",h),max:ze(this._reports,M.AUDIO,"mos_emodel_out",h),volatility:Ye(this._reports,M.AUDIO,"mos_emodel_out",h)},effective:{avg:Qe(this._reports,M.AUDIO,"mos_out",!1,h),min:Je(this._reports,M.AUDIO,"mos_out",h),max:ze(this._reports,M.AUDIO,"mos_out",h),volatility:Ye(this._reports,M.AUDIO,"mos_out",h)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[h].jitter=_,s[h].rtt=S,s[h].traffic=T,s[h].bitrate=g,s[h].loss=A,s[h].mos=R}}),Object.keys(r[M.VIDEO]).forEach(h=>{const d=r[M.VIDEO][h];if(s[h]={type:M.VIDEO,direction:d.direction},d.direction===$e.INBOUND){const _={avg:Qe(this._reports,M.VIDEO,"delta_jitter_ms_in",!1,h),min:Je(this._reports,M.VIDEO,"delta_jitter_ms_in",h),max:ze(this._reports,M.VIDEO,"delta_jitter_ms_in",h),volatility:Ye(this._reports,M.VIDEO,"delta_jitter_ms_in",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Qe(this._reports,M.VIDEO,"delta_kbs_in",!1,h),min:Je(this._reports,M.VIDEO,"delta_kbs_in",h),max:ze(this._reports,M.VIDEO,"delta_kbs_in",h),volatility:Ye(this._reports,M.VIDEO,"delta_kbs_in",h),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.VIDEO,"delta_KBytes_in",!1,h),min:Je(this._reports,M.VIDEO,"delta_KBytes_in",h),max:ze(this._reports,M.VIDEO,"delta_KBytes_in",h),volatility:Ye(this._reports,M.VIDEO,"delta_KBytes_in",h),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S=gt(this._reports,M.VIDEO,"total_packets_lost_in",h),E=gt(this._reports,M.VIDEO,"total_packets_in",h),C={lost:S,avg:Math.round((S/(S+E)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[h].jitter=_,s[h].traffic=T,s[h].bitrate=g,s[h].loss=C}else{const _={avg:Qe(this._reports,M.VIDEO,"delta_jitter_ms_out",!1,h),min:Je(this._reports,M.VIDEO,"delta_jitter_ms_out",h),max:ze(this._reports,M.VIDEO,"delta_jitter_ms_out",h),volatility:Ye(this._reports,M.VIDEO,"delta_jitter_ms_out",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Qe(this._reports,M.VIDEO,"delta_kbs_out",!1,h),min:Je(this._reports,M.VIDEO,"delta_kbs_out",h),max:ze(this._reports,M.VIDEO,"delta_kbs_out",h),volatility:Ye(this._reports,M.VIDEO,"delta_kbs_out",h),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.VIDEO,"delta_KBytes_out",!1,h),min:Je(this._reports,M.VIDEO,"delta_KBytes_out",h),max:ze(this._reports,M.VIDEO,"delta_KBytes_out",h),volatility:Ye(this._reports,M.VIDEO,"delta_KBytes_out",h),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={avg:Hf(this._reports,M.VIDEO,h),min:Je(this._reports,M.VIDEO,"delta_rtt_ms_out",h),max:ze(this._reports,M.VIDEO,"delta_rtt_ms_out",h),volatility:Ye(this._reports,M.VIDEO,"delta_rtt_ms_out",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=gt(this._reports,M.VIDEO,"total_packets_lost_out",h),C=gt(this._reports,M.VIDEO,"total_packets_out",h),A={lost:E,avg:Math.round((E/(E+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[h].jitter=_,s[h].rtt=S,s[h].traffic=T,s[h].bitrate=g,s[h].loss=A}})),{version:$v,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:Hv(this._reports,"data"),min:Je(this._reports,"data","delta_rtt_connectivity_ms"),max:ze(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ye(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+n)*100||0)*100)/100}},video:{in:{avg:Math.round((l/(l+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Qe(this._reports,"data","delta_kbs_in"),min:Je(this._reports,"data","delta_kbs_in"),max:ze(this._reports,"data","delta_kbs_in"),volatility:Ye(this._reports,"data","delta_kbs_in")},out:{avg:Qe(this._reports,"data","delta_kbs_out"),min:Je(this._reports,"data","delta_kbs_out"),max:ze(this._reports,"data","delta_kbs_out"),volatility:Ye(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Qe(this._reports,"data","delta_KBytes_in"),min:Je(this._reports,"data","delta_KBytes_in"),max:ze(this._reports,"data","delta_KBytes_in"),volatility:Ye(this._reports,"data","delta_KBytes_in")},out:{avg:Qe(this._reports,"data","delta_KBytes_out"),min:Je(this._reports,"data","delta_KBytes_out"),max:ze(this._reports,"data","delta_KBytes_out"),volatility:Ye(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:Fv(this._reports),remoteConnection:Vv(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const Vs="extractor ",Ff=(c,t,n,l)=>{let a=!1;const s=l[t].total_rtt_ms_out,r=l[t].total_rtt_measure_out,h=n?n[t].total_rtt_ms_out:0,d=n?n[t].total_rtt_measure_out:0,_={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[K.TIMESTAMP]===l[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===r))return _;const g=1e3*Number(c[K.ROUND_TRIP_TIME]);let T=s+g,S=r+1;return a&&(T=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-h,S=Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:g,totalRTT:T,totalRTTMeasurements:S}},qv=(c,t,n,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:l[t].total_rtt_connectivity_ms,totalRTTMeasurements:l[t].total_rtt_connectivity_measure};const a=1e3*Number(c[K.CURRENT_ROUND_TRIP_TIME]);let s=l[t].total_rtt_connectivity_ms+a,r=l[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,K.RESPONSES_RECEIVED)&&(r=Number(c[K.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:s,totalRTTMeasurements:r}},ho=(c,t,n)=>c[K.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.JITTER)?null:1e3*(Number(c[K.JITTER])||0),Bv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[M.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[M.VIDEO].total_frames_decoded_in,total_decode_time:t[M.VIDEO].total_time_decoded_in};const n=c[K.FRAMES_DECODED],l=c[K.TOTAL_DECODE_TIME],a=l-t[M.VIDEO].total_time_decoded_in,s=n-t[M.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?a*1e3/s:0,frames_decoded:n,total_decode_time:l}},Gv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[M.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[M.VIDEO].total_frames_encoded_out,total_encode_time:t[M.VIDEO].total_time_encoded_out};const n=c[K.FRAMES_ENCODED],l=c[K.TOTAL_ENCODE_TIME],a=l-t[M.VIDEO].total_time_encoded_out,s=n-t[M.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&a?a*1e3/s:0,frames_encoded:n,total_encode_time:l}},Vf=(c,t,n,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_SENT))return{packetsSent:n[t].total_packets_out,packetsLost:n[t].total_packets_lost_out,bytesSent:n[t].total_KBytes_out};const a=Number(c[K.PACKETS_SENT])||0-(l?l[t].total_packets_out:0),s=a-n[t].total_packets_out,r=Number(c[K.BYTES_SENT])/1024-(l?l[t].total_KBytes_out:0),h=r-n[t].total_KBytes_out,d=c[K.TIMESTAMP]||Date.now(),_=l?l.timestamp:null;let g=n.timestamp;!g&&_&&(g=_);const T=g?d-g:0,S=T>0?h*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:h,kbsSent:S}},jf=(c,t,n,l)=>{let a=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)&&(a=Number(c[K.PACKETS_LOST])||0-(l?l[t].total_packets_lost_out:0),s=a-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,K.FRACTION_LOST)&&(r=Number(100*c[K.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:s,fractionLost:r}},qf=(c,t,n,l)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_RECEIVED))return{percent_packets_lost:n[t].percent_packets_lost_in,packetsReceived:n[t].total_packets_in,packetsLost:n[t].total_packets_lost_in,bytesReceived:n[t].total_KBytes_in};const a=Number(c[K.PACKETS_RECEIVED])||0-(l?l[t].total_packets_in:0),s=Number(c[K.PACKETS_LOST])||0-(l?l[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,h=a-n[t].total_packets_in,d=a!==n[t].total_packets_in?r*100/(r+h):0,_=Number(c[K.BYTES_RECEIVED])/1024-(l?l[t].total_KBytes_in:0),g=_-n[t].total_KBytes_in,T=c[K.TIMESTAMP]||Date.now(),S=l?l.timestamp:null;let E=n.timestamp;!E&&S&&(E=S);const C=E?T-E:0,A=C>0?g*.008*1024/C*1e3:0;return{percentPacketsLost:d,packetsReceived:a,deltaPacketsReceived:h,packetsLost:s,deltaPacketsLost:r,KBytesReceived:_,deltaKBytesReceived:g,kbsReceived:A}},Wv=c=>c[K.CANDIDATE_TYPE]!=="relay"?"":c[K.RELAY_PROTOCOL]||"",Kv=c=>{if(!Object.prototype.hasOwnProperty.call(c,K.NETWORK_TYPE))return Ki.WIFI;switch(c[K.NETWORK_TYPE]){case au.ETHERNET:return Ki.ETHERNET;case au.CELLULAR_4G:return Ki.CELLULAR_4G;case au.WIFI:return Ki.WIFI;default:return Ki.CELLULAR}},Bf=c=>!Object.prototype.hasOwnProperty.call(c,K.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,K.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[K.FRAME_WIDTH]||null,height:c[K.FRAME_HEIGHT]||null,framerate:c[K.FRAMES_PER_SECOND]},Yv=c=>{const t=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_REASON)?c[K.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[K.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,l=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_DURATIONS)?c[K.QUALITY_LIMITATION_DURATIONS]:null;return l&&Object.keys(l).forEach(a=>{l[a]>1e3&&(l[a]=Number(l[a]/1e3))}),{reason:t,durations:l,resolutionChanges:n}},Jv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(n?n[M.VIDEO].total_pli_sent_in:0),a=(c[K.NACK]||0)-(n?n[M.VIDEO].total_nack_sent_in:0);return{pliCount:l,nackCount:a,deltaPliCount:l-t[M.VIDEO].total_pli_sent_in,deltaNackCount:a-t[M.VIDEO].total_nack_sent_in}},zv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const l=(c[K.PLI]||0)-(n?n[M.VIDEO].total_pli_received_out:0),a=(c[K.NACK]||0)-(n?n[M.VIDEO].total_nack_received_out:0);return{pliCount:l,nackCount:a,deltaPliCount:l-t[M.VIDEO].total_pli_received_out,deltaNackCount:a-t[M.VIDEO].total_nack_received_out}},Xv=c=>({channels:c[K.CHANNELS]||null,clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null,sdp_fmtp_line:c[K.SDP_FMTP_LINE]||null}),Qv=c=>({clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null}),Zv=(c,t,n)=>{const l=(c[K.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),a=(c[K.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[K.TIMESTAMP]||Date.now(),r=l-t.data.total_KBytes_in,h=a-t.data.total_KBytes_out,d=n?n.timestamp:null;let _=t.timestamp;!_&&d&&(_=d);const g=_?s-_:0,T=g>0?r*.008*1024/g*1e3:0,S=g>0?h*.008*1024/g*1e3:0;return{total_KBytes_received:l,total_KBytes_sent:a,delta_KBytes_received:r,delta_KBytes_sent:h,kbs_speed_received:T,kbs_speed_sent:S}},eS=c=>{const t=c[K.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[K.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},tS=(c,t,n,l)=>{if(!c)return[];switch(c[K.TYPE]){case zt.CANDIDATE_PAIR:let a=!1;if(c[K.NOMINATED]&&c[K.STATE]===M.SUCCEEDED&&(a=!0,Ue(Vs,`analyze() - got stats ${c[K.TYPE]} for ${n}`,c),K.SELECTED in c&&!c[K.SELECTED]&&(a=!1)),a){const r=c[K.LOCAL_CANDIDATE_ID],h=c[K.REMOTE_CANDIDATE_ID],d=Zv(c,t,l),_=eS(c),g=qv(c,"data",l,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:h}},{type:ne.DATA,value:{total_KBytes_in:d.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:d.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:d.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:d.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:d.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:d.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:_.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:_.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case zt.LOCAL_CANDIDATE:if(c[K.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:Kv(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[K.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:Wv(c)}}];break;case zt.REMOTE_CANDIDATE:if(c[K.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[K.PROTOCOL]||""}}];break;case zt.INBOUND_RTP:{Ue(Vs,`analyze() - got stats ${c[K.TYPE]} for ${n}`,c);const r=c[K.SSRC],h=ct(r,t,$e.INBOUND);h&&(h.timestamp=t.timestamp);const d=ct(r,l,$e.INBOUND);if(d&&(d.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const _=qf(c,M.AUDIO,h,d),g=ho(c,M.AUDIO,h),T=c[K.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:_.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:_.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:_.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:_.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:_.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:_.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:_.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:_.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const _=Bv(c,h),g=qf(c,M.VIDEO,h,d),T=ho(c,M.VIDEO,h),S=c[K.DECODER_IMPLEMENTATION]||null,E=c[K.CODEC_ID]||null,C=Bf(c),A=Jv(c,h,d);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:E}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:r,type:ne.VIDEO,value:{decoder_in:S}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_decode_frame_in:_.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:_.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:_.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:A.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:C}}]}break}case zt.OUTBOUND_RTP:{Ue(Vs,`analyze() - got stats ${c[K.TYPE]} for ${n}`,c);const r=c[K.SSRC],h=ct(r,t,$e.OUTBOUND);h&&(h.timestamp=t.timestamp);const d=ct(r,l,$e.OUTBOUND);if(d&&(d.timestamp=l.timestamp),c[K.MEDIA_TYPE]===M.AUDIO){const _=c[K.CODEC_ID]||null,g=Vf(c,M.AUDIO,h,d);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:_}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[K.MEDIA_TYPE]===M.VIDEO){const _=c[K.ENCODER_IMPLEMENTATION]||null,g=c[K.CODEC_ID]||null,T=Gv(c,h),S=Bf(c),E=Yv(c),C=zv(c,h,d),A=Vf(c,M.VIDEO,h,d);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:A.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:A.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:A.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:A.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:A.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:_}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_received_out:C.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:C.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:C.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:C.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_out:S}},{ssrc:r,type:ne.VIDEO,value:{limitation_out:E}}]}break}case zt.MEDIA_SOURCE:{Ue(Vs,`analyze() - got stats ${c[K.TYPE]} for ${n}`,c);break}case zt.TRACK:{Ue(Vs,`analyze() - got stats ${c[K.TYPE]} for ${n}`,c);break}case zt.CODEC:const s=[];return Object.keys(t[M.AUDIO]).forEach(r=>{const h=t[M.AUDIO][r];if(h.codec_id_in===c[K.ID]||h.codec_id_out===c[K.ID]){Ue(Vs,`analyze() - got stats ${c[K.TYPE]} for ${n}`,c);const d=Xv(c);c[K.ID]===h.codec_id_in?s.push({ssrc:h.ssrc,type:ne.AUDIO,value:{codec_in:d}}):s.push({ssrc:h.ssrc,type:ne.AUDIO,value:{codec_out:d}})}}),Object.keys(t[M.VIDEO]).forEach(r=>{const h=t[M.VIDEO][r];if(h.codec_id_in===c[K.ID]||h.codec_id_out===c[K.ID]){Ue(Vs,`analyze() - got stats ${c[K.TYPE]} for ${n}`,c);const d=Qv(c);c[K.ID]===h.codec_id_in?s.push({ssrc:h.ssrc,type:ne.VIDEO,value:{codec_in:d}}):s.push({ssrc:h.ssrc,type:ne.VIDEO,value:{codec_out:d}})}}),s;case zt.REMOTE_INBOUND_RTP:{Ue(Vs,`analyze() - got stats ${c[K.TYPE]} for ${n}`,c);const r=c[K.SSRC],h=ct(r,t,$e.OUTBOUND),d=ct(r,l,$e.OUTBOUND);if(c[K.KIND]===M.AUDIO){const _=Ff(c,M.AUDIO,d,h),g=ho(c,M.AUDIO,h),T=jf(c,M.AUDIO,h,d);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[K.KIND]===M.VIDEO){const _=Ff(c,M.VIDEO,d,h),g=ho(c,M.VIDEO,h),T=jf(c,M.VIDEO,h,d);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Yo=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),sS=(c,t=M.AUDIO,n,l,a)=>{const s=ct(a,c,$e.INBOUND),r=ct(a,n,$e.INBOUND),h=ct(a,l,$e.INBOUND),d=[],_=[],g=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=h&&h[t].delta_jitter_ms_in||null,C=c.data.delta_rtt_connectivity_ms,A=n&&n.data.delta_rtt_connectivity_ms||null,R=l&&l.data.delta_rtt_connectivity_ms||null;C&&d.push(C),A&&d.push(A),R&&d.push(R),T&&_.push(T),n&&S&&_.push(S),l&&E&&_.push(E);const V=d.length>0?Gs(d):100,w=_.length>0?Gs(_):10,le=93.2-g,x=.18*le*le-27.9*le+1126.62,H=(V+w)/2,ve=H-177.3<0?0:1,pe=.024*H+.11*(H-177.3)*ve,P=x-pe;return Yo(P)},nS=(c,t=M.AUDIO,n,l,a)=>{const s=ct(a,c,$e.OUTBOUND),r=ct(a,n,$e.OUTBOUND),h=ct(a,l,$e.OUTBOUND),d=[],_=[],g=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=h&&h[t].delta_rtt_ms_out||null,C=s[t].delta_jitter_ms_out,A=r&&r[t].delta_jitter_ms_out||null,R=h&&h[t].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,w=n&&n.data.delta_rtt_connectivity_ms||null,le=l&&l.data.delta_rtt_connectivity_ms||null;T?d.push(T):V&&d.push(V),S?d.push(S):w&&d.push(w),E?d.push(E):le&&d.push(le),C&&_.push(C),n&&A&&_.push(A),l&&R&&_.push(R);const x=d.length>0?Gs(d):100,H=_.length>0?Gs(_):10,ve=93.2-g,pe=.18*ve*ve-27.9*ve+1126.62,P=(x+H)/2,N=P-177.3<0?0:1,q=.024*P+.11*(P-177.3)*N,j=pe-q;return Yo(j)},rS=(c,t=M.AUDIO,n,l,a)=>{const s=ct(a,c,$e.INBOUND),r=ct(a,n,$e.INBOUND),h=ct(a,l,$e.INBOUND),d=[],_=[],g=s[t].percent_packets_lost_in/100,T=s[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=h&&h[t].delta_jitter_ms_in||null,C=c.data.delta_rtt_connectivity_ms,A=n&&n.data.delta_rtt_connectivity_ms||null,R=l&&l.data.delta_rtt_connectivity_ms||null;C&&d.push(C),A&&d.push(A),R&&d.push(R),T&&_.push(T),r&&S&&_.push(S),h&&E&&_.push(E);const V=d.length>0?Gs(d):100,w=_.length>0?Gs(_):10,le=0,x=19.8,H=29.7,ve=30,pe=(V+w)/2+ve,P=pe-177.3<0?0:1,N=.024*pe+.11*(pe-177.3)*P,j=93.2-(le+x*Math.log(1+H*g)+N);return Yo(j)},iS=(c,t=M.AUDIO,n,l,a)=>{const s=ct(a,c,$e.OUTBOUND),r=ct(a,n,$e.OUTBOUND),h=ct(a,l,$e.OUTBOUND),d=[],_=[],g=s[t].percent_packets_lost_out/100,T=s[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=h&&h[t].delta_rtt_ms_out||null,C=s[t].delta_jitter_ms_out,A=r&&r[t].delta_jitter_ms_out||null,R=h&&h[t].delta_jitter_ms_out||null,V=c.data.delta_rtt_connectivity_ms,w=n&&n.data.delta_rtt_connectivity_ms||null,le=l&&l.data.delta_rtt_connectivity_ms||null;T?d.push(T):V&&d.push(V),S?d.push(S):w&&d.push(w),E?d.push(E):le&&d.push(le),C&&_.push(C),r&&A&&_.push(A),h&&R&&_.push(R);const x=d.length>0?Gs(d):100,H=_.length>0?Gs(_):10,ve=0,pe=19.8,P=29.7,N=30,q=(x+H)/2+N,j=q-177.3<0?0:1,Y=.024*q+.11*(q-177.3)*j,X=93.2-(ve+pe*Math.log(1+P*g)+Y);return Yo(X)};class lS{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=Mv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new jv(t),this._state=gs.IDLE,this.registerToPCEvents(),An(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,l,a){const s=(d,_)=>d===M.AUDIO?_===zt.INBOUND_RTP?{...kd}:{...Pd}:_===zt.INBOUND_RTP?{...Md}:{...Ld},r=Nv(n);r.pname=this._config.pname,r.call_id=this._config.cid,r.user_id=this._config.uid,r.count=n?n.count+1:1;let h=null;return t.forEach(d=>{!h&&d.timestamp&&(h=d.timestamp),tS(d,r,r.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=r[g.type][g.ssrc];T||(T=s(g.type,d.type),T.ssrc=g.ssrc,r[g.type][g.ssrc]=T),Object.keys(g.value).forEach(S=>{T[S]=g.value[S]})}else Object.keys(g.value).forEach(T=>{r[g.type][T]=g.value[T]})})}),r.timestamp=h,Object.keys(r[M.AUDIO]).forEach(d=>{const _=r[M.AUDIO][d];_.direction===$e.INBOUND?(_.mos_emodel_in=sS(r,M.AUDIO,n,l,_.ssrc),_.mos_in=rS(r,M.AUDIO,n,l,_.ssrc)):(_.mos_emodel_out=nS(r,M.AUDIO,n,l,_.ssrc),_.mos_out=iS(r,M.AUDIO,n,l,_.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const l=Date.now();setTimeout(async()=>{try{const a=Date.now()-l,s=Date.now(),r=await this._config.pc.getStats(),h=this.analyze(r,null,null,null),d=Date.now();h.experimental.time_to_measure_ms=d-s,h.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(h),Ue(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(a){n(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==gs.RUNNING||!this._config.pc)return Ue(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),n=await this._config.pc.getStats(),l=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return l.experimental.time_to_measure_ms=a-t,this._exporter.addReport(l),Ue(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(l),l}catch(t){return dr(this._moduleName,`got error ${t}`),null}}async start(){Ue(this._moduleName,"starting"),this.state=gs.RUNNING,this._startedTime=this._exporter.start(),Ue(this._moduleName,"started")}async mute(){this.state=gs.MUTED,Ue(this._moduleName,"muted")}async unmute(){this.state=gs.RUNNING,Ue(this._moduleName,"unmuted")}async stop(t){if(Ue(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=gs.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Ue(this._moduleName,"stopped")}registerCallback(t,n,l){t in this._callbacks?(this._callbacks[t]={callback:n,context:l},Ue(this._moduleName,`registered callback '${t}'`)):dr(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Ue(this._moduleName,`unregistered callback '${t}'`)):dr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&Du(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&Du(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,Ue(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,n,l,a){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:l,description:a})}async registerToPCEvents(){const{pc:t}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const n=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${n.length} devices found`,"Media Devices state")}catch{dr(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const l=t.iceConnectionState;l===Wi.CONNECTED||l===Wi.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===Wi.DISCONNECTED||l===Wi.FAILED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===Wi.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const l=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",l,"ICE gathering state")},t.ontrack=l=>{this.addCustomEvent(new Date().toJSON(),"call",`${l.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const n=t.getReceivers();if(n&&n.length>0){const l=n[0],{transport:a}=l;if(a){const{iceTransport:s}=a;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class oS{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||Pv(),this._moduleName=this._id,An(this._moduleName,"probe created"),this._config=t,this._collector=new lS(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(t){this._collector.state=t}addCustomEvent(t,n,l,a=new Date().toJSON()){this._collector.addCustomEvent(a,n,t,l)}get isRunning(){return this._collector.state===gs.RUNNING}get isIdle(){return this._collector.state===gs.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Oo(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Rt="engine ";class aS{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},An(Rt,`configured for probing every ${this._config.refreshEvery}ms`),An(Rt,`configured for starting after ${this._config.startAfter}ms`),An(Rt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ue(Rt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,n){if(!t)throw new Error("undefined peer connection");const l=Uv(t,n,this._config),a=new oS(l);return this._probes.push(a),Ue(Rt,`${this._probes.length} probes registered`),a}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===gs.RUNNING&&t.stop(),this._probes=this._probes.filter(n=>t.id!==n.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},n=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),l=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const s=Dv(),r=this._probes.filter(h=>h.isRunning);for(const h of r){const d=await h.collectStats();d&&s.probes.push(d),Ue(Rt,`got probe ${h.id}`),await $f(0)}return s.delta_time_to_measure_probes_ms=En(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=En(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=En(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=En(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=En(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=En(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=En(s.probes,"video","total_time_encoded_out"),s};for(Ue(Rt,"starting to collect"),t(),Ue(Rt,"generating reference reports..."),await n(),Ue(Rt,"reference reports generated"),this._startedTime=Date.now();l();)if(Ue(Rt,`wait ${this._config.refreshEvery}ms before collecting`),await $f(this._config.refreshEvery),l()){Ue(Rt,"collecting...");const s=Date.now(),r=await a(),h=Date.now();r.delta_time_consumed_to_measure_ms=h-s,this.fireOnReports(r),Ue(Rt,"collected")}Ue(Rt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=l=>{this._probes.forEach(a=>{a.stop(l)})};An(Rt,"stop collecting"),n(t)}registerCallback(t,n,l){t in this._callbacks?(this._callbacks[t]={callback:n,context:l},Ue(Rt,`registered callback '${t}'`)):dr(Rt,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Ue(this._moduleName,`unregistered callback '${t}'`)):dr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&Du(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const uS="interface ";class cS{constructor(t){this._config=kv(t),An(uS,`welcome to ${this._config.name} version ${this._config.version}`),yv(this._config.verbose||!1),this._engine=new aS(this._config)}setupLogLevel(t){Cv(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,n){return this._engine.addNewProbe(t,n)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function fS(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,l)=>{const a=l;return{...n,[a]:c[a]}},{})}const dS=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],hS={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class _S{constructor(t){this.intervals={},this.analysers={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}async start(t,n,l){n&&n.getTracks().length&&await this.beginCalculation(t,n,l)}stop(t){this.clearVolumeInterval(t),this.analysers[t]&&typeof this.analysers[t].disconnect=="function"&&(this.analysers[t].disconnect(),delete this.analysers[t])}clearVolumeInterval(t){this.intervals[t]&&(clearInterval(this.intervals[t]),delete this.intervals[t])}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{this.stop(t)}),this.intervals={},this.analysers={}}async beginCalculation(t,n,l){this.clearVolumeInterval(l);const a=t.createAnalyser(),s=t.createMediaStreamSource(n);a.smoothingTimeConstant=.8,a.fftSize=1024,s.connect(a),this.analysers[l]=a,this.intervals[l]=setInterval(()=>{const r=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(r);let h=0;const d=r.length;for(let g=0;g<d;g++)h+=r[g];const _=h/d;this.onChangeFunction(l,_)},this.emitInterval)}}class pS{constructor(){this.resumePromise=null,this.context=new AudioContext,this.setupErrorHandling()}setupErrorHandling(){!this.context||typeof this.context.addEventListener!="function"||this.context.addEventListener("statechange",()=>{(this.context.state==="interrupted"||this.context.state==="closed")&&console.warn(`[ManagedAudioContext] AudioContext state changed to: ${this.context.state}`)})}createNewContext(){return console.log("[ManagedAudioContext] Creating new AudioContext instance"),this.context=new AudioContext,this.setupErrorHandling(),this.context}async getContext(){if(this.context.state==="closed")return console.warn("[ManagedAudioContext] AudioContext is closed, creating new instance"),this.createNewContext();if(this.context.state==="interrupted"){console.warn("[ManagedAudioContext] AudioContext is interrupted, attempting to resume");try{this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(t=>{console.error("[ManagedAudioContext] Failed to resume interrupted context:",t),this.resumePromise=null,this.createNewContext()})),await this.resumePromise}catch(t){return console.error("[ManagedAudioContext] Error resuming context, creating new one:",t),this.createNewContext()}}return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(t=>{throw console.error("[ManagedAudioContext] Failed to resume suspended context:",t),this.resumePromise=null,t})),await this.resumePromise),this.context.state==="closed"?(console.warn("[ManagedAudioContext] Context closed after resume attempt, creating new instance"),this.createNewContext()):this.context}}const _o={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},mS=0;function cu(c,t){const n=new AudioContext,l=n.createMediaStreamSource(c),a=n.createMediaStreamSource(new MediaStream([t])),s=n.createMediaStreamDestination();return l.connect(s),a.connect(s),s.stream}class gS{constructor(t){var n;this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.isCallWaitingEnabled=!0,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.conferenceNodes={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.vadSession=null,this.vadSessionState={currentMode:"clean",isSpeaking:!1},this.vadInterval=null,this.vadMrsInterval=null,this.vadSessionGeneration=0,this.ringbackTimers={},this.ringbackAudioContexts={},this.ringbackSessionProgressReceived={},this.hangupBeepContext=null,this.managedAudioContext=new pS,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new _S({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices(),this.processVADConfiguration(((n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)||{}),this.setupVADInstance()}setVADConfiguration(t){if(!this.MicVAD)throw new Error("VAD module is not provided in the initial configuration");const n=Object.keys(t);for(const l of n)this.noiseReduction[l]=t[l];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,l;const t=(l=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:l.vadModule;t&&t.MicVAD?(this.MicVAD=t.MicVAD,console.log("✅ VAD module loaded successfully")):this.noiseReduction.mode!=="disabled"&&(console.warn("⚠️ Noise reduction is enabled but VAD module is not provided. To use VAD features, please install @ricky0123/vad-web and pass it via configuration.noiseReductionOptions.vadModule option."),this.noiseReduction.mode="disabled")}processVADConfiguration(t){this.noiseReduction={mode:t.mode||"disabled",checkEveryMs:t.checkEveryMs||500,noiseCheckInterval:t.noiseCheckInterval||2e3,noiseThreshold:t.noiseThreshold||.004,vadConfig:t.vadConfig||{},baseAssetPath:t.baseAssetPath||"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:t.onnxWASMBasePath||"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/"}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(l=>!l.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return Nd()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(_o.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(_o.SELECTED_OUTPUT_DEVICE)||"default";try{const l=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(t),await this.setSpeaker(n),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),l.getTracks().forEach(s=>s.stop())}catch(l){console.error(l)}}async cleanupConferenceNodes(t){const n=this.conferenceNodes[t];if(!n)return;let l=0;n.sources.forEach((r,h)=>{var d;try{r.disconnect(),l++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting source ${h}:`,_),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting source ${h}:`,_)}});let a=0;n.destinations.forEach((r,h)=>{var d;try{r.disconnect(),a++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${h}:`,_),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting destination ${h}:`,_)}});let s=0;n.gains.forEach((r,h)=>{var d;try{r.disconnect(),s++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${h}:`,_),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting gain ${h}:`,_)}}),delete this.conferenceNodes[t]}setCallTime(t){const n={...t};delete n.callId,this.callTime={...this.callTime,[t.callId]:n},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const n={...this.callTime};delete n[t],this.callTime={...n},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,n){this.timeIntervals={...this.timeIntervals,[t]:n}}removeTimeInterval(t){const n={...this.timeIntervals};n[t]&&(clearInterval(n[t]),delete n[t],this.timeIntervals={...n})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,n){this.context.emit("changeCallVolume",{callId:t,volume:n})}getNoiseReductionMode(){return this.noiseReduction.mode}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,n){if(!/^[A-D0-9*#]+$/g.test(n))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[t].sendDTMF(n)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const n=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(l=>l.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:l}){const a=this.extendedCalls[t];if(!a)return;a._automaticHold=l??!1;const s=new Promise((r,h)=>{const d=setTimeout(()=>{h(new Error("Hold operation timeout"))},5e3),_=()=>{clearTimeout(d),a.putOnHoldTimestamp=n?Date.now():void 0,r()},g=T=>{clearTimeout(d),h(T)};try{n?(this.stopSessionVad(),a.hold({},_)):a.unhold({},_)}catch(T){g(T)}});try{await s,this.updateCall(a);const r=Object.values(this.extendedCalls).filter(h=>h.roomId===a.roomId&&(n?t!==h._id:!0));r.length>1&&await this.doConference(r)}catch(r){throw console.error("Hold operation failed:",r),r}}holdCall(t,n=!1){return this.processHold({callId:t,automatic:n,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===mS).forEach(t=>this.terminateCall(t._id))}answerCall(t){const n=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),n.answer(this.sipOptions),this.updateCall(n),this.setActiveRoom(n.roomId),n.connection.addEventListener("track",l=>{this.triggerAddStream(l,n)})}async moveCall(t,n){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:n}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=Uf(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const l={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...l}},this.context.emit("updateRoom",{room:l,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,a=t.request.getHeader("Call-Info");return a&&n.test(a)}refreshRemotePartyId(t,n){const l=n.getHeader("Remote-Party-ID");if(!l)return!1;let a=!1;const s=Pf(l);s!==null&&t._remote_party_display_name!==s&&(t._remote_party_display_name=s,a=!0);const r=Mf(l);return r!==null&&t._remote_party_uri_user!==r&&(t._remote_party_uri_user=r,a=!0),a}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:Uf(t)},this.extendedCalls[t._id]=t,n&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const l={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(l.isMoving=t.isMoving),t.isTransferring!==void 0&&(l.isTransferring=t.isTransferring),t.isMerging!==void 0&&(l.isMerging=t.isMerging),t.isTransferred!==void 0&&(l.isTransferred=t.isTransferred),this.callStatus={...this.callStatus,[t.callId]:{...l}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const n={...this.callStatus};delete n[t],this.callStatus={...n},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}async setupActiveStream(){const t=await ru(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);t.getTracks().forEach(n=>n.enabled=!this.isMuted),await this.setActiveStream(t)}async getActiveStream(){const t=await ru(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(n=>n.enabled=!this.isMuted),await this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:l})=>l===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(l=>l.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async l=>{await this.setupActiveStream();const a=this.activeStream;l.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(l)}):await this.doConference(n)}async setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===t))return;this.setSelectedOutputDevice(t);const n=Object.values(this.extendedCalls);if(n.length===0)return;const l=n.filter(a=>a.roomId===this.currentActiveRoomId);l.length===1?n.forEach(a=>{var s;(s=a.audioTag)==null||s.setSinkId(t),this.updateCall(a)}):await this.doConference(l)}removeRoom(t){const n={...this.activeRooms},l={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:l,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(n=>n.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}async startNoiseMonitor({stream:t,onNoiseDetected:n,onNoiseStop:l}){var _,g,T;let a;try{a=await this.managedAudioContext.getContext()}catch(S){console.error("[startNoiseMonitor] Failed to get AudioContext:",S),(_=this.context.logger)==null||_.error("[startNoiseMonitor] Failed to get AudioContext:",S);return}let s,r;try{s=a.createMediaStreamSource(t.clone()),r=a.createAnalyser()}catch(S){console.error("[startNoiseMonitor] Failed to create audio nodes:",S),console.error("[startNoiseMonitor] AudioContext state:",a.state),(g=this.context.logger)==null||g.error("[startNoiseMonitor] Failed to create audio nodes:",S),(T=this.context.logger)==null||T.error("[startNoiseMonitor] AudioContext state:",a.state);return}r.fftSize=1024;const h=new Float32Array(r.fftSize);s.connect(r);const d=[];this.vadInterval&&(clearInterval(this.vadInterval),this.vadInterval=null),this.vadMrsInterval&&(clearInterval(this.vadMrsInterval),this.vadMrsInterval=null),this.vadMrsInterval=setInterval(()=>{r.getFloatTimeDomainData(h);const S=mv(h);d.push(S);const E=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);d.length>E&&d.shift()},this.noiseReduction.checkEveryMs),this.vadInterval=setInterval(()=>{var A;if(d.length===0)return;const S=d.reduce((R,V)=>R+V,0)/d.length,E=this.vadSessionState;if(!E){console.warn("[startNoiseMonitor] State not found, stopping interval"),(A=this.context.logger)==null||A.warn("[startNoiseMonitor] State not found, stopping interval"),this.vadInterval&&(clearInterval(this.vadInterval),this.vadInterval=null),this.vadMrsInterval&&(clearInterval(this.vadMrsInterval),this.vadMrsInterval=null);return}const C=S>this.noiseReduction.noiseThreshold;E.isSpeaking||(C&&E.currentMode==="clean"?(E.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",!0),n()):!C&&E.currentMode==="noisy"&&(E.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",!1),l()))},this.noiseReduction.noiseCheckInterval)}async processVADForActiveStream(t={}){var g;const n=this.activeStream;this.stopSessionVad();const l=this.vadSessionGeneration,a=()=>l!==this.vadSessionGeneration;this.vadSessionState={currentMode:"clean",isSpeaking:!1};const s=await this.managedAudioContext.getContext();if(a())return;const r=await gv(n,s,150);if(a())return;let h=!1;const d=Object.values(this.extendedCalls).filter(T=>T.roomId===this.currentActiveRoomId),_=await this.MicVAD.new({getStream:()=>new Promise(T=>T(n)),pauseStream:async()=>{},resumeStream:async T=>T,...hS,...this.noiseReduction.vadConfig,baseAssetPath:this.noiseReduction.baseAssetPath,onnxWASMBasePath:this.noiseReduction.onnxWASMBasePath,onFrameProcessed:()=>{var T,S;if(!a()&&!h){if(h=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){if(t&&Object.keys(t).length)Object.keys(t).forEach(E=>{const C=this.extendedCalls[E];if(C&&C.connection.getSenders()[0]){const A=cu(r.stream,t[E]);C.connection.getSenders()[0].replaceTrack(A.getAudioTracks()[0])}});else{const E=d[0],C=(T=E==null?void 0:E.connection)==null?void 0:T.getSenders()[0],A=r.stream.getAudioTracks()[0];C&&C.replaceTrack(A)}return}if(!this.vadSessionState){console.error("[processVAD] CRITICAL: State not found"),(S=this.context.logger)==null||S.error("[processVAD] CRITICAL: State not found");return}this.startNoiseMonitor({stream:n,onNoiseDetected:async()=>{var E;if(console.log("[processVad] - Replace track with Vad Controlled"),(E=this.context.logger)==null||E.log("[processVad] - Replace track with Vad Controlled"),t&&Object.keys(t).length)Object.keys(t).forEach(C=>{const A=this.extendedCalls[C];if(A&&A.connection.getSenders()[0]){const R=cu(r.stream,t[C]);A.connection.getSenders()[0].replaceTrack(R.getAudioTracks()[0])}});else{const C=d[0];C.connection.getSenders()[0]&&C.connection.getSenders()[0].replaceTrack(r.stream.getAudioTracks()[0])}},onNoiseStop:async()=>{if(console.log("Replace track with Original"),t&&Object.keys(t).length)Object.keys(t).forEach(E=>{const C=this.extendedCalls[E];if(!C)return;const A=C.connection.getSenders()[0];if(A&&A.track&&A.transport&&A.transport.state!=="closed"&&A.transport.state!=="failed"){const R=cu(n,t[E]);A.replaceTrack(R.getAudioTracks()[0])}});else{const E=d[0].connection.getSenders()[0];E&&E.track&&E.transport&&E.transport.state!=="closed"&&E.transport.state!=="failed"&&E.replaceTrack(n.getAudioTracks()[0])}}})}},onSpeechStart:()=>{a()||(console.log("🎤 Speech started"),r.setSpeaking(!0),this.vadSessionState.isSpeaking=!0)},onSpeechEnd:()=>{a()||(console.log("🛑 Speech end"),r.setSpeaking(!1),this.vadSessionState.isSpeaking=!1)}});if(a()){try{_.pause()}catch(T){(g=this.context.logger)==null||g.error("[processVADForActiveStream] Error pausing stale vadSession:",T)}return}this.vadSession&&(this.vadSession.pause(),this.vadSession=null),this.vadSession=_,_.start()}stopSessionVad(){this.vadSessionGeneration++,this.vadSession&&(this.vadSession.pause(),this.vadSession=null),this.vadInterval&&(clearInterval(this.vadInterval),this.vadInterval=null),this.vadMrsInterval&&(clearInterval(this.vadMrsInterval),this.vadMrsInterval=null),this.vadSessionState&&(this.vadSessionState={currentMode:"clean",isSpeaking:!1},this.context.emit("changeNoiseReductionState",!1))}async roomReconfigure(t){var a,s,r,h;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(d=>d.roomId===t),l=this.currentActiveRoomId===t;if(console.log("[roomReconfigure] - Calls In Room:",n),(a=this.context.logger)==null||a.log("[roomReconfigure] - Calls In Room:",n),n.forEach((d,_)=>{if(d.audioTag){d.connection.getReceivers().forEach(T=>{T.track.enabled=!d.localMuted}),l&&this.muteReconfigure(d);const g=!l;d.audioTag.muted=g,this.updateCall(d)}}),n.length===0){!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t),console.log("[roomReconfigure] - Delete empty room",t),(s=this.context.logger)==null||s.log("[roomReconfigure] - Delete empty room",t),this.deleteRoomIfEmpty(t);return}if(n.length===1&&!l){const d=n[0];d.isOnHold().local||await this.holdCall(d._id,!0),!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}if(n.length===1&&l){const d=n[0];d.isOnHold().local&&d._automaticHold&&await this.unholdCall(d._id);const T=(((r=d.connection)==null?void 0:r.getSenders())||[])[0];if(d.connection&&T)try{await this.setupActiveStream();const E=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&(console.log("[roomReconfigure] - Call processVAD from roomReconfigure"),(h=this.context.logger)==null||h.log("[roomReconfigure] - Call processVAD from roomReconfigure"),this.processVADForActiveStream());const C=E.getTracks();await T.replaceTrack(C[0]),this.muteReconfigure(d)}catch(E){console.error(E)}!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}n.length>1&&await this.doConference(n)}async doConference(t){var g,T,S,E,C,A,R,V;if(console.log("[doConference] - In doConference, sessions:",t),(g=this.context.logger)==null||g.log("[doConference] - In doConference, sessions:",t),t.length===0)return;const n=t[0].roomId,l=this.currentActiveRoomId===n;if(t.find(w=>w.roomId!==n))return;let s;try{s=await this.managedAudioContext.getContext()}catch(w){console.error("[doConference] Failed to get AudioContext:",w),(T=this.context.logger)==null||T.error("[doConference] Failed to get AudioContext:",w);return}const r=s.state;if(r!=="running")if(console.error(`[doConference] ERROR: AudioContext is not running! State: ${r}`),(S=this.context.logger)==null||S.error(`[doConference] ERROR: AudioContext is not running! State: ${r}`),r==="suspended"||r==="interrupted")try{await s.resume();const w=s.state;if(w!=="running"){console.error(`[doConference] Failed to resume AudioContext, state: ${w}`),(E=this.context.logger)==null||E.error(`[doConference] Failed to resume AudioContext, state: ${w}`);return}}catch(w){console.error("[doConference] Error resuming AudioContext:",w),(C=this.context.logger)==null||C.error("[doConference] Error resuming AudioContext:",w);return}else if(r==="closed"){console.error("[doConference] AudioContext is closed, cannot proceed"),(A=this.context.logger)==null||A.error("[doConference] AudioContext is closed, cannot proceed");return}else return;await this.cleanupConferenceNodes(n),this.conferenceNodes[n]={sources:new Map,destinations:new Map,gains:new Map};const h=this.conferenceNodes[n],d=new Map;console.log("[doConference] - Before sessions forEach, sessions:",t),(R=this.context.logger)==null||R.log("[doConference] - Before sessions forEach, sessions:",t),t.forEach((w,le)=>{var x,H,ve;if(console.log("[doConference] - In sessions forEach, iteration for",w._id),(x=this.context.logger)==null||x.log("[doConference] - In sessions forEach, iteration for",w._id),w&&w.connection){const pe=w.connection.getReceivers();console.log("[doConference] - Receivers list length for",w._id,pe.length),(H=this.context.logger)==null||H.log("[doConference] - Receivers list length for",w._id,pe.length),pe.forEach((P,N)=>{var Y,F,X,U,k,B;P.track.enabled=!w.localMuted;const q=(Y=P.track)==null?void 0:Y.id;(F=P.track)==null||F.readyState,(X=P.track)==null||X.kind;const j=`${w._id}-${q}`;console.log("[doConference] - Gathering receiver tracks",w._id),console.log("[doConference] - Receiver track readyState",P.track.readyState),(U=this.context.logger)==null||U.log("[doConference] - Gathering receiver tracks",w._id),(k=this.context.logger)==null||k.log("[doConference] - Receiver track readyState",P.track.readyState),P.track&&P.track.readyState==="live"&&(console.log("[doConference] - Gathered receiver track",w._id),(B=this.context.logger)==null||B.log("[doConference] - Gathered receiver track",w._id),d.set(j,P.track))})}else console.log("[doConference] - No session or RTC connection, session:",w),(ve=this.context.logger)==null||ve.log("[doConference] - No session or RTC connection, session:",w)}),await this.setupActiveStream();const _={};await Sv.forEach(t,async(w,le)=>{var Y,F,X,U,k;if(!w||!w.connection){console.log("[doConference] - Return because of no session or connection, session:",w),(Y=this.context.logger)==null||Y.log("[doConference] - Return because of no session or connection, session:",w);return}const x=s.createMediaStreamDestination(),H=s.createMediaStreamDestination();h.destinations.set(w._id,x),h.destinations.set(`${w._id}-others`,H);const ve=w.connection.getReceivers(),pe=ve.length>0;console.log(`[doConference] Session ${w._id} has ${ve.length} receivers`),(F=this.context.logger)==null||F.log(`[doConference] Session ${w._id} has ${ve.length} receivers`),pe||(console.warn(`[doConference] Session ${w._id} has no receivers yet. Will re-configure when track arrives.`),(X=this.context.logger)==null||X.warn(`[doConference] Session ${w._id} has no receivers yet. Will re-configure when track arrives.`)),d.forEach((B,He)=>{var Q,W,G;if(console.log("[doConference] - In forEach receiverTracks for",w._id),(Q=this.context.logger)==null||Q.log("[doConference] - In forEach receiverTracks for",w._id),!He.startsWith(w._id)){if(!B||B.readyState!=="live"){console.warn(`[doConference] Skipping invalid track ${(B==null?void 0:B.id)||"unknown"} for session ${w._id}`),(W=this.context.logger)==null||W.warn(`[doConference] Skipping invalid track ${(B==null?void 0:B.id)||"unknown"} for session ${w._id}`);return}try{const re=s.createMediaStreamSource(new MediaStream([B])),_e=s.createGain(),Ie=`${w._id}-${He}`;re.connect(_e),_e.connect(x),_e.connect(H),console.log("[doConference] - In forEach connect track for",w._id),(G=this.context.logger)==null||G.log("[doConference] - In forEach connect track for",w._id),h.sources.set(Ie,re),h.gains.set(Ie,_e)}catch(re){console.error(re)}}});const P=H.stream.getTracks();if(_[w._id]=P[0],l&&this.activeStreamValue)try{const B=this.activeStream,He=s.createMediaStreamSource(B),Q=s.createGain(),W=`${w._id}-local`;He.connect(Q),Q.connect(x),h.sources.set(W,He),h.gains.set(W,Q)}catch(B){console.error(B)}else l&&(console.error(`Host room but no activeStreamValue - skipping host microphone for session ${w._id}`),(U=this.context.logger)==null||U.error(`Host room but no activeStreamValue - skipping host microphone for session ${w._id}`));const q=w.connection.getSenders()[0],j=x.stream.getTracks();if(q&&j[0])try{console.log("[doConference] - Final replaceTrack for",w._id),(k=this.context.logger)==null||k.log("[doConference] - Final replaceTrack for",w._id),console.log("RIGHT 2 initial replace for ",w._id),await q.replaceTrack(j[0]),this.muteReconfigure(w)}catch(B){console.error(B)}}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&(console.log("[doConference] - Call processVAD from doConference"),(V=this.context.logger)==null||V.log("[doConference] - Call processVAD from doConference"),this.processVADForActiveStream(_))}processCallerMute(t,n){const l=this.extendedCalls[t];l&&l.connection.getReceivers().length&&(l.localMuted=n,l.connection.getReceivers().forEach(a=>{a.track.enabled=!n}),this.updateCall(l))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const n=this.extendedCalls[t];n._status===4?n.terminate({status_code:603,reason_phrase:"Decline"}):n._status!==8&&n.terminate()}handleSipResponseForRingback(t,n){var s,r,h,d,_,g;let l=null;if(this.extendedCalls[t])l=t;else{const T=Object.values(this.extendedCalls).find(S=>S.id===t||S._id===t||S.id&&S.id.includes(t)||S._id&&S._id.includes(t));T&&(l=T.id)}if(!l){(s=this.context.logger)==null||s.warn(`[handleSipResponseForRingback] Could not find session for identifier ${t}, status ${n}`);return}const a=this.extendedCalls[l];if(!a){(r=this.context.logger)==null||r.warn(`[handleSipResponseForRingback] Call not found in extendedCalls for ${l}`);return}if(a.direction==="outgoing"){if(a._is_confirmed){(h=this.context.logger)==null||h.log(`[handleSipResponseForRingback] Call ${l} is already confirmed, skipping ringback tone`);return}if(this.timeIntervals[l]||this.startCallTimer(l),n===lu.TRYING||n===lu.RINGING){if(this.ringbackTimers[l])return;this.ringbackSessionProgressReceived[l]=!1,this.ringbackTimers[l]=setTimeout(()=>{var S,E;const T=this.extendedCalls[l];T&&!T._is_confirmed&&!this.ringbackSessionProgressReceived[l]?(this.startLocalRingbackTone(l),(S=this.context.logger)==null||S.log(`[handleSipResponseForRingback] Started local ringback tone for call ${l} after 2 seconds without 183`)):T&&T._is_confirmed&&((E=this.context.logger)==null||E.log(`[handleSipResponseForRingback] Call ${l} was confirmed during 2-second wait, skipping ringback tone`)),delete this.ringbackTimers[l]},2e3),(d=this.context.logger)==null||d.log(`[handleSipResponseForRingback] Started 2-second timer for call ${l} after receiving ${n}`)}n===lu.SESSION_PROGRESS&&(this.ringbackSessionProgressReceived[l]=!0,this.ringbackTimers[l]&&(clearTimeout(this.ringbackTimers[l]),delete this.ringbackTimers[l],(_=this.context.logger)==null||_.log(`[handleSipResponseForRingback] Cancelled ringback timer for call ${l} - 183 received`)),this.stopLocalRingbackTone(l),(g=this.context.logger)==null||g.log(`[handleSipResponseForRingback] Stopped local ringback tone for call ${l} - 183 received with SDP`))}}async startLocalRingbackTone(t){var n,l;if(!this.ringbackAudioContexts[t])try{const a=await this.managedAudioContext.getContext(),s=a.createOscillator(),r=a.createOscillator(),h=a.createGain();s.frequency.value=440,r.frequency.value=480,s.type="sine",r.type="sine",h.gain.value=0,s.connect(h),r.connect(h),h.connect(a.destination),s.start(),r.start();const d={context:a,oscillator1:s,oscillator2:r,gainNode:h,intervalId:null};this.ringbackAudioContexts[t]=d;const _=()=>{if(!this.ringbackAudioContexts[t])return;const T=a.currentTime;h.gain.cancelScheduledValues(T),h.gain.setValueAtTime(0,T),h.gain.linearRampToValueAtTime(.3,T+.05),h.gain.linearRampToValueAtTime(0,T+1)};_();const g=setInterval(()=>{if(!this.ringbackAudioContexts[t]){clearInterval(g);return}_()},4e3);d.intervalId=g,this.ringbackAudioContexts[t]=d,(n=this.context.logger)==null||n.log(`[startLocalRingbackTone] Started ringback tone for session ${t}`)}catch(a){(l=this.context.logger)==null||l.error(`[startLocalRingbackTone] Error starting ringback tone for session ${t}:`,a),console.error(`[startLocalRingbackTone] Error starting ringback tone for session ${t}:`,a)}}stopLocalRingbackTone(t){var l,a;const n=this.ringbackAudioContexts[t];if(n)try{n.intervalId&&clearInterval(n.intervalId),n.oscillator1&&n.oscillator1.stop(),n.oscillator2&&n.oscillator2.stop(),n.gainNode&&n.gainNode.disconnect(),delete this.ringbackAudioContexts[t],(l=this.context.logger)==null||l.log(`[stopLocalRingbackTone] Stopped ringback tone for session ${t}`)}catch(s){(a=this.context.logger)==null||a.error(`[stopLocalRingbackTone] Error stopping ringback tone for session ${t}:`,s),console.error(`[stopLocalRingbackTone] Error stopping ringback tone for session ${t}:`,s),delete this.ringbackAudioContexts[t]}}cleanupRingbackTone(t){this.ringbackTimers[t]&&(clearTimeout(this.ringbackTimers[t]),delete this.ringbackTimers[t]),this.stopLocalRingbackTone(t),delete this.ringbackSessionProgressReceived[t]}async playHangupBeep(){var t,n;if(!this.hangupBeepContext)try{const l=await this.managedAudioContext.getContext(),a=l.createOscillator(),s=l.createGain();a.frequency.value=800,a.type="sine",s.gain.value=0,a.connect(s),s.connect(l.destination),this.hangupBeepContext={context:l,oscillator:a,gainNode:s},a.start();const r=l.currentTime;s.gain.setValueAtTime(0,r),s.gain.linearRampToValueAtTime(.3,r+.01),s.gain.setValueAtTime(.3,r+.15),s.gain.linearRampToValueAtTime(0,r+.2),a.stop(r+.2),setTimeout(()=>{if(this.hangupBeepContext){try{this.hangupBeepContext.oscillator&&this.hangupBeepContext.oscillator.disconnect(),this.hangupBeepContext.gainNode&&this.hangupBeepContext.gainNode.disconnect()}catch(h){console.error("[playHangupBeep] Cleanup playing hangup beep error:",h)}this.hangupBeepContext=null}},250),(t=this.context.logger)==null||t.log("[playHangupBeep] Played hangup beep")}catch(l){(n=this.context.logger)==null||n.error("[playHangupBeep] Error playing hangup beep:",l),console.error("[playHangupBeep] Error playing hangup beep:",l),this.hangupBeepContext=null}}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const l=this.extendedCalls[t];if(!l._is_confirmed&&!l._is_canceled){const a=`sip:${n}@${this.context.sipDomain}`;l.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:t,isTransferring:!0,isTransferred:!1}),l.refer(`sip:${n}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(l)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const l=n[0],a=n[1];!l||!a||(this.updateCallStatus({callId:l._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),l.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(l))}mergeCallByIds(t,n){const l=Object.values(this.extendedCalls).find(s=>s._id===t),a=Object.values(this.extendedCalls).find(s=>s._id===n);if(!l||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),l.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(l)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}setCallWaiting(t){this.isCallWaitingEnabled=t,this.context.emit("changeIsCallWaiting",t)}startCallTimer(t){this.removeTimeInterval(t);const n={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(n);const l=setInterval(()=>{const a={...this.callTime[t]},s=pv(a);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,l)}async setActiveRoom(t){const n=this.currentActiveRoomId;t!==n&&(this.currentActiveRoomId=t,await this.roomReconfigure(n),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var _,g;const n=t.session;if(this.getActiveCalls[n.id]!==void 0)return;const a=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:a};n.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(_=n._remote_identity)==null?void 0:_._uri)==null?void 0:g._user),s.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(n.id))}),this.context.subscribe(Xt.CALL_FAILED,T=>{n.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):n.direction==="outgoing"&&n.once("confirmed",()=>{this.startCallTimer(n.id)});const r=n,h=this.hasAutoAnswerHeaders(t),d=r.direction==="incoming"&&!this.hasActiveCalls&&(h||this.autoAnswer);r.roomId=a,r.localMuted=!1,r.autoAnswer=d,d?this.addCall(r,!1):this.addCall(r),this.addCallStatus(n.id),this.addRoom(s),d&&setTimeout(()=>{this.answerCall(r._id)},250)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const l={...this.extendedCalls};delete l[t],this.extendedCalls={...l},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){const n=this.extendedCalls[t._id];if(!n)return;this.stopVUMeter("origin"),this.stopVUMeter(t._id);const l=n.roomId;this.removeCall(t._id),this.roomReconfigure(l).then(()=>{}).catch(a=>{console.error("Error reconfiguring room after call removal:",a)})}shouldTerminateNewSession(t){if(t.session.direction==="outgoing")return!1;const l=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||l}async newRTCSessionCallback(t){const n=t.session,l=n.direction==="incoming"?t.request.getHeader("Remote-Party-ID"):null;if(n._remote_party_display_name=Pf(l),n._remote_party_uri_user=Mf(l),this.shouldTerminateNewSession(t)){n.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}this.context.triggerListener({listenerType:Xt.NEW_CALL,session:n,event:t}),n.on("ended",r=>{var d,_,g;if(this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(_=(d=n._remote_identity)==null?void 0:d._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:n,event:r}),n._is_confirmed&&this.playHangupBeep(),n.connection){const T=n.connection.connectionState;(T==="closed"||T==="disconnected")&&this.context.emit("connectionStateChange",{session:n,connectionState:T})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(),this.cleanupRingbackTone(n.id);const h=this.getActiveCalls[n.id];h&&this.activeCallListRemove(h),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(T=>T.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("progress",r=>{var h,d;this.context.logger.log("Session in progress for",(d=(h=n._remote_identity)==null?void 0:h._uri)==null?void 0:d._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:n,event:r})}),n.on("failed",r=>{var d,_,g;if(this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(_=(d=n._remote_identity)==null?void 0:d._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:n,event:r}),n.connection){const T=n.connection.connectionState;(T==="closed"||T==="disconnected")&&this.context.emit("connectionStateChange",{session:n,connectionState:T})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(),this.cleanupRingbackTone(n.id),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const h=this.getActiveCalls[n.id];h&&this.activeCallListRemove(h),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(T=>T.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("confirmed",r=>{var h,d;this.context.logger.log("Session confirmed for",(d=(h=n._remote_identity)==null?void 0:h._uri)==null?void 0:d._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:r}),this.updateCall(n),this.cleanupRingbackTone(n.id),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)});const a=r=>{this.refreshRemotePartyId(n,r.request)&&this.updateCall(n)};n.on("reinvite",a),n.on("update",a);const s=r=>{r&&r.addEventListener("connectionstatechange",h=>{this.context.emit("connectionStateChange",{session:n,connectionState:r.connectionState})})};if(n.connection&&s(n.connection),n.on("peerconnection",({peerconnection:r})=>{s(r)}),await this.setupCall(t),n.direction==="outgoing"){const r=this.getActiveCalls[n.id].roomId;await this.setActiveRoom(r)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(n=>{n.audioTag&&(n.audioTag.volume=t,this.updateCall(n))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(_o.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(_o.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const n={...t};delete n.callId,this.callMetrics={...this.callMetrics,[t.callId]:n},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const n={...this.callMetrics};delete n[t],this.callMetrics={...n},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const n=new cS(this.metricConfig),l=n.createProbe(t.connection,{cid:t._id}),a=[];let s;l.onreport=r=>{Object.entries(r.audio).forEach(([_,g])=>{g.direction==="inbound"&&!a.includes(_)&&(a.push(_),s=_)});const h=r.audio[s];if(!h)return;const d=fS(h,dS);d.callId=t._id,this.setCallMetrics(d)},this.context.subscribe(Xt.CALL_ENDED,r=>{r._id===t._id&&n.stopAllProbes()}),n.startAllProbes()}async setupVUMeter(t,n){await this.VUMeter.start(await this.managedAudioContext.getContext(),t,n)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){try{const t=Date.now(),n=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((a,s)=>{a.stop()}),this.initialStreamValue=null),this.initialStreamValue=n}catch(t){throw t}}async triggerAddStream(t,n){var S,E;console.log(`[triggerAddStream] - For ${n._id}`),(S=this.context.logger)==null||S.log(`[triggerAddStream] - For ${n._id}`);const l=this.muteWhenJoin||this.isMuted;this.setIsMuted(l),this.initialStreamValue||await this.setupStream();const a=await this.managedAudioContext.getContext(),s=await ru(a,this.initialStreamValue,this.microphoneInputLevel*2),r=this.isMuted||this.muteWhenJoin;s.getTracks().forEach(C=>{C.enabled=!r}),await this.setActiveStream(s),await n.connection.getSenders()[0].replaceTrack(s.getTracks()[0]);const _=new MediaStream([t.track]);!Object.values(this.extendedCalls).find(C=>C.audioTag&&C.audioTag.id===n._id)&&ZT(_,n,this.selectedOutputDevice,this.speakerVolume);const T=n.roomId===this.currentActiveRoomId;n.audioTag&&(n.audioTag.muted=!T),await this.setupVUMeter(_,n._id),this.getCallQuality(n),this.updateCall(n),n.roomId!==void 0&&Object.values(this.extendedCalls).filter(A=>A.roomId===n.roomId).length>1&&(console.log(`[triggerAddStream] Re-configuring conference for room ${n.roomId} - track received for call ${n._id}`),(E=this.context.logger)==null||E.log(`[triggerAddStream] Re-configuring conference for room ${n.roomId} - track received for call ${n._id}`),setTimeout(()=>{this.roomReconfigure(n.roomId)},100)),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVADForActiveStream()}initCall(t,n,l=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const a=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=a.id,n&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:a.id,roomId:this.currentActiveRoomId}),l)){const s=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId&&r._id!==a.id);for(const r of s)this.holdCall(r._id,!0)}a.connection.addEventListener("track",s=>{this.triggerAddStream(s,a)})}async processRoomChange({callId:t,roomId:n}){const l=this.extendedCalls[t];if(!l)return;const a=l.roomId;l.roomId=n,this.updateCall(l),await this.roomReconfigure(a),await this.roomReconfigure(n)}}class TS{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,n){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,n,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class vS{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const n=this.extendedMessages[t];this.updateMSRPSession(n)}updateMSRPSession(t){this.activeMessages[t._id]=kf(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:kf(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const l=this.msrpHistory[n.id]||[];l.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...l]},this.context.emit("newMSRPMessage",{message:t,session:n})}messageTerminate(t){const n=this.extendedMessages[t];n._status!==8&&n.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const l=t;this.addMMSRPSession(l)}triggerMSRPListener({listenerType:t,session:n,event:l}){const a=this.context.listenersList[t];!a||!a.length||a.forEach(s=>{s(n,l)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const l={...this.extendedMessages};delete l[t],this.extendedMessages={...l},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){t.session._id||(t.session._id=t.request.call_id+t.request.from._parameters.tag);const n=t.session;n.on("ended",l=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:n,event:l});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("failed",l=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:n,event:l});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("confirmed",l=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:l}),this.updateMSRPSession(n)}),n.on("newMessage",l=>{this.addMSRPMessage(l,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,l){if(t.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(t,l);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const l=this.extendedMessages[t];if(!l)throw new Error(`MSRP session with id ${t} doesn't exist!`);l.sendMSRP(n)}}const po={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class $d{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class Hd extends $d{constructor(t,n){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=n}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const n=Pe.cloneArray(t.extraHeaders),l={from_tag:this.session._from_tag};t.fromUserName&&(l.from_uri=new Rn("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(l.from_display_name=t.fromDisplayName),n.push(`Contact: ${this.session._contact}`),n.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&n.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new yt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,l,n),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let t;this._connection.onicecandidate=n=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||n.candidate&&(this._candidates.push(n.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(n=>{this._connection.addTrack(n)})}async _sendInitialRequest(){const t=new tl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const n={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(n),await this._connection.setLocalDescription(this.jsep_offer);const l={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},a=JSON.stringify(l);this._request.body=a,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const n=JSON.parse(t.body);this.handleId=n.data.id;const l={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},a=[this.session.getPTypeHeader(Ut.PUBLISHER)];this.session.sendRequest($.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{var r,h,d,_;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((h=(r=g.plugindata)==null?void 0:r.data)==null?void 0:h.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(_=(d=g.plugindata)==null?void 0:d.data)!=null&&_.publishers&&this.session.receivePublishers(g)}catch(g){console.error(g)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const n=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handleId,session_id:this.session.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...n]},s=["Content-Type: application/json",this.session.getPTypeHeader(Ut.ICE)];this.session.sendRequest($.INFO,{extraHeaders:s,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async r=>{this._configureSent=!0;const d=r.data.split(`\r
|
|
159
|
-
`),_=d[d.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},
|
|
156
|
+
`),this._newMSRPSession("local",this._request),this._from_tag||(this._from_tag=this._request.from._parameters.tag),this._id=this._request.call_id+this._from_tag,new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:n=>{this.onTransportError(),console.log(n)},onAuthenticated:n=>{this._request=n},onReceiveResponse:n=>{this._receiveInviteResponse(n),n.status_code===200&&(n.parseSDP(!0),this._status=Re.STATUS_CONFIRMED,this.target_addr=n.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=Re.STATUS_INVITE_SENT}terminate(t={}){const s=t.cause||H.causes.BYE,i=Me.cloneArray(t.extraHeaders),a=t.body;let n,r=t.status_code,h=t.reason_phrase;if(this._status===Re.STATUS_TERMINATED)throw new qs.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Re.STATUS_NULL:case Re.STATUS_INVITE_SENT:case Re.STATUS_1XX_RECEIVED:if(r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(h=h||H.REASON_PHRASE[r]||"",n=`SIP ;cause=${r} ;text="${h}"`),this._status===Re.STATUS_NULL||this._status===Re.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=n):this._status===Re.STATUS_1XX_RECEIVED&&this._request.cancel(n),this._status=Re.STATUS_CANCELED,this._failed("local",null,H.causes.CANCELED);break;case Re.STATUS_WAITING_FOR_ANSWER:case Re.STATUS_ANSWERED:if(r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,h,i,a),this._failed("local",null,H.causes.REJECTED);break;case Re.STATUS_WAITING_FOR_ACK:case Re.STATUS_CONFIRMED:if(h=t.reason_phrase||H.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&i.push(`Reason: SIP ;cause=${r}; text="${h}"`),this._status===Re.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Wt.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:_})=>{_===H.ACK&&(this.sendRequest(H.BYE,{extraHeaders:i,body:a}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Wt.C.STATUS_TERMINATED&&(this.sendRequest(H.BYE,{extraHeaders:i,body:a}),d.terminate())}),this._ended("local",null,s),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(H.BYE,{extraHeaders:i,body:a}),this._ended("local",null,s)}}sendRequest(t,s){return this._dialog.sendRequest(t,s)}authenticate(t){this.status="auth";let s=new cr("");s.method="AUTH",s.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),s.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),t&&s.addHeader("Authorization",t.toString());let i=s.toString(),a=[];for(var n=0;n<i.length;n++)a.push(i.charCodeAt(n).toString(16));this._connection.send(s.toString())}onmessage(t){const s=new cr(t.data);if(this.status==="auth"&&s.code===401){const i=this.parseAuth(s.getHeader("WWW-Authenticate")),a=new ng(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},i,Me.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&s.code===200&&this._direction==="outgoing"?(this.my_addr.push(s.getHeader("To-Path")),this.my_addr.push(s.getHeader("Use-Path")),this.status="active",this.inviteParty(s)):this.status==="auth"&&s.code===200&&this._direction==="incoming"?(this.my_addr.push(s.getHeader("To-Path")),this.my_addr.push(s.getHeader("Use-Path")),this.status="active",this.acceptParty(s),this.emit("confirmed")):s.method==="SEND"&&(this._sendOk(s),this._sendReport(s),s.direction="incoming",this.emit("newMessage",s),this._msgHistory.push(s),this.emit("msgHistoryUpdate",this._msgHistory)),s.code===480&&this._close()}onclose(){console.log("close")}onopen(){const t=new RTCPeerConnection({iceServers:[]});t.createDataChannel(""),t.createOffer().then(t.setLocalDescription.bind(t)),t.onicecandidate=s=>{if(!s||!s.candidate||!s.candidate.candidate)return;const i=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=s.candidate.candidate.match(i);this.my_ip=a&&a[1],t.onicecandidate=()=>{},this.authenticate(null)}}onerror(t){console.log(t)}_receiveInviteResponse(t){if(console.log("resp0000000000000",t),this._dialog&&t.status_code>=200&&t.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(H.ACK);return}else{const s=new eo(this,t,"UAC");if(s.error!==void 0){console.log(s.error);return}this.sendRequest(H.ACK),this.sendRequest(H.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==Re.STATUS_INVITE_SENT&&this._status!==Re.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=Re.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){console.log("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=Re.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const s={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",s);const i=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).then(()=>this._progress("remote",t)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(console.log("maybe here???"),this._status=Re.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,H.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",t,H.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const s={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",s),new RTCSessionDescription({type:"answer",sdp:s.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(i=>this._connection.setLocalDescription(i)).catch(i=>{this._acceptAndTerminate(t,500,i.toString()),console.log("failed 4"),this._failed("local",t,H.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(H.ACK),this._confirmed("local",null)});break}default:{const s=Me.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,s)}}}sendMSRP(t){const s=new cr("");let i="";this.my_addr[1]&&(i=this.my_addr[1]),this.target_addr[1]&&(i+=" "+this.target_addr[1]),this.target_addr[0]&&(i+=" "+this.target_addr[0]),s.method="SEND",s.addHeader("To-Path",i),s.addHeader("From-Path",`${this.my_addr[0]}`),s.addHeader("Message-ID",Me.createRandomToken(10)),s.addHeader("Byte-Range","1-25/25"),s.addHeader("Content-Type","text/plain"),s.addHeader("Success-Report","yes"),s.addHeader("Failure-Report","yes"),s.body=t;let a=s.toString();console.log(a);let n=[];for(var r=0;r<a.length;r++)n.push(a.charCodeAt(r).toString(16));console.log(n),this._connection.send(s.toString()),s.direction="outgoing",this.emit("newMessage",s),this._msgHistory.push(s),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(t){let s=t.ident,i=t.getHeader("Message-ID"),a=new cr("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",i),a.ident=s;let n=a.toString();console.log(n);let r=[];for(var h=0;h<n.length;h++)r.push(n.charCodeAt(h).toString(16));console.log(r),this._connection.send(a.toString())}_sendReport(t){let s=t.ident,i=t.getHeader("Message-ID"),a=new cr("");a.method="REPORT",a.addHeader("To-Path",`${t.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",i),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=s;let n=a.toString();console.log(n);let r=[];for(var h=0;h<n.length;h++)r.push(n.charCodeAt(h).toString(16));console.log(r),this._connection.send(a.toString())}parseAuth(t){const s={},i=t.replace("Digest","").split(",");for(const a of i){const n=a.trim().split("=");s[n[0]]=n[1].match('^"(.+)"$')[1]}return s}init_incoming(t,s){let i;const a=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&a!=="application/sdp"){t.reply(415);return}if(this._status=Re.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(i=t.getHeader("expires")*1e3),t.to_tag=Me.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Re.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),console.log("failed 6"),this._failed("local",null,H.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),i&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Re.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,H.causes.EXPIRES))},i)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,s&&s(this),t.parseSDP(!0),this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",t),this._status!==Re.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,s,i){this.emit("_failed",{originator:t,message:s||null,cause:i}),this._close(),this.emit("failed",{originator:t,message:s||null,cause:i})}_close(){if(console.log("CLOSE SESSION"),this._status!==Re.STATUS_TERMINATED){if(this._status=Re.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){console.log("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyMSRPSession(this)}}_createDialog(t,s,i){const a=s==="UAS"?t.to_tag:t.from_tag,n=s==="UAS"?t.from_tag:t.to_tag,r=t.call_id+a+n;let h=this._earlyDialogs[r];if(i)return h?!0:(h=new eo(this,t,s,eo.C.STATUS_EARLY),h.error?(console.log("failed 8"),this._failed("remote",t,H.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=h,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,h)return h.update(t,s),this._dialog=h,delete this._earlyDialogs[r],!0;const d=new eo(this,t,s);return d.error?(console.log("failed 9"),this._failed("remote",t,H.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_newMSRPSession(t,s){this._ua.newMSRPSession(this,{originator:t,session:this,request:s})}_progress(t,s){this.emit("progress",{originator:t,response:s||null})}isEnded(){switch(this._status){case Re.STATUS_CANCELED:case Re.STATUS_TERMINATED:return!0;default:return!1}}_accepted(t,s){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:t,response:s||null})}_confirmed(t,s){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:s||null})}_ended(t,s,i){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:s||null,cause:i})}_runKeepAliveTimer(){if(!this._sessionTimers||!this._sessionTimers.enabled||this._sessionTimers.running)return;if(this._sessionTimers.currentExpires||(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires||30),!this._sessionTimers.refresher){console.log("Not the refresher; waiting for remote keep-alive");return}const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.timer=setTimeout(()=>{if(this._connection.readyState===WebSocket.OPEN)try{this._sendKeepAlive(),console.log("Session timer: sending MSRP keep-alive")}catch(s){console.error("Failed to send keep-alive:",s)}this._sessionTimers.running=!1,this._runKeepAliveTimer()},t*1e3*.5)}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let s;t.session_expires&&t.session_expires>=H.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,s=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,s="uac"),this._sessionTimers.refresher=s==="uac",this._runKeepAliveTimer()}receiveRequest(t){if(console.log("receiveRequest()"),t.method===H.CANCEL)(this._status===Re.STATUS_WAITING_FOR_ANSWER||this._status===Re.STATUS_ANSWERED)&&(this._status=Re.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",t,H.causes.CANCELED));else switch(t.method){case H.ACK:if(this._status!==Re.STATUS_WAITING_FOR_ACK)return;if(this._status=Re.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:H.causes.MISSING_SDP,status_code:400});break}const s={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",s);const i=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(a=>{this.terminate({cause:H.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",t);break;case H.BYE:this._status===Re.STATUS_CONFIRMED||this._status===Re.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,H.causes.BYE)):this._status===Re.STATUS_INVITE_RECEIVED||this._status===Re.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,H.causes.BYE)):t.reply(403,"Wrong Status");break;case H.INVITE:this._status===Re.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case H.INFO:this._status===Re.STATUS_1XX_RECEIVED||this._status===Re.STATUS_WAITING_FOR_ANSWER||this._status===Re.STATUS_ANSWERED||this._status===Re.STATUS_WAITING_FOR_ACK||this._status===Re.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Iu(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case H.UPDATE:this._status===Re.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case H.REFER:this._status===Re.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case H.NOTIFY:this._status===Re.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:H.causes.CONNECTION_ERROR,cause:H.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:H.causes.REQUEST_TIMEOUT,cause:H.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Re.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:H.causes.DIALOG_ERROR,cause:H.causes.DIALOG_ERROR})}}var WT=es();const Du=Xe(WT),fo=new Yo("Parser"),KT=(c,t)=>{let s,i,a=c.indexOf(`\r
|
|
157
|
+
`);if(a===-1){fo.warn("parseMessage() | no CRLF found, not a SIP message");return}const n=c.substring(0,a);let r=Du.parse(n,"Request_Response");if(r===-1){fo.warn(`parseMessage() | error parsing first line of SIP message: "${n}"`);return}else r.status_code?(s=new pr.IncomingResponse,s.status_code=r.status_code,s.reason_phrase=r.reason_phrase):(s=new pr.IncomingRequest(t),s.method=r.method,s.ruri=r.uri);s.data=c;let h=a+2;for(;;){if(a=YT(c,h),a===-2){i=h+2;break}else if(a===-1){fo.warn("parseMessage() | malformed message");return}if(r=JT(s,c,h,a),r!==!0){fo.warn("parseMessage() |",r.error);return}h=a+2}if(s.hasHeader("content-length")){const d=s.getHeader("content-length");s.body=c.substr(i,d)}else s.body=c.substring(i);return s};function YT(c,t){let s=t,i=0,a=0;if(c.substring(s,s+2).match(/(^\r\n)/))return-2;for(;i===0;){if(a=c.indexOf(`\r
|
|
158
|
+
`,s),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?s=a+2:i=a}return i}function JT(c,t,s,i){let a;const n=t.indexOf(":",s),r=t.substring(s,n).trim(),h=t.substring(n+1,i).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",h),c.getHeaders("via").length===1?(a=c.parseHeader("Via"),a&&(c.via=a,c.via_branch=a.branch)):a=0;break;case"from":case"f":c.setHeader("from",h),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",h),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=Du.parse(h,"Record_Route"),a===-1)a=void 0;else for(const d of a)c.addHeader("record-route",h.substring(d.possition,d.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":c.setHeader("call-id",h),a=c.parseHeader("call-id"),a&&(c.call_id=h);break;case"contact":case"m":if(a=Du.parse(h,"Contact"),a===-1)a=void 0;else for(const d of a)c.addHeader("contact",h.substring(d.possition,d.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":c.setHeader("content-length",h),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",h),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",h),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof pr.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",h),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",h),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",h),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",h),a=c.parseHeader("session-expires"),a&&(c.session_expires=a.expires,c.session_expires_refresher=a.refresher);break;case"refer-to":case"r":c.setHeader("refer-to",h),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",h),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",h),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,h),a=0}return a===void 0?{error:`error parsing header "${r}"`}:!0}const zT={parseMessage:KT},Wi=new Yo("Registrator"),ho=10;class QT{constructor(t,s){this._reg_id=1,this._ua=t,this._transport=s,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=vs.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const i=this._contact.indexOf(">");if(i!==-1){const a=this._contact.slice(0,i)+this._contact.slice(i+1,this._contact.length);this._contact=a}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s)){const i=t[s];this._extraContactParams+=`;${s}`,i&&(this._extraContactParams+=`=${i}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s)){const i=t[s];this._extraContactParams+=`;${s}`,i&&(this._extraContactParams+=`=${i}`)}}register(){if(this._registering){Wi.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const s=new Ct.OutgoingRequest(H.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),i=new sl(this._ua,s,{onRequestTimeout:()=>{this._registrationFailure(null,H.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,H.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){Wi.debug("no Contact header in response to REGISTER, response ignored");break}const n=a.headers.Contact.reduce((_,g)=>_.concat(g.parsed),[]);let r=n.find(_=>this._sipInstance===_.getParam("+sip.instance")&&this._reg_id===parseInt(_.getParam("reg-id")));if(r||(r=n.find(_=>_.uri.user===this._ua.contact.uri.user)),!r){Wi.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let h=r.getParam("expires");!h&&a.hasHeader("expires")&&(h=a.getHeader("expires")),h||(h=this._expires),h=Number(h),h<ho&&(h=ho);const d=h>64?h*1e3/2+Math.floor((h/2-32)*1e3*Math.random()):Math.floor(h*1e3/2);this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),r.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=r.getParam("temp-gruu").replace(/"/g,"")),r.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=r.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<ho&&(this._expires=ho),this.register()):(Wi.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,H.causes.SIP_FAILURE_CODE));break}default:{const n=vs.sipErrorCause(a.status_code);this._registrationFailure(a,n)}}}});this._registering=!0,i.send()}unregister(t={}){if(!this._registered){Wi.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const s=this._extraHeaders.slice();t.all?s.push(`Contact: *${this._extraContactParams}`):s.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),s.push("Expires: 0");const i=new Ct.OutgoingRequest(H.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},s);new sl(this._ua,i,{onRequestTimeout:()=>{this._unregistered(null,H.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,H.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:n=>{switch(!0){case/^1[0-9]{2}$/.test(n.status_code):break;case/^2[0-9]{2}$/.test(n.status_code):this._unregistered(n);break;default:{const r=vs.sipErrorCause(n.status_code);this._unregistered(n,r)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,s){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:s}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:s}))}_unregistered(t,s){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:s||null})}}const nt=console,Bs={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},XT=$T;class ZT extends XT{constructor(t){super(t),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new QT(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(t,s){return super.call(t,s)}joinVideoCall(t,s,i){nt.debug("call()");const a=new Vo(this);return a.configureMedia({audio:!0,video:!0}),a.connect(t,s,i),a}startScreenShare(){nt.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const s in this._janus_sessions)this._janus_sessions[s].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{rl.load(this._configuration,t)}catch(n){throw n}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=vs.newUUID());let s;typeof window<"u"&&typeof window.document<"u"?s=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(s=self.navigator.userAgent),s+=" "+De.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(s):s,t.onTransportCallback&&typeof t.onTransportCallback=="function"&&(this.onTransportCallback=t.onTransportCallback),this._configuration.jssip_id=vs.createRandomToken(5);const i=this._configuration.uri.clone();i.user=null,this._configuration.hostport_params=i.toString().replace(/^sip:/i,"");try{this._transport=new cT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=ev.bind(this),this._transport.onconnect=tv.bind(this),this._transport.ondisconnect=sv.bind(this),this._transport.ondata=nv.bind(this)}catch(n){throw nt.warn(n),new qs.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const n=this._configuration.uri.clone();n.user=null,n.clearParams(),n.clearHeaders(),this._configuration.registrar_server=n}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new In("sip",vs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(n={}){const r=n.anonymous||null,h=n.outbound||null;let d="<";return r?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),h&&(r?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",d}};const a=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const n in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,n)&&(a.indexOf(n)!==-1?Object.defineProperty(this._configuration,n,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,n,{writable:!1,configurable:!1}));nt.debug("configuration parameters after validation:");for(const n in this._configuration)if(Object.prototype.hasOwnProperty.call(rl.settings,n))switch(n){case"uri":case"registrar_server":nt.debug(`- ${n}: ${this._configuration[n]}`);break;case"password":case"ha1":case"authorization_jwt":nt.debug(`- ${n}: NOT SHOWN`);break;default:nt.debug(`- ${n}: ${JSON.stringify(this._configuration[n])}`)}}newMSRPSession(t,s){t.on("msgHistoryUpdate",i=>{console.log(i)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",s)}newJanusSession(t,s){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(i=>{i.setSession(t)}),this.processStreamPlugins.forEach(i=>{i.setSession(t)}),this.emit("newJanusSession",s)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(t){var n,r,h,d;const s=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){nt.debug("Request-URI does not point to us"),t.method!==De.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===De.SIPS){t.reply_sl(416);return}if(Wt.checkTransaction(this,t))return;if(s===De.INVITE?new Wt.InviteServerTransaction(this,this._transport,t):s!==De.ACK&&s!==De.CANCEL&&new Wt.NonInviteServerTransaction(this,this._transport,t),s===De.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const g=Date.now(),T=this.lastOptionsTimestamp>g-35e3,S=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>g;T&&S&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){t.reply(200);return}new sf.Options(this).init_incoming(t)}else if(s===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new sf.Message(this).init_incoming(t)}else if(s===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let i,a;if(t.to_tag)if(i=this._findDialog(t.call_id,t.from_tag,t.to_tag),i)i.receiveRequest(t);else if(s===De.NOTIFY)if(a=this._findSession(t),a)a.receiveRequest(t);else{if(t.body)try{const _=JSON.parse(t.body)||{};(r=(n=_.plugindata)==null?void 0:n.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(_),(d=(h=_.plugindata)==null?void 0:h.data)!=null&&d.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(_.plugindata.data.unpublished)}catch(_){console.error(_)}t.reply(200)}else s!==De.ACK&&t.reply(481);else switch(s){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const _=t.replaces;i=this._findDialog(_.call_id,_.from_tag,_.to_tag),i?(a=i.owner,a.isEnded()?t.reply(603):a.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(a=new iu(this),a.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(a=new Yg(this),a.init_incoming(t));else nt.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case De.BYE:t.reply(481);break;case De.CANCEL:a=this._findSession(t),a?a.receiveRequest(t):nt.debug("received CANCEL request for a non existent session");break;case De.ACK:break;case De.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,s){nt.debug("startMSRP()",s);const i=new iu(this);return i.connect(t),i}startJanus(t,s){nt.debug("startJanus()",s);const i=new iu(this);return i.connect(t),i}terminateMSRPSessions(t){nt.debug("terminateSessions()");for(const s in this._msrp_sessions)this._msrp_sessions[s].isEnded()||this._msrp_sessions[s].terminate(t)}terminateJanusSessions(t){nt.debug("terminateSessions()");for(const s in this._janus_sessions)this._janus_sessions[s].isEnded()||this._janus_sessions[s].terminate(t)}enableJanusAudio(t){nt.debug("enableJanusAudio()");for(const s in this._janus_sessions)this._janus_sessions[s].isEnded()||(t?this._janus_sessions[s].startAudio():this._janus_sessions[s].stopAudio())}enableJanusVideo(t){nt.debug("enableJanusVideo()");for(const s in this._janus_sessions)this._janus_sessions[s].isEnded()||(t?this._janus_sessions[s].startVideo():this._janus_sessions[s].stopVideo())}terminateAllSessions(){for(const t in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,t)){nt.debug(`closing session ${t}`);try{this._sessions[t].terminate()}catch(s){console.error(s)}}}stop(t=!0){if(nt.debug("stop()"),this._dynConfiguration={},this._status===Bs.STATUS_USER_CLOSED){nt.debug("UA already closed");return}this._registrator.close();const s=Object.keys(this._sessions).length;t&&this.terminateAllSessions();for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){nt.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(n){console.error(n)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){nt.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(n){console.error(n)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(n){console.error(n)}this._status=Bs.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function ev(c){this.emit("connecting",c)}function tv(c){this._status!==Bs.STATUS_USER_CLOSED&&(this._status=Bs.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function sv(c){const t=["nict","ict","nist","ist"];for(const s of t)for(const i in this._transactions[s])Object.prototype.hasOwnProperty.call(this._transactions[s],i)&&this._transactions[s][i].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Bs.STATUS_USER_CLOSED&&(this._status=Bs.STATUS_NOT_READY,this._error=Bs.NETWORK_ERROR)}function nv(c){const t=c.transport;let s=c.message;const i=s;if(s=zT.parseMessage(s,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(s,i),!!s&&!(this._status===Bs.STATUS_USER_CLOSED&&s instanceof pr.IncomingRequest)&&RT(s,this,t)){if(s instanceof pr.IncomingRequest)s.transport=t,this.receiveRequest(s);else if(s instanceof pr.IncomingResponse){let a;switch(s.method){case De.INVITE:if(a=this._transactions.ict[s.via_branch],a){const n=s.status_code;if((n===100||n===180||n===183)&&this.audio&&typeof this.audio.handleSipResponseForRingback=="function"){let r=null;if(a._session&&a._session.id)r=a._session.id;else if(s.call_id&&this._sessions){const d=Object.values(this._sessions).find(_=>_._id&&_._id.includes(s.call_id)||_.id&&_.id.includes(s.call_id)||_.call_id===s.call_id);d&&(d.id||d._id)&&(r=d.id||d._id)}else s.call_id&&(r=s.call_id);r&&this.audio.handleSipResponseForRingback(r,n)}a.receiveResponse(s)}break;case De.ACK:break;default:a=this._transactions.nict[s.via_branch],a&&a.receiveResponse(s);break}}}}const rv=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer","putOnHoldTimestamp","_remote_party_display_name","_remote_party_uri_user"],iv=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Mf(c){const t={};return rv.forEach(s=>{c[s]!==void 0&&(t[s]=c[s])}),t.localHold=c._localHold,t}function Pf(c){const t={};return iv.forEach(s=>{c[s]!==void 0&&(t[s]=c[s])}),t}async function lu(c,t,s){const i=c.createMediaStreamSource(t),a=c.createMediaStreamDestination(),n=c.createGain();return i.connect(n),n.connect(a),n.gain.value=s,a.stream}function lv(c,t,s,i){if(Ld())return;const a=document.createElement("audio");a.id=t._id,a.className="audioTag",a.srcObject=c,a.setSinkId(s),a.volume=i,a.play(),t.audioTag=a}function Lf(c){if(!c)return null;const t=c.match(/^\s*"((?:[^"\\]|\\.)*)"/);return t?t[1].replace(/\\(.)/g,"$1"):null}function $f(c){if(!c)return null;const t=c.match(/<?sips?:([^@>\s;]+)@/i);return t?t[1]:null}function ov(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function Ld(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const av=ct,uv=es(),Nt=new av("WebSocketInterface");var cv=class{constructor(t){Nt.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const s=uv.parse(t,"absoluteURI");if(s===-1)throw Nt.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(s.scheme!=="wss"&&s.scheme!=="ws")throw Nt.warn(`invalid WebSocket URI scheme: ${s.scheme}`),new TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${s.host}${s.port?`:${s.port}`:""};transport=ws`,this._via_transport=s.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Nt.debug("connect()"),this.isConnected()){Nt.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Nt.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Nt.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(t){this._onError(t)}}disconnect(){Nt.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Nt.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Nt.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){Nt.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:s,reason:i}){Nt.debug(`WebSocket ${this._url} closed`),t===!1&&Nt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,s,i)}_onMessage({data:t}){Nt.debug("received WebSocket message"),this.ondata(t)}_onError(t){Nt.warn(`WebSocket ${this._url} error: `,t)}};const Nu=jo,fv=De,dv=As,hv=At(),_v=Pd,pv=Cs(),mv=ju(),gv=es(),Tv=cv,vv=gr("JsSIP");vv("version %s",Nu.version);var Sv={C:fv,Exceptions:dv,Utils:hv,UA:_v,URI:pv,NameAddrHeader:mv,WebSocketInterface:Tv,Grammar:gv,debug:gr,get name(){return Nu.title},get version(){return Nu.version}};const Ev=Xe(Sv);function ou(c){return c<10?`0${c}`:`${c}`}function yv(c){let t=c.hours||0,s=c.minutes||0,i=c.seconds||0;i++,i===60&&(i=0,s++,s===60&&(s=0,t++));const a=`${ou(t)}:${ou(s)}:${ou(i)}`;return{seconds:i,minutes:s,hours:t,formatted:a}}function Cv(c){let t=0;for(let s=0;s<c.length;s++)t+=c[s]*c[s];return Math.sqrt(t/c.length)}async function Av(c,t,s=150){const i=t.createMediaStreamSource(c),a=t.createDelay();a.delayTime.value=s/1e3;const n=t.createGain();n.gain.value=0;const r=t.createMediaStreamDestination();return i.connect(a).connect(n).connect(r),{stream:r.stream,setSpeaking:h=>{n.gain.value=h?1:0}}}var Rt={};Rt.forEach=async(c,t,s)=>{const i=[];for(let a=0;a<c.length;a++)if(a in c){const n=Promise.resolve(c[a]).then(r=>t.call(s||globalThis,r,a,c));i.push(n)}await Promise.all(i)};Rt.forEachSeries=async(c,t,s)=>{for(let i=0;i<c.length;i++)i in c&&await t.call(s||globalThis,await c[i],i,c)};Rt.map=async(c,t,s)=>{const i=[];for(let a=0;a<c.length;a++)a in c&&(i[a]=Promise.resolve(c[a]).then(n=>t.call(s||globalThis,n,a,c)));return Promise.all(i)};Rt.mapSeries=async(c,t,s)=>{const i=[];for(let a=0;a<c.length;a++)a in c&&(i[a]=await t.call(s||globalThis,await c[a],a,c));return i};Rt.find=(c,t,s)=>new Promise((i,a)=>{if(c.length===0)return i();let n=1;for(let r=0;r<c.length;r++){const h=d=>{d?i(c[r]):n===c.length&&i(),n++};Promise.resolve(c[r]).then(d=>t.call(s||globalThis,d,r,c)).then(h).catch(a)}});Rt.findSeries=async(c,t,s)=>{for(let i=0;i<c.length;i++)if(await t.call(s||globalThis,await c[i],i,c))return c[i]};Rt.findIndex=(c,t,s)=>new Promise((i,a)=>{if(c.length===0)return i(-1);let n=1;for(let r=0;r<c.length;r++){const h=d=>{d?i(r):n===c.length&&i(-1),n++};Promise.resolve(c[r]).then(d=>t.call(s||globalThis,d,r,c)).then(h).catch(a)}});Rt.findIndexSeries=async(c,t,s)=>{for(let i=0;i<c.length;i++)if(await t.call(s||globalThis,await c[i],i,c))return i};Rt.some=(c,t,s)=>new Promise((i,a)=>{if(c.length===0)return i(!1);let n=1;for(let r=0;r<c.length;r++){if(!(r in c)){n++;continue}const h=d=>{d?i(!0):n===c.length&&i(!1),n++};Promise.resolve(c[r]).then(d=>t.call(s||globalThis,d,r,c)).then(h).catch(a)}});Rt.someSeries=async(c,t,s)=>{for(let i=0;i<c.length;i++)if(i in c&&await t.call(s||globalThis,await c[i],i,c))return!0;return!1};Rt.every=(c,t,s)=>new Promise((i,a)=>{if(c.length===0)return i(!0);let n=1;for(let r=0;r<c.length;r++){if(!(r in c)){n++;continue}const h=d=>{d?n===c.length&&i(!0):i(!1),n++};Promise.resolve(c[r]).then(d=>t.call(s||globalThis,d,r,c)).then(h).catch(a)}});Rt.everySeries=async(c,t,s)=>{for(let i=0;i<c.length;i++)if(i in c&&!await t.call(s||globalThis,await c[i],i,c))return!1;return!0};Rt.filter=(c,t,s)=>new Promise(async(i,a)=>{const n=[];for(let h=0;h<c.length;h++)h in c&&(n[h]=Promise.resolve(c[h]).then(d=>t.call(s||globalThis,d,h,c)).catch(a));const r=[];for(let h=0;h<n.length;h++)await n[h]&&r.push(await c[h]);i(r)});Rt.filterSeries=async(c,t,s)=>{const i=[];for(let a=0;a<c.length;a++)a in c&&await t.call(s||globalThis,await c[a],a,c)&&i.push(await c[a]);return i};Rt.reduce=async(c,t,s)=>{if(c.length===0&&s===void 0)throw TypeError("Reduce of empty array with no initial value");let i,a;for(s!==void 0?(a=s,i=0):(a=c[0],i=1),i;i<c.length;i++)i in c&&(a=await t(await a,await c[i],i,c));return a};var $d={};(function(c){const t=Rt;Object.keys(t).forEach(s=>{const i=s.charAt(0).toUpperCase()+s.slice(1);c[`async${i}`]=async function(...a){return t[s](this,...a)}})})($d);const Rv=Rt,Iv=$d;var bv=Object.assign(Rv,{instanceMethods:Iv});const Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},au={TRYING:100,RINGING:180,SESSION_PROGRESS:183,OK:200,MOVED_TEMPORARILY:302,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,REQUEST_TIMEOUT:408,BUSY_HERE:486,REQUEST_TERMINATED:487,INTERNAL_SERVER_ERROR:500,SERVICE_UNAVAILABLE:503,BUSY_EVERYWHERE:600,DECLINE:603};var wv={exports:{}};(function(c){var t=function(s){var i=Object.prototype,a=i.hasOwnProperty,n=Object.defineProperty||function(X,W,G){X[W]=G.value},r,h=typeof Symbol=="function"?Symbol:{},d=h.iterator||"@@iterator",_=h.asyncIterator||"@@asyncIterator",g=h.toStringTag||"@@toStringTag";function T(X,W,G){return Object.defineProperty(X,W,{value:G,enumerable:!0,configurable:!0,writable:!0}),X[W]}try{T({},"")}catch{T=function(W,G,re){return W[G]=re}}function S(X,W,G,re){var pe=W&&W.prototype instanceof ie?W:ie,Ie=Object.create(pe.prototype),ke=new M(re||[]);return n(Ie,"_invoke",{value:Y(X,G,ke)}),Ie}s.wrap=S;function E(X,W,G){try{return{type:"normal",arg:X.call(W,G)}}catch(re){return{type:"throw",arg:re}}}var C="suspendedStart",A="suspendedYield",R="executing",F="completed",I={};function ie(){}function N(){}function $(){}var ve={};T(ve,d,function(){return this});var _e=Object.getPrototypeOf,U=_e&&_e(_e(B([])));U&&U!==i&&a.call(U,d)&&(ve=U);var x=$.prototype=ie.prototype=Object.create(ve);N.prototype=$,n(x,"constructor",{value:$,configurable:!0}),n($,"constructor",{value:N,configurable:!0}),N.displayName=T($,g,"GeneratorFunction");function q(X){["next","throw","return"].forEach(function(W){T(X,W,function(G){return this._invoke(W,G)})})}s.isGeneratorFunction=function(X){var W=typeof X=="function"&&X.constructor;return W?W===N||(W.displayName||W.name)==="GeneratorFunction":!1},s.mark=function(X){return Object.setPrototypeOf?Object.setPrototypeOf(X,$):(X.__proto__=$,T(X,g,"GeneratorFunction")),X.prototype=Object.create(x),X},s.awrap=function(X){return{__await:X}};function j(X,W){function G(Ie,ke,Ae,oe){var ye=E(X[Ie],X,ke);if(ye.type==="throw")oe(ye.arg);else{var rt=ye.arg,at=rt.value;return at&&typeof at=="object"&&a.call(at,"__await")?W.resolve(at.__await).then(function(Ee){G("next",Ee,Ae,oe)},function(Ee){G("throw",Ee,Ae,oe)}):W.resolve(at).then(function(Ee){rt.value=Ee,Ae(rt)},function(Ee){return G("throw",Ee,Ae,oe)})}}var re;function pe(Ie,ke){function Ae(){return new W(function(oe,ye){G(Ie,ke,oe,ye)})}return re=re?re.then(Ae,Ae):Ae()}n(this,"_invoke",{value:pe})}q(j.prototype),T(j.prototype,_,function(){return this}),s.AsyncIterator=j,s.async=function(X,W,G,re,pe){pe===void 0&&(pe=Promise);var Ie=new j(S(X,W,G,re),pe);return s.isGeneratorFunction(W)?Ie:Ie.next().then(function(ke){return ke.done?ke.value:Ie.next()})};function Y(X,W,G){var re=C;return function(Ie,ke){if(re===R)throw new Error("Generator is already running");if(re===F){if(Ie==="throw")throw ke;return Fe()}for(G.method=Ie,G.arg=ke;;){var Ae=G.delegate;if(Ae){var oe=V(Ae,G);if(oe){if(oe===I)continue;return oe}}if(G.method==="next")G.sent=G._sent=G.arg;else if(G.method==="throw"){if(re===C)throw re=F,G.arg;G.dispatchException(G.arg)}else G.method==="return"&&G.abrupt("return",G.arg);re=R;var ye=E(X,W,G);if(ye.type==="normal"){if(re=G.done?F:A,ye.arg===I)continue;return{value:ye.arg,done:G.done}}else ye.type==="throw"&&(re=F,G.method="throw",G.arg=ye.arg)}}}function V(X,W){var G=W.method,re=X.iterator[G];if(re===r)return W.delegate=null,G==="throw"&&X.iterator.return&&(W.method="return",W.arg=r,V(X,W),W.method==="throw")||G!=="return"&&(W.method="throw",W.arg=new TypeError("The iterator does not provide a '"+G+"' method")),I;var pe=E(re,X.iterator,W.arg);if(pe.type==="throw")return W.method="throw",W.arg=pe.arg,W.delegate=null,I;var Ie=pe.arg;if(!Ie)return W.method="throw",W.arg=new TypeError("iterator result is not an object"),W.delegate=null,I;if(Ie.done)W[X.resultName]=Ie.value,W.next=X.nextLoc,W.method!=="return"&&(W.method="next",W.arg=r);else return Ie;return W.delegate=null,I}q(x),T(x,g,"Generator"),T(x,d,function(){return this}),T(x,"toString",function(){return"[object Generator]"});function Q(X){var W={tryLoc:X[0]};1 in X&&(W.catchLoc=X[1]),2 in X&&(W.finallyLoc=X[2],W.afterLoc=X[3]),this.tryEntries.push(W)}function k(X){var W=X.completion||{};W.type="normal",delete W.arg,X.completion=W}function M(X){this.tryEntries=[{tryLoc:"root"}],X.forEach(Q,this),this.reset(!0)}s.keys=function(X){var W=Object(X),G=[];for(var re in W)G.push(re);return G.reverse(),function pe(){for(;G.length;){var Ie=G.pop();if(Ie in W)return pe.value=Ie,pe.done=!1,pe}return pe.done=!0,pe}};function B(X){if(X){var W=X[d];if(W)return W.call(X);if(typeof X.next=="function")return X;if(!isNaN(X.length)){var G=-1,re=function pe(){for(;++G<X.length;)if(a.call(X,G))return pe.value=X[G],pe.done=!1,pe;return pe.value=r,pe.done=!0,pe};return re.next=re}}return{next:Fe}}s.values=B;function Fe(){return{value:r,done:!0}}return M.prototype={constructor:M,reset:function(X){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(k),!X)for(var W in this)W.charAt(0)==="t"&&a.call(this,W)&&!isNaN(+W.slice(1))&&(this[W]=r)},stop:function(){this.done=!0;var X=this.tryEntries[0],W=X.completion;if(W.type==="throw")throw W.arg;return this.rval},dispatchException:function(X){if(this.done)throw X;var W=this;function G(oe,ye){return Ie.type="throw",Ie.arg=X,W.next=oe,ye&&(W.method="next",W.arg=r),!!ye}for(var re=this.tryEntries.length-1;re>=0;--re){var pe=this.tryEntries[re],Ie=pe.completion;if(pe.tryLoc==="root")return G("end");if(pe.tryLoc<=this.prev){var ke=a.call(pe,"catchLoc"),Ae=a.call(pe,"finallyLoc");if(ke&&Ae){if(this.prev<pe.catchLoc)return G(pe.catchLoc,!0);if(this.prev<pe.finallyLoc)return G(pe.finallyLoc)}else if(ke){if(this.prev<pe.catchLoc)return G(pe.catchLoc,!0)}else if(Ae){if(this.prev<pe.finallyLoc)return G(pe.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(X,W){for(var G=this.tryEntries.length-1;G>=0;--G){var re=this.tryEntries[G];if(re.tryLoc<=this.prev&&a.call(re,"finallyLoc")&&this.prev<re.finallyLoc){var pe=re;break}}pe&&(X==="break"||X==="continue")&&pe.tryLoc<=W&&W<=pe.finallyLoc&&(pe=null);var Ie=pe?pe.completion:{};return Ie.type=X,Ie.arg=W,pe?(this.method="next",this.next=pe.finallyLoc,I):this.complete(Ie)},complete:function(X,W){if(X.type==="throw")throw X.arg;return X.type==="break"||X.type==="continue"?this.next=X.arg:X.type==="return"?(this.rval=this.arg=X.arg,this.method="return",this.next="end"):X.type==="normal"&&W&&(this.next=W),I},finish:function(X){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.finallyLoc===X)return this.complete(G.completion,G.afterLoc),k(G),I}},catch:function(X){for(var W=this.tryEntries.length-1;W>=0;--W){var G=this.tryEntries[W];if(G.tryLoc===X){var re=G.completion;if(re.type==="throw"){var pe=re.arg;k(G)}return pe}}throw new Error("illegal catch attempt")},delegateYield:function(X,W,G){return this.delegate={iterator:B(X),resultName:W,nextLoc:G},this.method==="next"&&(this.arg=r),I}},s}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(wv);var Hd={exports:{}};(function(c){(function(t,s){c.exports?c.exports=s():t.log=s()})(Qd,function(){var t=function(){},s="undefined",i=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function n(A,R){var F=A[R];if(typeof F.bind=="function")return F.bind(A);try{return Function.prototype.bind.call(F,A)}catch{return function(){return Function.prototype.apply.apply(F,[A,arguments])}}}function r(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function h(A){return A==="debug"&&(A="log"),typeof console===s?!1:A==="trace"&&i?r:console[A]!==void 0?n(console,A):console.log!==void 0?n(console,"log"):t}function d(A,R){for(var F=0;F<a.length;F++){var I=a[F];this[I]=F<A?t:this.methodFactory(I,A,R)}this.log=this.debug}function _(A,R,F){return function(){typeof console!==s&&(d.call(this,R,F),this[A].apply(this,arguments))}}function g(A,R,F){return h(A)||_.apply(this,arguments)}function T(A,R,F){var I=this,ie;R=R??"WARN";var N="loglevel";typeof A=="string"?N+=":"+A:typeof A=="symbol"&&(N=void 0);function $(x){var q=(a[x]||"silent").toUpperCase();if(!(typeof window===s||!N)){try{window.localStorage[N]=q;return}catch{}try{window.document.cookie=encodeURIComponent(N)+"="+q+";"}catch{}}}function ve(){var x;if(!(typeof window===s||!N)){try{x=window.localStorage[N]}catch{}if(typeof x===s)try{var q=window.document.cookie,j=q.indexOf(encodeURIComponent(N)+"=");j!==-1&&(x=/^([^;]+)/.exec(q.slice(j))[1])}catch{}return I.levels[x]===void 0&&(x=void 0),x}}function _e(){if(!(typeof window===s||!N)){try{window.localStorage.removeItem(N);return}catch{}try{window.document.cookie=encodeURIComponent(N)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}I.name=A,I.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},I.methodFactory=F||g,I.getLevel=function(){return ie},I.setLevel=function(x,q){if(typeof x=="string"&&I.levels[x.toUpperCase()]!==void 0&&(x=I.levels[x.toUpperCase()]),typeof x=="number"&&x>=0&&x<=I.levels.SILENT){if(ie=x,q!==!1&&$(x),d.call(I,x,A),typeof console===s&&x<I.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+x},I.setDefaultLevel=function(x){R=x,ve()||I.setLevel(x,!1)},I.resetLevel=function(){I.setLevel(R,!1),_e()},I.enableAll=function(x){I.setLevel(I.levels.TRACE,x)},I.disableAll=function(x){I.setLevel(I.levels.SILENT,x)};var U=ve();U==null&&(U=R),I.setLevel(U,!1)}var S=new T,E={};S.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var F=E[R];return F||(F=E[R]=new T(R,S.getLevel(),S.methodFactory)),F};var C=typeof window!==s?window.log:void 0;return S.noConflict=function(){return typeof window!==s&&window.log===S&&(window.log=C),S},S.getLoggers=function(){return E},S.default=S,S})})(Hd);var bt=Hd.exports;const Ss=()=>`${new Date().toISOString()} | metrics`,Es=(c,t,s)=>`${c} | ${t} | ${s}`;bt.setDefaultLevel(bt.levels.TRACE);const Ov=c=>{bt.info(Es(Ss(),"log ",`set log level to ${c?"verbose":"info"}`)),bt.setLevel(c?bt.levels.TRACE:bt.levels.INFO)},Dv=c=>{const t=[...Object.keys(bt.levels)];t.includes(c)?(bt.info(Es(Ss(),"log ",`update log level to ${c.toLowerCase()}`)),bt.setLevel(c)):bt.warn(Es(Ss(),"log ","Incorrect log level please choose one of "),t)},Ue=(c,t,s)=>{s?bt.debug(Es(Ss(),c,t),s):bt.debug(Es(Ss(),c,t))},uu=(c,t)=>{bt.info(Es(Ss(),c,t))},Rn=(c,t)=>{bt.info(Es(Ss(),c,t))},No=(c,t)=>{bt.warn(Es(Ss(),c,t))},hr=(c,t)=>{bt.error(Es(Ss(),c,t))};function Nv(c){return Math.floor(Math.random()*c).toString()}function Hf(c,t){let s=t;return c.forEach(i=>{s=s.replace(i,"")}),s}function xv(c,t){let s="";for(let i=0;i<t;i+=1)s+=c[Nv(c.length)];return s}function Uv({length:c=20,useLetters:t=!0,useNumbers:s=!0,includeSymbols:i=[],excludeSymbols:a=[]}={}){let n="abcdefghijklmnopqrstuvwxyz",r="0123456789",h=[],d=[],_=[];return t&&(a.length&&(n=Hf(a,n)),d=n.split("")),s&&(a.length&&(r=Hf(a,r)),_=r.split("")),h=[...d,..._,...i],xv(h,c)}var kv=Uv;const Xi=Xe(kv),Mv=()=>"WebRTCMetrics",Pv=()=>"5.0.3",He={INBOUND:"inbound",OUTBOUND:"outbound"},Ts={IDLE:"idle",RUNNING:"running",MUTED:"muted"},Ki={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},Lv=()=>({...{delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}}),Fd={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:He.INBOUND},Vd={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:He.OUTBOUND},jd={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:He.INBOUND},qd={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:He.OUTBOUND},$v=c=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(c){const s={...c,audio:{},video:{},data:{...c.data},network:{...c.network},experimental:{...c.experimental}};return Object.keys(c.audio).forEach(i=>{s.audio[i]={...c.audio[i]}}),Object.keys(c.video).forEach(i=>{s.video[i]={...c.video[i]}}),s}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},Hv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Xi()}`,cid:`c-${Xi()}`,uid:`u-${Xi()}`,record:!1,ticket:!0},Qt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},K={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},P={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Yi={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},cu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},fu="config ",Fv=(c,t={},s)=>{const i={...s,...t};return t.pname||No(fu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${s.pname}'`),t.cid||No(fu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${s.cid}'`),t.uid||No(fu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${s.uid}'`),i.pc=c,i},Vv=(c={})=>{const t={...Hv,...c};return t.name=Mv(),t.version=Pv(),t},ml=(c,t,s,i=!1,a)=>{let n=c.map(r=>{if(!s)return r[t];if(!a)return r[t][s];const h=r[t][a];return h?h[s]:null});return n=n.filter(r=>i?Number.isFinite(r)&&r>0:Number.isFinite(r)),n.length===0?[]:n},Ws=c=>c.reduce((t,s)=>t+s,0)/c.length,jv=()=>`probe-${Xi()}`,qv=()=>`coltr-${Xi()}`,Ff=c=>new Promise(t=>setTimeout(t,c)),xu=(c,t,s)=>{t?c.call(t,s):c(s)},Je=(c,t,s,i)=>{const a=ml(c,t,s,!0,i);if(a.length===0)return null;const n=a.reduce((_,g)=>_+g,0)/a.length;return n===0?null:a.map(_=>Math.abs(n-_)).reduce((_,g)=>_+g,0)/a.length*100/n},Ze=(c,t,s,i=!1,a)=>{const n=ml(c,t,s,i,a);return n.length===0?null:n.reduce((r,h)=>r+h,0)/n.length},yn=(c,t,s)=>ml(c,t,s).reduce((a,n)=>a+n,0),ze=(c,t,s,i)=>{const a=ml(c,t,s,!0,i);return a.length===0?null:Math.min(...a)},Qe=(c,t,s,i)=>{const a=ml(c,t,s,!1,i);return a.length===0?null:Math.max(...a)},Tt=(c,t,s,i)=>{const a=c.slice().pop();if(!a)return null;if(!s)return a[t];if(!i)return a[t][s];const n=a[t][i];return n?n[s]:null},Bv=c=>c.slice().pop(),ft=(c,t,s)=>{if(!t)return null;const i={};let a=t[P.AUDIO][c];a||(a=s===He.INBOUND?{...Fd}:{...Vd}),i[P.AUDIO]=a;let n=t[P.VIDEO][c];return n||(n=s===He.INBOUND?{...jd}:{...qd}),i[P.VIDEO]=n,i},Ji="exporter ",Gv="2.0",Vf=(c,t,s)=>{if(!c||c.length===0)return 0;const i=c[c.length-1];if(!i)return 0;const a=i[t][s];if(a){const n=a.total_rtt_ms_out,r=a.total_rtt_measure_out;return!r||!n?Ze(c,t,"delta_rtt_ms_out",!1,s):Number(n/r)}return null},Wv=(c,t)=>{if(!c||c.length===0)return 0;const s=c[c.length-1];if(!s)return 0;const i=s[t].total_rtt_connectivity_ms,a=s[t].total_rtt_connectivity_measure;return!a||!i?Ze(c,t,"delta_rtt_connectivity_ms"):Number(i/a)},Kv=c=>Tt(c,"network","local_candidate_type")!=="relay"?`direct/${Tt(c,"network","local_candidate_protocol")}`:`turn/${Tt(c,"network","local_candidate_relay_protocol")}`,Yv=c=>{const t=Tt(c,"network","remote_candidate_type"),s=Tt(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${s}`:`turn/${s}`};class Jv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){uu(Ji,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){uu(Ji,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(Ue(Ji,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){uu(Ji,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ue(Ji,"ticket() - generate ticket");const t=Tt(this._reports,"audio","total_packets_lost_in"),s=Tt(this._reports,"audio","total_packets_in"),i=Tt(this._reports,"video","total_packets_lost_in"),a=Tt(this._reports,"video","total_packets_in"),n={},r=Bv(this._reports);return r&&(Object.keys(r[P.AUDIO]).forEach(h=>{const d=r[P.AUDIO][h];if(n[d.ssrc]={type:P.AUDIO,direction:d.direction},d.direction===He.INBOUND){const _={avg:Ze(this._reports,P.AUDIO,"delta_jitter_ms_in",!1,h),min:ze(this._reports,P.AUDIO,"delta_jitter_ms_in",h),max:Qe(this._reports,P.AUDIO,"delta_jitter_ms_in",h),volatility:Je(this._reports,P.AUDIO,"delta_jitter_ms_in",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Ze(this._reports,P.AUDIO,"delta_kbs_in",!1,h),min:ze(this._reports,P.AUDIO,"delta_kbs_in",h),max:Qe(this._reports,P.AUDIO,"delta_kbs_in",h),volatility:Je(this._reports,P.AUDIO,"delta_kbs_in",h),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Ze(this._reports,P.AUDIO,"delta_KBytes_in",!1,h),min:ze(this._reports,P.AUDIO,"delta_KBytes_in",h),max:Qe(this._reports,P.AUDIO,"delta_KBytes_in",h),volatility:Je(this._reports,P.AUDIO,"delta_KBytes_in",h),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={emodel:{avg:Ze(this._reports,P.AUDIO,"mos_emodel_in",!1,h),min:ze(this._reports,P.AUDIO,"mos_emodel_in",h),max:Qe(this._reports,P.AUDIO,"mos_emodel_in",h),volatility:Je(this._reports,P.AUDIO,"mos_emodel_in",h)},effective:{avg:Ze(this._reports,P.AUDIO,"mos_in",!1,h),min:ze(this._reports,P.AUDIO,"mos_in",h),max:Qe(this._reports,P.AUDIO,"mos_in",h),volatility:Je(this._reports,P.AUDIO,"mos_in",h)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},E=Tt(this._reports,P.AUDIO,"total_packets_lost_in",h),C=Tt(this._reports,P.AUDIO,"total_packets_in",h),A={lost:E,avg:Math.round((E/(E+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};n[h].jitter=_,n[h].mos=S,n[h].traffic=T,n[h].bitrate=g,n[h].loss=A}else{const _={avg:Ze(this._reports,P.AUDIO,"delta_jitter_ms_out",!1,h),min:ze(this._reports,P.AUDIO,"delta_jitter_ms_out",h),max:Qe(this._reports,P.AUDIO,"delta_jitter_ms_out",h),volatility:Je(this._reports,P.AUDIO,"delta_jitter_ms_out",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Ze(this._reports,P.AUDIO,"delta_kbs_out",!1,h),min:ze(this._reports,P.AUDIO,"delta_kbs_out",h),max:Qe(this._reports,P.AUDIO,"delta_kbs_out",h),volatility:Je(this._reports,P.AUDIO,"delta_kbs_out",h),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Ze(this._reports,P.AUDIO,"delta_KBytes_out",!1,h),min:ze(this._reports,P.AUDIO,"delta_KBytes_out",h),max:Qe(this._reports,P.AUDIO,"delta_KBytes_out",h),volatility:Je(this._reports,P.AUDIO,"delta_KBytes_out",h),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},S={avg:Vf(this._reports,P.AUDIO,h),min:ze(this._reports,P.AUDIO,"delta_rtt_ms_out",h),max:Qe(this._reports,P.AUDIO,"delta_rtt_ms_out",h),volatility:Je(this._reports,P.AUDIO,"delta_rtt_ms_out",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=Tt(this._reports,P.AUDIO,"total_packets_lost_out",h),C=Tt(this._reports,P.AUDIO,"total_packets_out",h),A={lost:E,avg:Math.round((E/(E+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},R={emodel:{avg:Ze(this._reports,P.AUDIO,"mos_emodel_out",!1,h),min:ze(this._reports,P.AUDIO,"mos_emodel_out",h),max:Qe(this._reports,P.AUDIO,"mos_emodel_out",h),volatility:Je(this._reports,P.AUDIO,"mos_emodel_out",h)},effective:{avg:Ze(this._reports,P.AUDIO,"mos_out",!1,h),min:ze(this._reports,P.AUDIO,"mos_out",h),max:Qe(this._reports,P.AUDIO,"mos_out",h),volatility:Je(this._reports,P.AUDIO,"mos_out",h)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};n[h].jitter=_,n[h].rtt=S,n[h].traffic=T,n[h].bitrate=g,n[h].loss=A,n[h].mos=R}}),Object.keys(r[P.VIDEO]).forEach(h=>{const d=r[P.VIDEO][h];if(n[h]={type:P.VIDEO,direction:d.direction},d.direction===He.INBOUND){const _={avg:Ze(this._reports,P.VIDEO,"delta_jitter_ms_in",!1,h),min:ze(this._reports,P.VIDEO,"delta_jitter_ms_in",h),max:Qe(this._reports,P.VIDEO,"delta_jitter_ms_in",h),volatility:Je(this._reports,P.VIDEO,"delta_jitter_ms_in",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Ze(this._reports,P.VIDEO,"delta_kbs_in",!1,h),min:ze(this._reports,P.VIDEO,"delta_kbs_in",h),max:Qe(this._reports,P.VIDEO,"delta_kbs_in",h),volatility:Je(this._reports,P.VIDEO,"delta_kbs_in",h),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Ze(this._reports,P.VIDEO,"delta_KBytes_in",!1,h),min:ze(this._reports,P.VIDEO,"delta_KBytes_in",h),max:Qe(this._reports,P.VIDEO,"delta_KBytes_in",h),volatility:Je(this._reports,P.VIDEO,"delta_KBytes_in",h),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S=Tt(this._reports,P.VIDEO,"total_packets_lost_in",h),E=Tt(this._reports,P.VIDEO,"total_packets_in",h),C={lost:S,avg:Math.round((S/(S+E)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};n[h].jitter=_,n[h].traffic=T,n[h].bitrate=g,n[h].loss=C}else{const _={avg:Ze(this._reports,P.VIDEO,"delta_jitter_ms_out",!1,h),min:ze(this._reports,P.VIDEO,"delta_jitter_ms_out",h),max:Qe(this._reports,P.VIDEO,"delta_jitter_ms_out",h),volatility:Je(this._reports,P.VIDEO,"delta_jitter_ms_out",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Ze(this._reports,P.VIDEO,"delta_kbs_out",!1,h),min:ze(this._reports,P.VIDEO,"delta_kbs_out",h),max:Qe(this._reports,P.VIDEO,"delta_kbs_out",h),volatility:Je(this._reports,P.VIDEO,"delta_kbs_out",h),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Ze(this._reports,P.VIDEO,"delta_KBytes_out",!1,h),min:ze(this._reports,P.VIDEO,"delta_KBytes_out",h),max:Qe(this._reports,P.VIDEO,"delta_KBytes_out",h),volatility:Je(this._reports,P.VIDEO,"delta_KBytes_out",h),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={avg:Vf(this._reports,P.VIDEO,h),min:ze(this._reports,P.VIDEO,"delta_rtt_ms_out",h),max:Qe(this._reports,P.VIDEO,"delta_rtt_ms_out",h),volatility:Je(this._reports,P.VIDEO,"delta_rtt_ms_out",h),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=Tt(this._reports,P.VIDEO,"total_packets_lost_out",h),C=Tt(this._reports,P.VIDEO,"total_packets_out",h),A={lost:E,avg:Math.round((E/(E+C)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};n[h].jitter=_,n[h].rtt=S,n[h].traffic=T,n[h].bitrate=g,n[h].loss=A}})),{version:Gv,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:n,data:{rtt:{avg:Wv(this._reports,"data"),min:ze(this._reports,"data","delta_rtt_connectivity_ms"),max:Qe(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Je(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+s)*100||0)*100)/100}},video:{in:{avg:Math.round((i/(i+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Ze(this._reports,"data","delta_kbs_in"),min:ze(this._reports,"data","delta_kbs_in"),max:Qe(this._reports,"data","delta_kbs_in"),volatility:Je(this._reports,"data","delta_kbs_in")},out:{avg:Ze(this._reports,"data","delta_kbs_out"),min:ze(this._reports,"data","delta_kbs_out"),max:Qe(this._reports,"data","delta_kbs_out"),volatility:Je(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Ze(this._reports,"data","delta_KBytes_in"),min:ze(this._reports,"data","delta_KBytes_in"),max:Qe(this._reports,"data","delta_KBytes_in"),volatility:Je(this._reports,"data","delta_KBytes_in")},out:{avg:Ze(this._reports,"data","delta_KBytes_out"),min:ze(this._reports,"data","delta_KBytes_out"),max:Qe(this._reports,"data","delta_KBytes_out"),volatility:Je(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:Kv(this._reports),remoteConnection:Yv(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const js="extractor ",jf=(c,t,s,i)=>{let a=!1;const n=i[t].total_rtt_ms_out,r=i[t].total_rtt_measure_out,h=s?s[t].total_rtt_ms_out:0,d=s?s[t].total_rtt_measure_out:0,_={rtt:null,totalRTT:n,totalRTTMeasurements:r};if(c[K.TIMESTAMP]===i[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===r))return _;const g=1e3*Number(c[K.ROUND_TRIP_TIME]);let T=n+g,S=r+1;return a&&(T=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-h,S=Number(c[K.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:g,totalRTT:T,totalRTTMeasurements:S}},zv=(c,t,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:i[t].total_rtt_connectivity_ms,totalRTTMeasurements:i[t].total_rtt_connectivity_measure};const a=1e3*Number(c[K.CURRENT_ROUND_TRIP_TIME]);let n=i[t].total_rtt_connectivity_ms+a,r=i[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,K.TOTAL_ROUND_TRIP_TIME)&&(n=1e3*Number(c[K.TOTAL_ROUND_TRIP_TIME])-(s?s[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,K.RESPONSES_RECEIVED)&&(r=Number(c[K.RESPONSES_RECEIVED])-(s?s[t].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:n,totalRTTMeasurements:r}},_o=(c,t,s)=>c[K.TIMESTAMP]===s[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,K.JITTER)?null:1e3*(Number(c[K.JITTER])||0),Qv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[P.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[P.VIDEO].total_frames_decoded_in,total_decode_time:t[P.VIDEO].total_time_decoded_in};const s=c[K.FRAMES_DECODED],i=c[K.TOTAL_DECODE_TIME],a=i-t[P.VIDEO].total_time_decoded_in,n=s-t[P.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:n>0?a*1e3/n:0,frames_decoded:s,total_decode_time:i}},Xv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,K.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,K.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[P.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[P.VIDEO].total_frames_encoded_out,total_encode_time:t[P.VIDEO].total_time_encoded_out};const s=c[K.FRAMES_ENCODED],i=c[K.TOTAL_ENCODE_TIME],a=i-t[P.VIDEO].total_time_encoded_out,n=s-t[P.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:n>0&&a?a*1e3/n:0,frames_encoded:s,total_encode_time:i}},qf=(c,t,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_SENT))return{packetsSent:s[t].total_packets_out,packetsLost:s[t].total_packets_lost_out,bytesSent:s[t].total_KBytes_out};const a=Number(c[K.PACKETS_SENT])||0-(i?i[t].total_packets_out:0),n=a-s[t].total_packets_out,r=Number(c[K.BYTES_SENT])/1024-(i?i[t].total_KBytes_out:0),h=r-s[t].total_KBytes_out,d=c[K.TIMESTAMP]||Date.now(),_=i?i.timestamp:null;let g=s.timestamp;!g&&_&&(g=_);const T=g?d-g:0,S=T>0?h*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:n,KBytesSent:r,deltaKBytesSent:h,kbsSent:S}},Bf=(c,t,s,i)=>{let a=s[t].total_packets_lost_out,n=0,r=0;return Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)&&(a=Number(c[K.PACKETS_LOST])||0-(i?i[t].total_packets_lost_out:0),n=a-s[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,K.FRACTION_LOST)&&(r=Number(100*c[K.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:n,fractionLost:r}},Gf=(c,t,s,i)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,K.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,K.BYTES_RECEIVED))return{percent_packets_lost:s[t].percent_packets_lost_in,packetsReceived:s[t].total_packets_in,packetsLost:s[t].total_packets_lost_in,bytesReceived:s[t].total_KBytes_in};const a=Number(c[K.PACKETS_RECEIVED])||0-(i?i[t].total_packets_in:0),n=Number(c[K.PACKETS_LOST])||0-(i?i[t].total_packets_lost_in:0),r=n-s[t].total_packets_lost_in,h=a-s[t].total_packets_in,d=a!==s[t].total_packets_in?r*100/(r+h):0,_=Number(c[K.BYTES_RECEIVED])/1024-(i?i[t].total_KBytes_in:0),g=_-s[t].total_KBytes_in,T=c[K.TIMESTAMP]||Date.now(),S=i?i.timestamp:null;let E=s.timestamp;!E&&S&&(E=S);const C=E?T-E:0,A=C>0?g*.008*1024/C*1e3:0;return{percentPacketsLost:d,packetsReceived:a,deltaPacketsReceived:h,packetsLost:n,deltaPacketsLost:r,KBytesReceived:_,deltaKBytesReceived:g,kbsReceived:A}},Zv=c=>c[K.CANDIDATE_TYPE]!=="relay"?"":c[K.RELAY_PROTOCOL]||"",eS=c=>{if(!Object.prototype.hasOwnProperty.call(c,K.NETWORK_TYPE))return Yi.WIFI;switch(c[K.NETWORK_TYPE]){case cu.ETHERNET:return Yi.ETHERNET;case cu.CELLULAR_4G:return Yi.CELLULAR_4G;case cu.WIFI:return Yi.WIFI;default:return Yi.CELLULAR}},Wf=c=>!Object.prototype.hasOwnProperty.call(c,K.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,K.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[K.FRAME_WIDTH]||null,height:c[K.FRAME_HEIGHT]||null,framerate:c[K.FRAMES_PER_SECOND]},tS=c=>{const t=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_REASON)?c[K.QUALITY_LIMITATION_REASON]:null,s=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[K.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,i=Object.prototype.hasOwnProperty.call(c,K.QUALITY_LIMITATION_DURATIONS)?c[K.QUALITY_LIMITATION_DURATIONS]:null;return i&&Object.keys(i).forEach(a=>{i[a]>1e3&&(i[a]=Number(i[a]/1e3))}),{reason:t,durations:i,resolutionChanges:s}},sS=(c,t,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const i=(c[K.PLI]||0)-(s?s[P.VIDEO].total_pli_sent_in:0),a=(c[K.NACK]||0)-(s?s[P.VIDEO].total_nack_sent_in:0);return{pliCount:i,nackCount:a,deltaPliCount:i-t[P.VIDEO].total_pli_sent_in,deltaNackCount:a-t[P.VIDEO].total_nack_sent_in}},nS=(c,t,s)=>{if(!Object.prototype.hasOwnProperty.call(c,K.PLI)||!Object.prototype.hasOwnProperty.call(c,K.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const i=(c[K.PLI]||0)-(s?s[P.VIDEO].total_pli_received_out:0),a=(c[K.NACK]||0)-(s?s[P.VIDEO].total_nack_received_out:0);return{pliCount:i,nackCount:a,deltaPliCount:i-t[P.VIDEO].total_pli_received_out,deltaNackCount:a-t[P.VIDEO].total_nack_received_out}},rS=c=>({channels:c[K.CHANNELS]||null,clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null,sdp_fmtp_line:c[K.SDP_FMTP_LINE]||null}),iS=c=>({clock_rate:c[K.CLOCK_RATE]||null,mime_type:c[K.MIME_TYPE]||null}),lS=(c,t,s)=>{const i=(c[K.BYTES_RECEIVED]||0)/1024-(s?s.data.total_KBytes_in:0),a=(c[K.BYTES_SENT]||0)/1024-(s?s.data.total_KBytes_out:0),n=c[K.TIMESTAMP]||Date.now(),r=i-t.data.total_KBytes_in,h=a-t.data.total_KBytes_out,d=s?s.timestamp:null;let _=t.timestamp;!_&&d&&(_=d);const g=_?n-_:0,T=g>0?r*.008*1024/g*1e3:0,S=g>0?h*.008*1024/g*1e3:0;return{total_KBytes_received:i,total_KBytes_sent:a,delta_KBytes_received:r,delta_KBytes_sent:h,kbs_speed_received:T,kbs_speed_sent:S}},oS=c=>{const t=c[K.AVAILABLE_INCOMING_BITRATE]/1024||0,s=c[K.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:s}},aS=(c,t,s,i)=>{if(!c)return[];switch(c[K.TYPE]){case Qt.CANDIDATE_PAIR:let a=!1;if(c[K.NOMINATED]&&c[K.STATE]===P.SUCCEEDED&&(a=!0,Ue(js,`analyze() - got stats ${c[K.TYPE]} for ${s}`,c),K.SELECTED in c&&!c[K.SELECTED]&&(a=!1)),a){const r=c[K.LOCAL_CANDIDATE_ID],h=c[K.REMOTE_CANDIDATE_ID],d=lS(c,t,i),_=oS(c),g=zv(c,"data",i,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:h}},{type:ne.DATA,value:{total_KBytes_in:d.total_KBytes_received}},{type:ne.DATA,value:{total_KBytes_out:d.total_KBytes_sent}},{type:ne.DATA,value:{delta_KBytes_in:d.delta_KBytes_received}},{type:ne.DATA,value:{delta_KBytes_out:d.delta_KBytes_sent}},{type:ne.DATA,value:{delta_kbs_in:d.kbs_speed_received}},{type:ne.DATA,value:{delta_kbs_out:d.kbs_speed_sent}},{type:ne.DATA,value:{delta_kbs_bandwidth_in:_.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:_.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:g.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:g.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:g.totalRTTMeasurements}}]}break;case Qt.LOCAL_CANDIDATE:if(c[K.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:eS(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[K.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:Zv(c)}}];break;case Qt.REMOTE_CANDIDATE:if(c[K.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[K.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[K.PROTOCOL]||""}}];break;case Qt.INBOUND_RTP:{Ue(js,`analyze() - got stats ${c[K.TYPE]} for ${s}`,c);const r=c[K.SSRC],h=ft(r,t,He.INBOUND);h&&(h.timestamp=t.timestamp);const d=ft(r,i,He.INBOUND);if(d&&(d.timestamp=i.timestamp),c[K.MEDIA_TYPE]===P.AUDIO){const _=Gf(c,P.AUDIO,h,d),g=_o(c,P.AUDIO,h),T=c[K.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:_.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:_.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:_.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:_.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:_.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:_.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:_.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:_.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[K.MEDIA_TYPE]===P.VIDEO){const _=Qv(c,h),g=Gf(c,P.VIDEO,h,d),T=_o(c,P.VIDEO,h),S=c[K.DECODER_IMPLEMENTATION]||null,E=c[K.CODEC_ID]||null,C=Wf(c),A=sS(c,h,d);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:E}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:g.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:r,type:ne.VIDEO,value:{decoder_in:S}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_decode_frame_in:_.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:_.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:_.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:A.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:C}}]}break}case Qt.OUTBOUND_RTP:{Ue(js,`analyze() - got stats ${c[K.TYPE]} for ${s}`,c);const r=c[K.SSRC],h=ft(r,t,He.OUTBOUND);h&&(h.timestamp=t.timestamp);const d=ft(r,i,He.OUTBOUND);if(d&&(d.timestamp=i.timestamp),c[K.MEDIA_TYPE]===P.AUDIO){const _=c[K.CODEC_ID]||null,g=qf(c,P.AUDIO,h,d);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:_}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:g.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:g.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:g.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:g.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:g.kbsSent}}]}if(c[K.MEDIA_TYPE]===P.VIDEO){const _=c[K.ENCODER_IMPLEMENTATION]||null,g=c[K.CODEC_ID]||null,T=Xv(c,h),S=Wf(c),E=tS(c),C=nS(c,h,d),A=qf(c,P.VIDEO,h,d);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:A.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:A.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:A.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:A.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:A.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:_}},{ssrc:r,type:ne.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_received_out:C.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:C.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:C.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:C.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_out:S}},{ssrc:r,type:ne.VIDEO,value:{limitation_out:E}}]}break}case Qt.MEDIA_SOURCE:{Ue(js,`analyze() - got stats ${c[K.TYPE]} for ${s}`,c);break}case Qt.TRACK:{Ue(js,`analyze() - got stats ${c[K.TYPE]} for ${s}`,c);break}case Qt.CODEC:const n=[];return Object.keys(t[P.AUDIO]).forEach(r=>{const h=t[P.AUDIO][r];if(h.codec_id_in===c[K.ID]||h.codec_id_out===c[K.ID]){Ue(js,`analyze() - got stats ${c[K.TYPE]} for ${s}`,c);const d=rS(c);c[K.ID]===h.codec_id_in?n.push({ssrc:h.ssrc,type:ne.AUDIO,value:{codec_in:d}}):n.push({ssrc:h.ssrc,type:ne.AUDIO,value:{codec_out:d}})}}),Object.keys(t[P.VIDEO]).forEach(r=>{const h=t[P.VIDEO][r];if(h.codec_id_in===c[K.ID]||h.codec_id_out===c[K.ID]){Ue(js,`analyze() - got stats ${c[K.TYPE]} for ${s}`,c);const d=iS(c);c[K.ID]===h.codec_id_in?n.push({ssrc:h.ssrc,type:ne.VIDEO,value:{codec_in:d}}):n.push({ssrc:h.ssrc,type:ne.VIDEO,value:{codec_out:d}})}}),n;case Qt.REMOTE_INBOUND_RTP:{Ue(js,`analyze() - got stats ${c[K.TYPE]} for ${s}`,c);const r=c[K.SSRC],h=ft(r,t,He.OUTBOUND),d=ft(r,i,He.OUTBOUND);if(c[K.KIND]===P.AUDIO){const _=jf(c,P.AUDIO,d,h),g=_o(c,P.AUDIO,h),T=Bf(c,P.AUDIO,h,d);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(c[K.KIND]===P.VIDEO){const _=jf(c,P.VIDEO,d,h),g=_o(c,P.VIDEO,h),T=Bf(c,P.VIDEO,h,d);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:_.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:_.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:_.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[K.TIMESTAMP]}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},zo=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),uS=(c,t=P.AUDIO,s,i,a)=>{const n=ft(a,c,He.INBOUND),r=ft(a,s,He.INBOUND),h=ft(a,i,He.INBOUND),d=[],_=[],g=n[t].percent_packets_lost_in,T=n[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=h&&h[t].delta_jitter_ms_in||null,C=c.data.delta_rtt_connectivity_ms,A=s&&s.data.delta_rtt_connectivity_ms||null,R=i&&i.data.delta_rtt_connectivity_ms||null;C&&d.push(C),A&&d.push(A),R&&d.push(R),T&&_.push(T),s&&S&&_.push(S),i&&E&&_.push(E);const F=d.length>0?Ws(d):100,I=_.length>0?Ws(_):10,ie=93.2-g,N=.18*ie*ie-27.9*ie+1126.62,$=(F+I)/2,ve=$-177.3<0?0:1,_e=.024*$+.11*($-177.3)*ve,U=N-_e;return zo(U)},cS=(c,t=P.AUDIO,s,i,a)=>{const n=ft(a,c,He.OUTBOUND),r=ft(a,s,He.OUTBOUND),h=ft(a,i,He.OUTBOUND),d=[],_=[],g=n[t].percent_packets_lost_out,T=n[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=h&&h[t].delta_rtt_ms_out||null,C=n[t].delta_jitter_ms_out,A=r&&r[t].delta_jitter_ms_out||null,R=h&&h[t].delta_jitter_ms_out||null,F=c.data.delta_rtt_connectivity_ms,I=s&&s.data.delta_rtt_connectivity_ms||null,ie=i&&i.data.delta_rtt_connectivity_ms||null;T?d.push(T):F&&d.push(F),S?d.push(S):I&&d.push(I),E?d.push(E):ie&&d.push(ie),C&&_.push(C),s&&A&&_.push(A),i&&R&&_.push(R);const N=d.length>0?Ws(d):100,$=_.length>0?Ws(_):10,ve=93.2-g,_e=.18*ve*ve-27.9*ve+1126.62,U=(N+$)/2,x=U-177.3<0?0:1,q=.024*U+.11*(U-177.3)*x,j=_e-q;return zo(j)},fS=(c,t=P.AUDIO,s,i,a)=>{const n=ft(a,c,He.INBOUND),r=ft(a,s,He.INBOUND),h=ft(a,i,He.INBOUND),d=[],_=[],g=n[t].percent_packets_lost_in/100,T=n[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=h&&h[t].delta_jitter_ms_in||null,C=c.data.delta_rtt_connectivity_ms,A=s&&s.data.delta_rtt_connectivity_ms||null,R=i&&i.data.delta_rtt_connectivity_ms||null;C&&d.push(C),A&&d.push(A),R&&d.push(R),T&&_.push(T),r&&S&&_.push(S),h&&E&&_.push(E);const F=d.length>0?Ws(d):100,I=_.length>0?Ws(_):10,ie=0,N=19.8,$=29.7,ve=30,_e=(F+I)/2+ve,U=_e-177.3<0?0:1,x=.024*_e+.11*(_e-177.3)*U,j=93.2-(ie+N*Math.log(1+$*g)+x);return zo(j)},dS=(c,t=P.AUDIO,s,i,a)=>{const n=ft(a,c,He.OUTBOUND),r=ft(a,s,He.OUTBOUND),h=ft(a,i,He.OUTBOUND),d=[],_=[],g=n[t].percent_packets_lost_out/100,T=n[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=h&&h[t].delta_rtt_ms_out||null,C=n[t].delta_jitter_ms_out,A=r&&r[t].delta_jitter_ms_out||null,R=h&&h[t].delta_jitter_ms_out||null,F=c.data.delta_rtt_connectivity_ms,I=s&&s.data.delta_rtt_connectivity_ms||null,ie=i&&i.data.delta_rtt_connectivity_ms||null;T?d.push(T):F&&d.push(F),S?d.push(S):I&&d.push(I),E?d.push(E):ie&&d.push(ie),C&&_.push(C),r&&A&&_.push(A),h&&R&&_.push(R);const N=d.length>0?Ws(d):100,$=_.length>0?Ws(_):10,ve=0,_e=19.8,U=29.7,x=30,q=(N+$)/2+x,j=q-177.3<0?0:1,Y=.024*q+.11*(q-177.3)*j,Q=93.2-(ve+_e*Math.log(1+U*g)+Y);return zo(Q)};class hS{constructor(t,s){this._callbacks={onreport:null,onticket:null},this._id=qv(),this._moduleName=this._id,this._probeId=s,this._config=t,this._exporter=new Jv(t),this._state=Ts.IDLE,this.registerToPCEvents(),Rn(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,s,i,a){const n=(d,_)=>d===P.AUDIO?_===Qt.INBOUND_RTP?{...Fd}:{...Vd}:_===Qt.INBOUND_RTP?{...jd}:{...qd},r=$v(s);r.pname=this._config.pname,r.call_id=this._config.cid,r.user_id=this._config.uid,r.count=s?s.count+1:1;let h=null;return t.forEach(d=>{!h&&d.timestamp&&(h=d.timestamp),aS(d,r,r.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let T=r[g.type][g.ssrc];T||(T=n(g.type,d.type),T.ssrc=g.ssrc,r[g.type][g.ssrc]=T),Object.keys(g.value).forEach(S=>{T[S]=g.value[S]})}else Object.keys(g.value).forEach(T=>{r[g.type][T]=g.value[T]})})}),r.timestamp=h,Object.keys(r[P.AUDIO]).forEach(d=>{const _=r[P.AUDIO][d];_.direction===He.INBOUND?(_.mos_emodel_in=uS(r,P.AUDIO,s,i,_.ssrc),_.mos_in=fS(r,P.AUDIO,s,i,_.ssrc)):(_.mos_emodel_out=cS(r,P.AUDIO,s,i,_.ssrc),_.mos_out=dS(r,P.AUDIO,s,i,_.ssrc))}),r}async takeReferenceStats(){return new Promise((t,s)=>{const i=Date.now();setTimeout(async()=>{try{const a=Date.now()-i,n=Date.now(),r=await this._config.pc.getStats(),h=this.analyze(r,null,null,null),d=Date.now();h.experimental.time_to_measure_ms=d-n,h.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(h),Ue(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(a){s(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Ts.RUNNING||!this._config.pc)return Ue(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),s=await this._config.pc.getStats(),i=this.analyze(s,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return i.experimental.time_to_measure_ms=a-t,this._exporter.addReport(i),Ue(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(i),i}catch(t){return hr(this._moduleName,`got error ${t}`),null}}async start(){Ue(this._moduleName,"starting"),this.state=Ts.RUNNING,this._startedTime=this._exporter.start(),Ue(this._moduleName,"started")}async mute(){this.state=Ts.MUTED,Ue(this._moduleName,"muted")}async unmute(){this.state=Ts.RUNNING,Ue(this._moduleName,"unmuted")}async stop(t){if(Ue(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Ts.IDLE,this._config.ticket){const{ticket:s}=this._exporter;this.fireOnTicket(s)}this._exporter.reset(),Ue(this._moduleName,"stopped")}registerCallback(t,s,i){t in this._callbacks?(this._callbacks[t]={callback:s,context:i},Ue(this._moduleName,`registered callback '${t}'`)):hr(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Ue(this._moduleName,`unregistered callback '${t}'`)):hr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&xu(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&xu(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,Ue(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,s,i,a){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:s,name:i,description:a})}async registerToPCEvents(){const{pc:t}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const s=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${s.length} devices found`,"Media Devices state")}catch{hr(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const i=t.iceConnectionState;i===Ki.CONNECTED||i===Ki.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",i,"ICE connection state"):i===Ki.DISCONNECTED||i===Ki.FAILED?this.addCustomEvent(new Date().toJSON(),"call",i,"ICE connection state"):i===Ki.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const i=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",i,"ICE gathering state")},t.ontrack=i=>{this.addCustomEvent(new Date().toJSON(),"call",`${i.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const s=t.getReceivers();if(s&&s.length>0){const i=s[0],{transport:a}=i;if(a){const{iceTransport:n}=a;n&&(n.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class _S{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||jv(),this._moduleName=this._id,Rn(this._moduleName,"probe created"),this._config=t,this._collector=new hS(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(t){this._collector.state=t}addCustomEvent(t,s,i,a=new Date().toJSON()){this._collector.addCustomEvent(a,s,t,i)}get isRunning(){return this._collector.state===Ts.RUNNING}get isIdle(){return this._collector.state===Ts.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){No(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const It="engine ";class pS{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},Rn(It,`configured for probing every ${this._config.refreshEvery}ms`),Rn(It,`configured for starting after ${this._config.startAfter}ms`),Rn(It,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ue(It,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,s){if(!t)throw new Error("undefined peer connection");const i=Fv(t,s,this._config),a=new _S(i);return this._probes.push(a),Ue(It,`${this._probes.length} probes registered`),a}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===Ts.RUNNING&&t.stop(),this._probes=this._probes.filter(s=>t.id!==s.id)}async start(){const t=()=>{this._probes.forEach(n=>n.start())},s=async()=>Promise.all(this._probes.map(n=>n.takeReferenceStats())),i=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const n=Lv(),r=this._probes.filter(h=>h.isRunning);for(const h of r){const d=await h.collectStats();d&&n.probes.push(d),Ue(It,`got probe ${h.id}`),await Ff(0)}return n.delta_time_to_measure_probes_ms=yn(n.probes,"experimental","time_to_measure_ms"),n.delta_KBytes_in=yn(n.probes,"data","delta_KBytes_in"),n.delta_KBytes_out=yn(n.probes,"data","delta_KBytes_out"),n.delta_kbs_in=yn(n.probes,"data","delta_kbs_in"),n.delta_kbs_out=yn(n.probes,"data","delta_kbs_out"),n.total_time_decoded_in=yn(n.probes,"video","total_time_decoded_in"),n.total_time_encoded_out=yn(n.probes,"video","total_time_encoded_out"),n};for(Ue(It,"starting to collect"),t(),Ue(It,"generating reference reports..."),await s(),Ue(It,"reference reports generated"),this._startedTime=Date.now();i();)if(Ue(It,`wait ${this._config.refreshEvery}ms before collecting`),await Ff(this._config.refreshEvery),i()){Ue(It,"collecting...");const n=Date.now(),r=await a(),h=Date.now();r.delta_time_consumed_to_measure_ms=h-n,this.fireOnReports(r),Ue(It,"collected")}Ue(It,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const s=i=>{this._probes.forEach(a=>{a.stop(i)})};Rn(It,"stop collecting"),s(t)}registerCallback(t,s,i){t in this._callbacks?(this._callbacks[t]={callback:s,context:i},Ue(It,`registered callback '${t}'`)):hr(It,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Ue(this._moduleName,`unregistered callback '${t}'`)):hr(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&xu(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const mS="interface ";class gS{constructor(t){this._config=Vv(t),Rn(mS,`welcome to ${this._config.name} version ${this._config.version}`),Ov(this._config.verbose||!1),this._engine=new pS(this._config)}setupLogLevel(t){Dv(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,s){return this._engine.addNewProbe(t,s)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function TS(c,t){return Object.keys(c).filter(s=>t.includes(s)).reduce((s,i)=>{const a=i;return{...s,[a]:c[a]}},{})}const vS=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],SS={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class ES{constructor(t){this.intervals={},this.analysers={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}async start(t,s,i){s&&s.getTracks().length&&await this.beginCalculation(t,s,i)}stop(t){this.clearVolumeInterval(t),this.analysers[t]&&typeof this.analysers[t].disconnect=="function"&&(this.analysers[t].disconnect(),delete this.analysers[t])}clearVolumeInterval(t){this.intervals[t]&&(clearInterval(this.intervals[t]),delete this.intervals[t])}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{this.stop(t)}),this.intervals={},this.analysers={}}async beginCalculation(t,s,i){this.clearVolumeInterval(i);const a=t.createAnalyser(),n=t.createMediaStreamSource(s);a.smoothingTimeConstant=.8,a.fftSize=1024,n.connect(a),this.analysers[i]=a,this.intervals[i]=setInterval(()=>{const r=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(r);let h=0;const d=r.length;for(let g=0;g<d;g++)h+=r[g];const _=h/d;this.onChangeFunction(i,_)},this.emitInterval)}}class yS{constructor(){this.resumePromise=null,this.context=new AudioContext,this.setupErrorHandling()}setupErrorHandling(){!this.context||typeof this.context.addEventListener!="function"||this.context.addEventListener("statechange",()=>{(this.context.state==="interrupted"||this.context.state==="closed")&&console.warn(`[ManagedAudioContext] AudioContext state changed to: ${this.context.state}`)})}createNewContext(){return console.log("[ManagedAudioContext] Creating new AudioContext instance"),this.context=new AudioContext,this.setupErrorHandling(),this.context}async getContext(){if(this.context.state==="closed")return console.warn("[ManagedAudioContext] AudioContext is closed, creating new instance"),this.createNewContext();if(this.context.state==="interrupted"){console.warn("[ManagedAudioContext] AudioContext is interrupted, attempting to resume");try{this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(t=>{console.error("[ManagedAudioContext] Failed to resume interrupted context:",t),this.resumePromise=null,this.createNewContext()})),await this.resumePromise}catch(t){return console.error("[ManagedAudioContext] Error resuming context, creating new one:",t),this.createNewContext()}}return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(t=>{throw console.error("[ManagedAudioContext] Failed to resume suspended context:",t),this.resumePromise=null,t})),await this.resumePromise),this.context.state==="closed"?(console.warn("[ManagedAudioContext] Context closed after resume attempt, creating new instance"),this.createNewContext()):this.context}}const po={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},CS=0;function du(c,t){const s=new AudioContext,i=s.createMediaStreamSource(c),a=s.createMediaStreamSource(new MediaStream([t])),n=s.createMediaStreamDestination();return i.connect(n),a.connect(n),n.stream}class AS{constructor(t){var s;this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.isCallWaitingEnabled=!0,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.conferenceNodes={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.vadSession=null,this.vadSessionState={currentMode:"clean",isSpeaking:!1},this.vadInterval=null,this.vadMrsInterval=null,this.vadSessionGeneration=0,this.ringbackTimers={},this.ringbackAudioContexts={},this.ringbackSessionProgressReceived={},this.hangupBeepContext=null,this.managedAudioContext=new yS,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new ES({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices(),this.processVADConfiguration(((s=this.context.options.configuration)==null?void 0:s.noiseReductionOptions)||{}),this.setupVADInstance()}setVADConfiguration(t){if(!this.MicVAD)throw new Error("VAD module is not provided in the initial configuration");const s=Object.keys(t);for(const i of s)this.noiseReduction[i]=t[i];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var s,i;const t=(i=(s=this.context.options.configuration)==null?void 0:s.noiseReductionOptions)==null?void 0:i.vadModule;t&&t.MicVAD?(this.MicVAD=t.MicVAD,console.log("✅ VAD module loaded successfully")):this.noiseReduction.mode!=="disabled"&&(console.warn("⚠️ Noise reduction is enabled but VAD module is not provided. To use VAD features, please install @ricky0123/vad-web and pass it via configuration.noiseReductionOptions.vadModule option."),this.noiseReduction.mode="disabled")}processVADConfiguration(t){this.noiseReduction={mode:t.mode||"disabled",checkEveryMs:t.checkEveryMs||500,noiseCheckInterval:t.noiseCheckInterval||2e3,noiseThreshold:t.noiseThreshold||.004,vadConfig:t.vadConfig||{},baseAssetPath:t.baseAssetPath||"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:t.onnxWASMBasePath||"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/"}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(i=>!i.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return Ld()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(po.SELECTED_INPUT_DEVICE)||"default",s=localStorage.getItem(po.SELECTED_OUTPUT_DEVICE)||"default";try{const i=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(t),await this.setSpeaker(s),navigator.mediaDevices.addEventListener("devicechange",async()=>{const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}),i.getTracks().forEach(n=>n.stop())}catch(i){console.error(i)}}async cleanupConferenceNodes(t){const s=this.conferenceNodes[t];if(!s)return;let i=0;s.sources.forEach((r,h)=>{var d;try{r.disconnect(),i++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting source ${h}:`,_),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting source ${h}:`,_)}});let a=0;s.destinations.forEach((r,h)=>{var d;try{r.disconnect(),a++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${h}:`,_),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting destination ${h}:`,_)}});let n=0;s.gains.forEach((r,h)=>{var d;try{r.disconnect(),n++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${h}:`,_),(d=this.context.logger)==null||d.error(`[cleanupConferenceNodes] Error disconnecting gain ${h}:`,_)}}),delete this.conferenceNodes[t]}setCallTime(t){const s={...t};delete s.callId,this.callTime={...this.callTime,[t.callId]:s},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const s={...this.callTime};delete s[t],this.callTime={...s},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,s){this.timeIntervals={...this.timeIntervals,[t]:s}}removeTimeInterval(t){const s={...this.timeIntervals};s[t]&&(clearInterval(s[t]),delete s[t],this.timeIntervals={...s})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,s){this.context.emit("changeCallVolume",{callId:t,volume:s})}getNoiseReductionMode(){return this.noiseReduction.mode}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,s){if(!/^[A-D0-9*#]+$/g.test(s))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[t].sendDTMF(s)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const s=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(i=>i.enabled=!t),this.roomReconfigure(s)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:s,automatic:i}){const a=this.extendedCalls[t];if(!a)return;a._automaticHold=i??!1;const n=new Promise((r,h)=>{const d=setTimeout(()=>{h(new Error("Hold operation timeout"))},5e3),_=()=>{clearTimeout(d),a.putOnHoldTimestamp=s?Date.now():void 0,r()},g=T=>{clearTimeout(d),h(T)};try{s?(this.stopSessionVad(),a.hold({},_)):a.unhold({},_)}catch(T){g(T)}});try{await n,this.updateCall(a);const r=Object.values(this.extendedCalls).filter(h=>h.roomId===a.roomId&&(s?t!==h._id:!0));r.length>1&&await this.doConference(r)}catch(r){throw console.error("Hold operation failed:",r),r}}holdCall(t,s=!1){return this.processHold({callId:t,automatic:s,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===CS).forEach(t=>this.terminateCall(t._id))}answerCall(t){const s=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),s.answer(this.sipOptions),this.updateCall(s),this.setActiveRoom(s.roomId),s.connection.addEventListener("track",i=>{this.triggerAddStream(i,s)})}async moveCall(t,s){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:s}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=Mf(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const i={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...i}},this.context.emit("updateRoom",{room:i,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const s=/answer-after=0/,a=t.request.getHeader("Call-Info");return a&&s.test(a)}refreshRemotePartyId(t,s){const i=s.getHeader("Remote-Party-ID");if(!i)return!1;let a=!1;const n=Lf(i);n!==null&&t._remote_party_display_name!==n&&(t._remote_party_display_name=n,a=!0);const r=$f(i);return r!==null&&t._remote_party_uri_user!==r&&(t._remote_party_uri_user=r,a=!0),a}addCall(t,s=!0){this.activeCalls={...this.activeCalls,[t._id]:Mf(t)},this.extendedCalls[t._id]=t,s&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const i={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(i.isMoving=t.isMoving),t.isTransferring!==void 0&&(i.isTransferring=t.isTransferring),t.isMerging!==void 0&&(i.isMerging=t.isMerging),t.isTransferred!==void 0&&(i.isTransferred=t.isTransferred),this.callStatus={...this.callStatus,[t.callId]:{...i}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const s={...this.callStatus};delete s[t],this.callStatus={...s},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}async setupActiveStream(){const t=await lu(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);t.getTracks().forEach(s=>s.enabled=!this.isMuted),await this.setActiveStream(t)}async getActiveStream(){const t=await lu(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(s=>s.enabled=!this.isMuted),await this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:i})=>i===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const s=Object.values(this.extendedCalls).filter(i=>i.roomId===this.currentActiveRoomId);s.length===1?Object.values(s).forEach(async i=>{await this.setupActiveStream();const a=this.activeStream;i.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(i)}):await this.doConference(s)}async setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===t))return;this.setSelectedOutputDevice(t);const s=Object.values(this.extendedCalls);if(s.length===0)return;const i=s.filter(a=>a.roomId===this.currentActiveRoomId);i.length===1?s.forEach(a=>{var n;(n=a.audioTag)==null||n.setSinkId(t),this.updateCall(a)}):await this.doConference(i)}removeRoom(t){const s={...this.activeRooms},i={...s[t]};delete s[t],this.activeRooms={...s},this.context.emit("removeRoom",{room:i,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(s=>s.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}async startNoiseMonitor({stream:t,onNoiseDetected:s,onNoiseStop:i}){var _,g,T;let a;try{a=await this.managedAudioContext.getContext()}catch(S){console.error("[startNoiseMonitor] Failed to get AudioContext:",S),(_=this.context.logger)==null||_.error("[startNoiseMonitor] Failed to get AudioContext:",S);return}let n,r;try{n=a.createMediaStreamSource(t.clone()),r=a.createAnalyser()}catch(S){console.error("[startNoiseMonitor] Failed to create audio nodes:",S),console.error("[startNoiseMonitor] AudioContext state:",a.state),(g=this.context.logger)==null||g.error("[startNoiseMonitor] Failed to create audio nodes:",S),(T=this.context.logger)==null||T.error("[startNoiseMonitor] AudioContext state:",a.state);return}r.fftSize=1024;const h=new Float32Array(r.fftSize);n.connect(r);const d=[];this.vadInterval&&(clearInterval(this.vadInterval),this.vadInterval=null),this.vadMrsInterval&&(clearInterval(this.vadMrsInterval),this.vadMrsInterval=null),this.vadMrsInterval=setInterval(()=>{r.getFloatTimeDomainData(h);const S=Cv(h);d.push(S);const E=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);d.length>E&&d.shift()},this.noiseReduction.checkEveryMs),this.vadInterval=setInterval(()=>{var A;if(d.length===0)return;const S=d.reduce((R,F)=>R+F,0)/d.length,E=this.vadSessionState;if(!E){console.warn("[startNoiseMonitor] State not found, stopping interval"),(A=this.context.logger)==null||A.warn("[startNoiseMonitor] State not found, stopping interval"),this.vadInterval&&(clearInterval(this.vadInterval),this.vadInterval=null),this.vadMrsInterval&&(clearInterval(this.vadMrsInterval),this.vadMrsInterval=null);return}const C=S>this.noiseReduction.noiseThreshold;E.isSpeaking||(C&&E.currentMode==="clean"?(E.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",!0),s()):!C&&E.currentMode==="noisy"&&(E.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",!1),i()))},this.noiseReduction.noiseCheckInterval)}async processVADForActiveStream(t={}){var g;const s=this.activeStream;this.stopSessionVad();const i=this.vadSessionGeneration,a=()=>i!==this.vadSessionGeneration;this.vadSessionState={currentMode:"clean",isSpeaking:!1};const n=await this.managedAudioContext.getContext();if(a())return;const r=await Av(s,n,150);if(a())return;let h=!1;const d=Object.values(this.extendedCalls).filter(T=>T.roomId===this.currentActiveRoomId),_=await this.MicVAD.new({getStream:()=>new Promise(T=>T(s)),pauseStream:async()=>{},resumeStream:async T=>T,...SS,...this.noiseReduction.vadConfig,baseAssetPath:this.noiseReduction.baseAssetPath,onnxWASMBasePath:this.noiseReduction.onnxWASMBasePath,onFrameProcessed:()=>{var T,S;if(!a()&&!h){if(h=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){if(t&&Object.keys(t).length)Object.keys(t).forEach(E=>{const C=this.extendedCalls[E];if(C&&C.connection.getSenders()[0]){const A=du(r.stream,t[E]);C.connection.getSenders()[0].replaceTrack(A.getAudioTracks()[0])}});else{const E=d[0],C=(T=E==null?void 0:E.connection)==null?void 0:T.getSenders()[0],A=r.stream.getAudioTracks()[0];C&&C.replaceTrack(A)}return}if(!this.vadSessionState){console.error("[processVAD] CRITICAL: State not found"),(S=this.context.logger)==null||S.error("[processVAD] CRITICAL: State not found");return}this.startNoiseMonitor({stream:s,onNoiseDetected:async()=>{var E;if(console.log("[processVad] - Replace track with Vad Controlled"),(E=this.context.logger)==null||E.log("[processVad] - Replace track with Vad Controlled"),t&&Object.keys(t).length)Object.keys(t).forEach(C=>{const A=this.extendedCalls[C];if(A&&A.connection.getSenders()[0]){const R=du(r.stream,t[C]);A.connection.getSenders()[0].replaceTrack(R.getAudioTracks()[0])}});else{const C=d[0];C.connection.getSenders()[0]&&C.connection.getSenders()[0].replaceTrack(r.stream.getAudioTracks()[0])}},onNoiseStop:async()=>{if(console.log("Replace track with Original"),t&&Object.keys(t).length)Object.keys(t).forEach(E=>{const C=this.extendedCalls[E];if(!C)return;const A=C.connection.getSenders()[0];if(A&&A.track&&A.transport&&A.transport.state!=="closed"&&A.transport.state!=="failed"){const R=du(s,t[E]);A.replaceTrack(R.getAudioTracks()[0])}});else{const E=d[0].connection.getSenders()[0];E&&E.track&&E.transport&&E.transport.state!=="closed"&&E.transport.state!=="failed"&&E.replaceTrack(s.getAudioTracks()[0])}}})}},onSpeechStart:()=>{a()||(console.log("🎤 Speech started"),r.setSpeaking(!0),this.vadSessionState.isSpeaking=!0)},onSpeechEnd:()=>{a()||(console.log("🛑 Speech end"),r.setSpeaking(!1),this.vadSessionState.isSpeaking=!1)}});if(a()){try{_.pause()}catch(T){(g=this.context.logger)==null||g.error("[processVADForActiveStream] Error pausing stale vadSession:",T)}return}this.vadSession&&(this.vadSession.pause(),this.vadSession=null),this.vadSession=_,_.start()}stopSessionVad(){this.vadSessionGeneration++,this.vadSession&&(this.vadSession.pause(),this.vadSession=null),this.vadInterval&&(clearInterval(this.vadInterval),this.vadInterval=null),this.vadMrsInterval&&(clearInterval(this.vadMrsInterval),this.vadMrsInterval=null),this.vadSessionState&&(this.vadSessionState={currentMode:"clean",isSpeaking:!1},this.context.emit("changeNoiseReductionState",!1))}async roomReconfigure(t){var a,n,r,h;if(t===void 0)return;const s=Object.values(this.extendedCalls).filter(d=>d.roomId===t),i=this.currentActiveRoomId===t;if(console.log("[roomReconfigure] - Calls In Room:",s),(a=this.context.logger)==null||a.log("[roomReconfigure] - Calls In Room:",s),s.forEach((d,_)=>{if(d.audioTag){d.connection.getReceivers().forEach(T=>{T.track.enabled=!d.localMuted}),i&&this.muteReconfigure(d);const g=!i;d.audioTag.muted=g,this.updateCall(d)}}),s.length===0){!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t),console.log("[roomReconfigure] - Delete empty room",t),(n=this.context.logger)==null||n.log("[roomReconfigure] - Delete empty room",t),this.deleteRoomIfEmpty(t);return}if(s.length===1&&!i){const d=s[0];d.isOnHold().local||await this.holdCall(d._id,!0),!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}if(s.length===1&&i){const d=s[0];d.isOnHold().local&&d._automaticHold&&await this.unholdCall(d._id);const T=(((r=d.connection)==null?void 0:r.getSenders())||[])[0];if(d.connection&&T)try{await this.setupActiveStream();const E=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&(console.log("[roomReconfigure] - Call processVAD from roomReconfigure"),(h=this.context.logger)==null||h.log("[roomReconfigure] - Call processVAD from roomReconfigure"),this.processVADForActiveStream());const C=E.getTracks();await T.replaceTrack(C[0]),this.muteReconfigure(d)}catch(E){console.error(E)}!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}s.length>1&&await this.doConference(s)}async doConference(t){var g,T,S,E,C,A,R,F;if(console.log("[doConference] - In doConference, sessions:",t),(g=this.context.logger)==null||g.log("[doConference] - In doConference, sessions:",t),t.length===0)return;const s=t[0].roomId,i=this.currentActiveRoomId===s;if(t.find(I=>I.roomId!==s))return;let n;try{n=await this.managedAudioContext.getContext()}catch(I){console.error("[doConference] Failed to get AudioContext:",I),(T=this.context.logger)==null||T.error("[doConference] Failed to get AudioContext:",I);return}const r=n.state;if(r!=="running")if(console.error(`[doConference] ERROR: AudioContext is not running! State: ${r}`),(S=this.context.logger)==null||S.error(`[doConference] ERROR: AudioContext is not running! State: ${r}`),r==="suspended"||r==="interrupted")try{await n.resume();const I=n.state;if(I!=="running"){console.error(`[doConference] Failed to resume AudioContext, state: ${I}`),(E=this.context.logger)==null||E.error(`[doConference] Failed to resume AudioContext, state: ${I}`);return}}catch(I){console.error("[doConference] Error resuming AudioContext:",I),(C=this.context.logger)==null||C.error("[doConference] Error resuming AudioContext:",I);return}else if(r==="closed"){console.error("[doConference] AudioContext is closed, cannot proceed"),(A=this.context.logger)==null||A.error("[doConference] AudioContext is closed, cannot proceed");return}else return;await this.cleanupConferenceNodes(s),this.conferenceNodes[s]={sources:new Map,destinations:new Map,gains:new Map};const h=this.conferenceNodes[s],d=new Map;console.log("[doConference] - Before sessions forEach, sessions:",t),(R=this.context.logger)==null||R.log("[doConference] - Before sessions forEach, sessions:",t),t.forEach((I,ie)=>{var N,$,ve;if(console.log("[doConference] - In sessions forEach, iteration for",I._id),(N=this.context.logger)==null||N.log("[doConference] - In sessions forEach, iteration for",I._id),I&&I.connection){const _e=I.connection.getReceivers();console.log("[doConference] - Receivers list length for",I._id,_e.length),($=this.context.logger)==null||$.log("[doConference] - Receivers list length for",I._id,_e.length),_e.forEach((U,x)=>{var Y,V,Q,k,M,B;U.track.enabled=!I.localMuted;const q=(Y=U.track)==null?void 0:Y.id;(V=U.track)==null||V.readyState,(Q=U.track)==null||Q.kind;const j=`${I._id}-${q}`;console.log("[doConference] - Gathering receiver tracks",I._id),console.log("[doConference] - Receiver track readyState",U.track.readyState),(k=this.context.logger)==null||k.log("[doConference] - Gathering receiver tracks",I._id),(M=this.context.logger)==null||M.log("[doConference] - Receiver track readyState",U.track.readyState),U.track&&U.track.readyState==="live"&&(console.log("[doConference] - Gathered receiver track",I._id),(B=this.context.logger)==null||B.log("[doConference] - Gathered receiver track",I._id),d.set(j,U.track))})}else console.log("[doConference] - No session or RTC connection, session:",I),(ve=this.context.logger)==null||ve.log("[doConference] - No session or RTC connection, session:",I)}),await this.setupActiveStream();const _={};await bv.forEach(t,async(I,ie)=>{var Y,V,Q,k,M;if(!I||!I.connection){console.log("[doConference] - Return because of no session or connection, session:",I),(Y=this.context.logger)==null||Y.log("[doConference] - Return because of no session or connection, session:",I);return}const N=n.createMediaStreamDestination(),$=n.createMediaStreamDestination();h.destinations.set(I._id,N),h.destinations.set(`${I._id}-others`,$);const ve=I.connection.getReceivers(),_e=ve.length>0;console.log(`[doConference] Session ${I._id} has ${ve.length} receivers`),(V=this.context.logger)==null||V.log(`[doConference] Session ${I._id} has ${ve.length} receivers`),_e||(console.warn(`[doConference] Session ${I._id} has no receivers yet. Will re-configure when track arrives.`),(Q=this.context.logger)==null||Q.warn(`[doConference] Session ${I._id} has no receivers yet. Will re-configure when track arrives.`)),d.forEach((B,Fe)=>{var X,W,G;if(console.log("[doConference] - In forEach receiverTracks for",I._id),(X=this.context.logger)==null||X.log("[doConference] - In forEach receiverTracks for",I._id),!Fe.startsWith(I._id)){if(!B||B.readyState!=="live"){console.warn(`[doConference] Skipping invalid track ${(B==null?void 0:B.id)||"unknown"} for session ${I._id}`),(W=this.context.logger)==null||W.warn(`[doConference] Skipping invalid track ${(B==null?void 0:B.id)||"unknown"} for session ${I._id}`);return}try{const re=n.createMediaStreamSource(new MediaStream([B])),pe=n.createGain(),Ie=`${I._id}-${Fe}`;re.connect(pe),pe.connect(N),pe.connect($),console.log("[doConference] - In forEach connect track for",I._id),(G=this.context.logger)==null||G.log("[doConference] - In forEach connect track for",I._id),h.sources.set(Ie,re),h.gains.set(Ie,pe)}catch(re){console.error(re)}}});const U=$.stream.getTracks();if(_[I._id]=U[0],i&&this.activeStreamValue)try{const B=this.activeStream,Fe=n.createMediaStreamSource(B),X=n.createGain(),W=`${I._id}-local`;Fe.connect(X),X.connect(N),h.sources.set(W,Fe),h.gains.set(W,X)}catch(B){console.error(B)}else i&&(console.error(`Host room but no activeStreamValue - skipping host microphone for session ${I._id}`),(k=this.context.logger)==null||k.error(`Host room but no activeStreamValue - skipping host microphone for session ${I._id}`));const q=I.connection.getSenders()[0],j=N.stream.getTracks();if(q&&j[0])try{console.log("[doConference] - Final replaceTrack for",I._id),(M=this.context.logger)==null||M.log("[doConference] - Final replaceTrack for",I._id),console.log("RIGHT 2 initial replace for ",I._id),await q.replaceTrack(j[0]),this.muteReconfigure(I)}catch(B){console.error(B)}}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&(console.log("[doConference] - Call processVAD from doConference"),(F=this.context.logger)==null||F.log("[doConference] - Call processVAD from doConference"),this.processVADForActiveStream(_))}processCallerMute(t,s){const i=this.extendedCalls[t];i&&i.connection.getReceivers().length&&(i.localMuted=s,i.connection.getReceivers().forEach(a=>{a.track.enabled=!s}),this.updateCall(i))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const s=this.extendedCalls[t];s._status===4?s.terminate({status_code:603,reason_phrase:"Decline"}):s._status!==8&&s.terminate()}handleSipResponseForRingback(t,s){var n,r,h,d,_,g;let i=null;if(this.extendedCalls[t])i=t;else{const T=Object.values(this.extendedCalls).find(S=>S.id===t||S._id===t||S.id&&S.id.includes(t)||S._id&&S._id.includes(t));T&&(i=T.id)}if(!i){(n=this.context.logger)==null||n.warn(`[handleSipResponseForRingback] Could not find session for identifier ${t}, status ${s}`);return}const a=this.extendedCalls[i];if(!a){(r=this.context.logger)==null||r.warn(`[handleSipResponseForRingback] Call not found in extendedCalls for ${i}`);return}if(a.direction==="outgoing"){if(a._is_confirmed){(h=this.context.logger)==null||h.log(`[handleSipResponseForRingback] Call ${i} is already confirmed, skipping ringback tone`);return}if(this.timeIntervals[i]||this.startCallTimer(i),s===au.TRYING||s===au.RINGING){if(this.ringbackTimers[i])return;this.ringbackSessionProgressReceived[i]=!1,this.ringbackTimers[i]=setTimeout(()=>{var S,E;const T=this.extendedCalls[i];T&&!T._is_confirmed&&!this.ringbackSessionProgressReceived[i]?(this.startLocalRingbackTone(i),(S=this.context.logger)==null||S.log(`[handleSipResponseForRingback] Started local ringback tone for call ${i} after 2 seconds without 183`)):T&&T._is_confirmed&&((E=this.context.logger)==null||E.log(`[handleSipResponseForRingback] Call ${i} was confirmed during 2-second wait, skipping ringback tone`)),delete this.ringbackTimers[i]},2e3),(d=this.context.logger)==null||d.log(`[handleSipResponseForRingback] Started 2-second timer for call ${i} after receiving ${s}`)}s===au.SESSION_PROGRESS&&(this.ringbackSessionProgressReceived[i]=!0,this.ringbackTimers[i]&&(clearTimeout(this.ringbackTimers[i]),delete this.ringbackTimers[i],(_=this.context.logger)==null||_.log(`[handleSipResponseForRingback] Cancelled ringback timer for call ${i} - 183 received`)),this.stopLocalRingbackTone(i),(g=this.context.logger)==null||g.log(`[handleSipResponseForRingback] Stopped local ringback tone for call ${i} - 183 received with SDP`))}}async startLocalRingbackTone(t){var s,i;if(!this.ringbackAudioContexts[t])try{const a=await this.managedAudioContext.getContext(),n=a.createOscillator(),r=a.createOscillator(),h=a.createGain();n.frequency.value=440,r.frequency.value=480,n.type="sine",r.type="sine",h.gain.value=0,n.connect(h),r.connect(h),h.connect(a.destination),n.start(),r.start();const d={context:a,oscillator1:n,oscillator2:r,gainNode:h,intervalId:null};this.ringbackAudioContexts[t]=d;const _=()=>{if(!this.ringbackAudioContexts[t])return;const T=a.currentTime;h.gain.cancelScheduledValues(T),h.gain.setValueAtTime(0,T),h.gain.linearRampToValueAtTime(.3,T+.05),h.gain.linearRampToValueAtTime(0,T+1)};_();const g=setInterval(()=>{if(!this.ringbackAudioContexts[t]){clearInterval(g);return}_()},4e3);d.intervalId=g,this.ringbackAudioContexts[t]=d,(s=this.context.logger)==null||s.log(`[startLocalRingbackTone] Started ringback tone for session ${t}`)}catch(a){(i=this.context.logger)==null||i.error(`[startLocalRingbackTone] Error starting ringback tone for session ${t}:`,a),console.error(`[startLocalRingbackTone] Error starting ringback tone for session ${t}:`,a)}}stopLocalRingbackTone(t){var i,a;const s=this.ringbackAudioContexts[t];if(s)try{s.intervalId&&clearInterval(s.intervalId),s.oscillator1&&s.oscillator1.stop(),s.oscillator2&&s.oscillator2.stop(),s.gainNode&&s.gainNode.disconnect(),delete this.ringbackAudioContexts[t],(i=this.context.logger)==null||i.log(`[stopLocalRingbackTone] Stopped ringback tone for session ${t}`)}catch(n){(a=this.context.logger)==null||a.error(`[stopLocalRingbackTone] Error stopping ringback tone for session ${t}:`,n),console.error(`[stopLocalRingbackTone] Error stopping ringback tone for session ${t}:`,n),delete this.ringbackAudioContexts[t]}}cleanupRingbackTone(t){this.ringbackTimers[t]&&(clearTimeout(this.ringbackTimers[t]),delete this.ringbackTimers[t]),this.stopLocalRingbackTone(t),delete this.ringbackSessionProgressReceived[t]}async playHangupBeep(){var t,s;if(!this.hangupBeepContext)try{const i=await this.managedAudioContext.getContext(),a=i.createOscillator(),n=i.createGain();a.frequency.value=800,a.type="sine",n.gain.value=0,a.connect(n),n.connect(i.destination),this.hangupBeepContext={context:i,oscillator:a,gainNode:n},a.start();const r=i.currentTime;n.gain.setValueAtTime(0,r),n.gain.linearRampToValueAtTime(.3,r+.01),n.gain.setValueAtTime(.3,r+.15),n.gain.linearRampToValueAtTime(0,r+.2),a.stop(r+.2),setTimeout(()=>{if(this.hangupBeepContext){try{this.hangupBeepContext.oscillator&&this.hangupBeepContext.oscillator.disconnect(),this.hangupBeepContext.gainNode&&this.hangupBeepContext.gainNode.disconnect()}catch(h){console.error("[playHangupBeep] Cleanup playing hangup beep error:",h)}this.hangupBeepContext=null}},250),(t=this.context.logger)==null||t.log("[playHangupBeep] Played hangup beep")}catch(i){(s=this.context.logger)==null||s.error("[playHangupBeep] Error playing hangup beep:",i),console.error("[playHangupBeep] Error playing hangup beep:",i),this.hangupBeepContext=null}}transferCall(t,s){if(s.toString().length===0)return new Error("Target must be passed");const i=this.extendedCalls[t];if(!i._is_confirmed&&!i._is_canceled){const a=`sip:${s}@${this.context.sipDomain}`;i.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:t,isTransferring:!0,isTransferred:!1}),i.refer(`sip:${s}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(i)}mergeCall(t){const s=Object.values(this.extendedCalls).filter(n=>n.roomId===t);if(s.length!==2)return;const i=s[0],a=s[1];!i||!a||(this.updateCallStatus({callId:i._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),i.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(i))}mergeCallByIds(t,s){const i=Object.values(this.extendedCalls).find(n=>n._id===t),a=Object.values(this.extendedCalls).find(n=>n._id===s);if(!i||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:s,isMerging:!0}),i.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(i)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}setCallWaiting(t){this.isCallWaitingEnabled=t,this.context.emit("changeIsCallWaiting",t)}startCallTimer(t){this.removeTimeInterval(t);const s={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(s);const i=setInterval(()=>{const a={...this.callTime[t]},n=yv(a);this.setCallTime({callId:t,...n})},1e3);this.setTimeInterval(t,i)}async setActiveRoom(t){const s=this.currentActiveRoomId;t!==s&&(this.currentActiveRoomId=t,await this.roomReconfigure(s),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var _,g;const s=t.session;if(this.getActiveCalls[s.id]!==void 0)return;const a=this.getNewRoomId(),n={started:new Date,incomingInProgress:!1,roomId:a};s.direction==="incoming"?(this.context.logger.log("New incoming call from",(g=(_=s._remote_identity)==null?void 0:_._uri)==null?void 0:g._user),n.incomingInProgress=!0,this.context.subscribe(Xt.CALL_CONFIRMED,T=>{s.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.startCallTimer(s.id))}),this.context.subscribe(Xt.CALL_FAILED,T=>{s.id===T.id&&(this.updateRoom({incomingInProgress:!1,roomId:a}),this.deleteRoomIfEmpty(a))})):s.direction==="outgoing"&&s.once("confirmed",()=>{this.startCallTimer(s.id)});const r=s,h=this.hasAutoAnswerHeaders(t),d=r.direction==="incoming"&&!this.hasActiveCalls&&(h||this.autoAnswer);r.roomId=a,r.localMuted=!1,r.autoAnswer=d,d?this.addCall(r,!1):this.addCall(r),this.addCallStatus(s.id),this.addRoom(n),d&&setTimeout(()=>{this.answerCall(r._id)},250)}removeCall(t){const s={...this.activeCalls};delete s[t],this.activeCalls={...s};const i={...this.extendedCalls};delete i[t],this.extendedCalls={...i},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){const s=this.extendedCalls[t._id];if(!s)return;this.stopVUMeter("origin"),this.stopVUMeter(t._id);const i=s.roomId;this.removeCall(t._id),this.roomReconfigure(i).then(()=>{}).catch(a=>{console.error("Error reconfiguring room after call removal:",a)})}shouldTerminateNewSession(t){if(t.session.direction==="outgoing")return!1;const i=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||i}async newRTCSessionCallback(t){const s=t.session,i=s.direction==="incoming"?t.request.getHeader("Remote-Party-ID"):null;if(s._remote_party_display_name=Lf(i),s._remote_party_uri_user=$f(i),this.shouldTerminateNewSession(t)){s.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}this.context.triggerListener({listenerType:Xt.NEW_CALL,session:s,event:t}),s.on("ended",r=>{var d,_,g;if(this.stopVUMeter(s.id),this.context.logger.log("Session ended for",(_=(d=s._remote_identity)==null?void 0:d._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:s,event:r}),s._is_confirmed&&this.playHangupBeep(),s.connection){const T=s.connection.connectionState;(T==="closed"||T==="disconnected")&&this.context.emit("connectionStateChange",{session:s,connectionState:T})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(),this.cleanupRingbackTone(s.id);const h=this.getActiveCalls[s.id];h&&this.activeCallListRemove(h),this.stopCallTimer(s.id),this.removeCallStatus(s.id),this.removeCallMetrics(s.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(T=>T.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),s.on("progress",r=>{var h,d;this.context.logger.log("Session in progress for",(d=(h=s._remote_identity)==null?void 0:h._uri)==null?void 0:d._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:s,event:r})}),s.on("failed",r=>{var d,_,g;if(this.stopVUMeter(s.id),this.context.logger.log("Session failed for",(_=(d=s._remote_identity)==null?void 0:d._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:s,event:r}),s.connection){const T=s.connection.connectionState;(T==="closed"||T==="disconnected")&&this.context.emit("connectionStateChange",{session:s,connectionState:T})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(),this.cleanupRingbackTone(s.id),s.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const h=this.getActiveCalls[s.id];h&&this.activeCallListRemove(h),this.stopCallTimer(s.id),this.removeCallStatus(s.id),this.removeCallMetrics(s.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(T=>T.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),s.on("confirmed",r=>{var h,d;this.context.logger.log("Session confirmed for",(d=(h=s._remote_identity)==null?void 0:h._uri)==null?void 0:d._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:s,event:r}),this.updateCall(s),this.cleanupRingbackTone(s.id),s.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)});const a=r=>{this.refreshRemotePartyId(s,r.request)&&this.updateCall(s)};s.on("reinvite",a),s.on("update",a);const n=r=>{r&&r.addEventListener("connectionstatechange",h=>{this.context.emit("connectionStateChange",{session:s,connectionState:r.connectionState})})};if(s.connection&&n(s.connection),s.on("peerconnection",({peerconnection:r})=>{n(r)}),await this.setupCall(t),s.direction==="outgoing"){const r=this.getActiveCalls[s.id].roomId;await this.setActiveRoom(r)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(s=>{s.audioTag&&(s.audioTag.volume=t,this.updateCall(s))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(po.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(po.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const s={...t};delete s.callId,this.callMetrics={...this.callMetrics,[t.callId]:s},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const s={...this.callMetrics};delete s[t],this.callMetrics={...s},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const s=new gS(this.metricConfig),i=s.createProbe(t.connection,{cid:t._id}),a=[];let n;i.onreport=r=>{Object.entries(r.audio).forEach(([_,g])=>{g.direction==="inbound"&&!a.includes(_)&&(a.push(_),n=_)});const h=r.audio[n];if(!h)return;const d=TS(h,vS);d.callId=t._id,this.setCallMetrics(d)},this.context.subscribe(Xt.CALL_ENDED,r=>{r._id===t._id&&s.stopAllProbes()}),s.startAllProbes()}async setupVUMeter(t,s){await this.VUMeter.start(await this.managedAudioContext.getContext(),t,s)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){try{const t=Date.now(),s=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((a,n)=>{a.stop()}),this.initialStreamValue=null),this.initialStreamValue=s}catch(t){throw t}}async triggerAddStream(t,s){var S,E;console.log(`[triggerAddStream] - For ${s._id}`),(S=this.context.logger)==null||S.log(`[triggerAddStream] - For ${s._id}`);const i=this.muteWhenJoin||this.isMuted;this.setIsMuted(i),this.initialStreamValue||await this.setupStream();const a=await this.managedAudioContext.getContext(),n=await lu(a,this.initialStreamValue,this.microphoneInputLevel*2),r=this.isMuted||this.muteWhenJoin;n.getTracks().forEach(C=>{C.enabled=!r}),await this.setActiveStream(n),await s.connection.getSenders()[0].replaceTrack(n.getTracks()[0]);const _=new MediaStream([t.track]);!Object.values(this.extendedCalls).find(C=>C.audioTag&&C.audioTag.id===s._id)&&lv(_,s,this.selectedOutputDevice,this.speakerVolume);const T=s.roomId===this.currentActiveRoomId;s.audioTag&&(s.audioTag.muted=!T),await this.setupVUMeter(_,s._id),this.getCallQuality(s),this.updateCall(s),s.roomId!==void 0&&Object.values(this.extendedCalls).filter(A=>A.roomId===s.roomId).length>1&&(console.log(`[triggerAddStream] Re-configuring conference for room ${s.roomId} - track received for call ${s._id}`),(E=this.context.logger)==null||E.log(`[triggerAddStream] Re-configuring conference for room ${s.roomId} - track received for call ${s._id}`),setTimeout(()=>{this.roomReconfigure(s.roomId)},100)),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVADForActiveStream()}initCall(t,s,i=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const a=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=a.id,s&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:a.id,roomId:this.currentActiveRoomId}),i)){const n=Object.values(this.extendedCalls).filter(r=>r.roomId===this.currentActiveRoomId&&r._id!==a.id);for(const r of n)this.holdCall(r._id,!0)}a.connection.addEventListener("track",n=>{this.triggerAddStream(n,a)})}async processRoomChange({callId:t,roomId:s}){const i=this.extendedCalls[t];if(!i)return;const a=i.roomId;i.roomId=s,this.updateCall(i),await this.roomReconfigure(a),await this.roomReconfigure(s)}}class RS{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,s){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,s,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}const Pe={CREATE:"m.conversation.create",MESSAGE:"m.conversation.message",MEMBER:"m.conversation.member",CLOSED:"m.conversation.closed",SYNC:"m.sync",UPLOAD_REQUEST:"m.upload.request",UPLOAD_RESPONSE:"m.upload.response",FILE_ACCESS_REQUEST:"m.file.access.request",FILE_ACCESS_RESPONSE:"m.file.access.response",REACTION:"m.reaction",TYPING:"m.typing",SENT:"m.sent",DELIVERED:"m.delivered",READ:"m.read",FAILED:"m.failed",SENDING:"m.sending"},Kf="m.conversation.member",IS="m.conversation.create",mo="m.conversation.closed";function Yf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,c=>{const t=Math.random()*16|0;return(c==="x"?t:t&3|8).toString(16)})}function Jf(c="req"){return`${c}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Bd(c){return c&&(Array.isArray(c.attachments)||(c.attachments=[]),c)}function zf(c){return c&&(c.content&&Bd(c.content),c)}function bS(c){return c??{}}function wS(c){var t;return c?(Bd(c),!!(c.content||(t=c.attachments)!=null&&t.length)):!1}function OS(c){return c?c.startsWith("image/")?"image":c.startsWith("video/")?"video":c.startsWith("audio/")?"audio":"file":"file"}class DS{constructor(t){this.msrpSession=null,this.extendedSession=null,this.conversationsMap=new Map,this.pendingUploads=new Map,this.pendingFileAccessRequests=new Map,this.uploadRequestTimeoutMs=3e4,this.fileAccessTimeoutMs=3e4,this.typingKeepAliveInterval=null,this.typingKeepAliveConversationKey=null,this.typingKeepAliveIntervalMs=2e3,this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getMsrpSession(){return this.msrpSession}get hasActiveSession(){return this.extendedSession!==null}get conversations(){const t={};return this.conversationsMap.forEach((s,i)=>{t[i]=s}),t}msrpAnswer(t){this.extendedSession&&this.updateMSRPSession(this.extendedSession)}updateMSRPSession(t){this.msrpSession=Pf(t),this.context.emit("changeMsrpSession",this.msrpSession)}setMSRPSession(t){this.msrpSession=Pf(t),this.extendedSession=t,this.context.emit("changeMsrpSession",this.msrpSession)}addMSRPMessage(t,s){this.context.emit("newMSRPMessage",{message:t,session:s})}messageTerminate(t){this.extendedSession&&this.extendedSession._status!==8&&this.extendedSession.terminate()}addMessageSession(t){var s;t._id&&((s=this.extendedSession)==null?void 0:s._id)!==t._id&&this.setMSRPSession(t)}triggerMSRPListener({listenerType:t,session:s,event:i}){const a=this.context.listenersList[t];!a||!a.length||a.forEach(n=>{n(s,i)})}clearMSRPSession(){this.msrpSession=null,this.extendedSession=null,this.context.emit("changeMsrpSession",this.msrpSession)}newMSRPSessionCallback(t){t.session._id||(t.session._id=t.request.call_id+t.request.from._parameters.tag);const s=t.session;s.on("ended",i=>{var a;this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:s,event:i}),((a=this.extendedSession)==null?void 0:a._id)===s._id&&this.clearMSRPSession()}),s.on("failed",i=>{var a;this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:s,event:i}),((a=this.extendedSession)==null?void 0:a._id)===s._id&&this.clearMSRPSession()}),s.on("confirmed",i=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:s,event:i}),this.updateMSRPSession(s)}),s.on("newMessage",i=>{this.addMSRPMessage(i,s),this.processIncomingMSRPMessage(i)}),this.addMessageSession(s)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}getUserUri(){var t;return(t=this.context.configuration)!=null&&t.uri?typeof this.context.configuration.uri=="string"?this.context.configuration.uri:this.context.configuration.uri.toString():""}initMSRP(t={}){const s=this.extractSipUser(this.getUserUri());if(!s)return console.error("Cannot init MSRP: current user SIP identity not available");const i=this.context.startMSRP(s,t);i.on("active",()=>{this.addMessageSession(i),i.sendMSRP(""),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}initMSRPAndSendMessage(t,s,i={}){if(t.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(t,i);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(s),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,s){if(!this.extendedSession)throw new Error("No active MSRP session");this.extendedSession.sendMSRP(s)}safeSendMSRP(t){if(!this.msrpSession||!this.extendedSession)return console.warn("safeSendMSRP: no active MSRP session - message dropped",t),!1;try{return this.extendedSession.sendMSRP(t),!0}catch(s){return console.error("safeSendMSRP error:",s),this.clearMSRPSession(),!1}}buildCreateConversationEvent(t){return{type:Pe.CREATE,sender:this.getUserUri(),origin_server_ts:Date.now(),content:{creator:this.getUserUri(),invitee:t}}}buildTextMessageEvent(t,s){return{type:Pe.MESSAGE,conversationKey:t,sender:this.getUserUri(),origin_server_ts:Date.now(),content:{message_type:"text",content:s,txn_id:Yf()}}}buildMediaMessageEvent(t,s,i=""){const a=s.media_type||OS(s.mime_type),n={kind:a,mime_type:s.mime_type,filename:s.filename};return s.preview_url&&(n.preview_url=s.preview_url),s.icon_url&&(n.icon_url=s.icon_url),s.transcription&&(n.transcription=s.transcription),{type:Pe.MESSAGE,conversationKey:t,sender:this.getUserUri(),origin_server_ts:Date.now(),content:{message_type:a,content:i||s.filename||"",attachments:[n],txn_id:Yf()}}}buildMemberEvent(t,s,i,a){const n={type:Pe.MEMBER,conversationKey:t,sender:this.getUserUri(),state_key:s,origin_server_ts:Date.now(),content:{membership:i}};return a&&(n.content.role=a),n}buildCloseConversationEvent(t,s="Conversation resolved",i="resolved"){const a=Date.now();return{type:Pe.CLOSED,conversationKey:t,sender:this.getUserUri(),origin_server_ts:a,content:{reason:s,cause:i,closed_by:this.getUserUri(),closed_at:a}}}buildReactionEvent(t,s,i){return{type:Pe.REACTION,conversationKey:t,sender:this.getUserUri(),origin_server_ts:Date.now(),content:{relates_to:{event_id:s,key:i}}}}buildTypingEvent(t,s){return{type:Pe.TYPING,conversationKey:t,sender:this.getUserUri(),origin_server_ts:Date.now(),content:{typing:s}}}buildReadReceiptEvent(t,s){return{type:Pe.READ,event_id:s,conversationKey:t,sender:this.getUserUri(),origin_server_ts:Date.now(),content:{ts:Date.now(),up_to:!0}}}sendCreateConversationMessage(t){if(!this.extendedSession)return console.warn("No MSRP session available for creating conversation"),!1;const i=(Array.isArray(t)?t:[t]).map(a=>(a??"").trim()).filter(a=>a.length>0).map(a=>a.startsWith("sip:")?a:`sip:${a}@${this.context.sipDomain}`);return i.length===0?(console.log("Room creation cancelled - invitee required"),!1):this.safeSendMSRP(JSON.stringify(this.buildCreateConversationEvent(i)))}sendTextMessage(t,s){const i=(s??"").trim();return!t||!i?!1:this.safeSendMSRP(JSON.stringify(this.buildTextMessageEvent(t,i)))}sendMediaMessage(t,s,i=""){return!t||!s?!1:this.safeSendMSRP(JSON.stringify(this.buildMediaMessageEvent(t,s,i)))}sendReaction(t,s,i){return!t||!s||!i?!1:this.safeSendMSRP(JSON.stringify(this.buildReactionEvent(t,s,i)))}sendTypingIndicator(t,s){return t?this.safeSendMSRP(JSON.stringify(this.buildTypingEvent(t,s))):!1}startTypingKeepAlive(t){t&&(this.stopTypingKeepAlive(!1),this.typingKeepAliveConversationKey=t,this.sendTypingIndicator(t,!0),this.typingKeepAliveInterval=setInterval(()=>{this.typingKeepAliveConversationKey&&this.hasActiveSession?this.sendTypingIndicator(this.typingKeepAliveConversationKey,!0):this.stopTypingKeepAlive(!0)},this.typingKeepAliveIntervalMs))}stopTypingKeepAlive(t=!0){this.typingKeepAliveInterval&&(clearInterval(this.typingKeepAliveInterval),this.typingKeepAliveInterval=null);const s=this.typingKeepAliveConversationKey;this.typingKeepAliveConversationKey=null,t&&s&&this.sendTypingIndicator(s,!1)}sendReadReceipt(t,s){return!t||!s||!this.hasActiveSession?!1:this.safeSendMSRP(JSON.stringify(this.buildReadReceiptEvent(t,s)))}closeConversation(t,s="Conversation resolved",i="resolved"){const a=this.conversationsMap.get(t);if(!a||this.isConversationClosed(a))return!1;const n=a.currentUserRole||"assigned";return n!=="in_charge"&&n!=="manager"?!1:this.safeSendMSRP(JSON.stringify(this.buildCloseConversationEvent(t,s,i)))}changeMemberRole(t,s,i){const a=this.conversationsMap.get(t),n=(a==null?void 0:a.currentUserRole)||"assigned";return n!=="in_charge"&&n!=="manager"?(console.warn("Not authorized to change roles (role:",n,")"),!1):this.safeSendMSRP(JSON.stringify(this.buildMemberEvent(t,s,"join",i)))}acceptInvite(t){return this.safeSendMSRP(JSON.stringify(this.buildMemberEvent(t,this.getUserUri(),"join")))}rejectInvite(t){const s=this.safeSendMSRP(JSON.stringify(this.buildMemberEvent(t,this.getUserUri(),"leave")));return s&&this.conversationsMap.delete(t)&&this.context.emit("msrpConversationRemoved",{conversationKey:t}),s}leaveConversation(t){const s=this.safeSendMSRP(JSON.stringify(this.buildMemberEvent(t,this.getUserUri(),"leave")));return s&&this.conversationsMap.delete(t)&&this.context.emit("msrpConversationRemoved",{conversationKey:t}),s}requestUploadUrl(t,s,i,a){return new Promise((n,r)=>{if(!this.hasActiveSession){r(new Error("No MSRP session available"));return}const h=Jf("upload"),d={type:Pe.UPLOAD_REQUEST,conversationKey:t,sender:this.getUserUri(),origin_server_ts:Date.now(),content:{request_id:h,filename:s,mime_type:i,file_size:a}};this.pendingUploads.set(h,{resolve:n,reject:r}),setTimeout(()=>{this.pendingUploads.has(h)&&(this.pendingUploads.delete(h),r(new Error("Upload request timeout")))},this.uploadRequestTimeoutMs),this.safeSendMSRP(JSON.stringify(d))||(this.pendingUploads.delete(h),r(new Error("Failed to send upload request")))})}requestFileAccess(t,s){return new Promise((i,a)=>{if(!this.hasActiveSession){a(new Error("No MSRP session available"));return}const n=Jf("file-access-req"),r={type:Pe.FILE_ACCESS_REQUEST,event_id:n,conversationKey:t,sender:this.getUserUri(),content:{request_id:n,event_id:s}};this.pendingFileAccessRequests.set(n,{resolve:i,reject:a}),setTimeout(()=>{this.pendingFileAccessRequests.has(n)&&(this.pendingFileAccessRequests.delete(n),a(new Error("File access request timed out")))},this.fileAccessTimeoutMs),this.safeSendMSRP(JSON.stringify(r))||(this.pendingFileAccessRequests.delete(n),a(new Error("Failed to send file access request")))})}async uploadFile(t,s,i=""){if(!t)throw new Error("conversationKey is required");if(!s)throw new Error("file is required");const a=await this.requestUploadUrl(t,s.name,s.type||"application/octet-stream",s.size),n=new FormData;n.append("file",s);const r=await fetch(a.upload_url,{method:"POST",body:n});if(!r.ok){const d=await r.json().catch(()=>({}));throw new Error((d==null?void 0:d.error)||`Upload failed: HTTP ${r.status}`)}const h=await r.json();return this.sendMediaMessage(t,h,i),h}processIncomingMSRPMessage(t){if(!t||t.direction==="outgoing")return;let s;try{s=JSON.parse(t.body)}catch{console.warn("Received non-JSON MSRP message",t.body);return}this.handleIncomingEvent(s)}handleIncomingEvent(t){const s=zf(t);if(!(!s||!s.type))switch(s.type){case Pe.SYNC:this.handleIncomingSync(s);break;case Pe.CREATE:this.handleIncomingConversationCreate(s);break;case Pe.MESSAGE:this.handleIncomingConversationMessage(s);break;case Pe.MEMBER:this.handleIncomingConversationMember(s);break;case Pe.CLOSED:this.handleIncomingConversationClosed(s);break;case Pe.REACTION:this.handleIncomingReaction(s);break;case Pe.TYPING:this.handleIncomingTyping(s);break;case Pe.SENT:case Pe.SENDING:case Pe.DELIVERED:case Pe.READ:case Pe.FAILED:this.handleIncomingReceipt(s);break;case Pe.UPLOAD_RESPONSE:this.handleIncomingUploadResponse(s);break;case Pe.FILE_ACCESS_RESPONSE:this.handleIncomingFileAccessResponse(s);break;default:console.warn("Unhandled MSRP event:",s.type,s)}}handleIncomingSync(t){if(!t.content)return;const s=t.content.conversations??[],i=this.getUserUri(),a=this.extractSipUser(i),n={};s.forEach(r=>{const h=this.conversationKeyOf(r);if(!h)return;const{creator:d,timeline:_,created_at:g,updated_at:T}=r,S=bS(r.state_events),E=new Set,C=new Map;let A=null,R="assigned";S[Kf]&&Object.entries(S[Kf]).forEach(([I,ie])=>{var _e,U;const N=(_e=ie.content)==null?void 0:_e.membership,$=((U=ie.content)==null?void 0:U.role)||"assigned";this.extractSipUser(I)===a&&(A=N??null,N==="join"&&(R=$)),N==="join"&&(E.add(I),C.set(I,$))});const F=(_||[]).filter(I=>I.type===Pe.MESSAGE).map(I=>zf({...I}));F.length>0&&(n[h]=F),this.upsertConversationState(h,{conversationKey:h,creator:d??null,members:E,memberRoles:C,currentUserRole:R,currentUserStatus:A,state_events:S,created_at:g||Date.now(),updated_at:T||Date.now(),status:r.status})}),this.context.emit("msrpSyncCompleted",{conversations:this.snapshotConversationsMap(),messagesByConversation:n})}handleIncomingConversationCreate(t){var a;const s=this.conversationKeyOf(t);if(!s||this.conversationsMap.has(s))return;const i=this.getUserUri();this.upsertConversationState(s,{conversationKey:s,creator:((a=t.content)==null?void 0:a.creator)||t.sender||null,members:new Set([i]),memberRoles:new Map([[i,"in_charge"]]),currentUserRole:"in_charge",state_events:{[IS]:{"":t}},created_at:t.origin_server_ts||Date.now(),updated_at:t.origin_server_ts||Date.now(),currentUserStatus:"join"}),this.context.emit("msrpConversationCreated",{conversationKey:s,conversation:this.snapshotConversation(this.conversationsMap.get(s))})}handleIncomingConversationMessage(t){const s=this.conversationKeyOf(t);if(!s||!wS(t.content))return;const i=this.conversationsMap.get(s);i&&(i.updated_at=t.origin_server_ts||Date.now(),this.context.emit("msrpMessageAdded",{conversationKey:s,message:t}))}handleIncomingConversationClosed(t){const s=this.conversationKeyOf(t);if(!s)return;const i=this.conversationsMap.get(s);i&&(i.state_events||(i.state_events={}),i.state_events[mo]=i.state_events[mo]||{},i.state_events[mo][""]=t,i.status="closed",i.updated_at=t.origin_server_ts||Date.now(),this.context.emit("msrpConversationUpdated",{conversationKey:s,patch:{status:i.status,state_events:{...i.state_events},updated_at:i.updated_at}}))}handleIncomingReceipt(t){const s=this.conversationKeyOf(t),i=t.event_id;if(!s||!i)return;const n={[Pe.SENDING]:"pending",[Pe.SENT]:"sent",[Pe.DELIVERED]:"delivered",[Pe.READ]:"read",[Pe.FAILED]:"failed"}[t.type];if(!n)return;const r=t.origin_server_ts||Date.now(),h=this.conversationsMap.get(s);h&&(h.updated_at=r),this.context.emit("msrpReceiptChanged",{conversationKey:s,eventId:i,status:n,updatedAt:r})}handleIncomingTyping(t){var i;const s=this.conversationKeyOf(t);s&&t.sender!==this.getUserUri()&&this.context.emit("msrpTyping",{conversationKey:s,sender:t.sender,isTyping:!!((i=t.content)!=null&&i.typing)})}handleIncomingReaction(t){var d,_;const s=this.conversationKeyOf(t),i=(d=t.content)==null?void 0:d.relates_to,a=(i==null?void 0:i.key)||(i==null?void 0:i.emoji);if(!s||!(i!=null&&i.event_id)||!a)return;const n=((_=t.content)==null?void 0:_.action)==="remove"?"remove":"add",r=t.origin_server_ts||Date.now(),h=this.conversationsMap.get(s);h&&(h.updated_at=r),this.context.emit("msrpReactionChanged",{conversationKey:s,eventId:i.event_id,emoji:a,action:n,sender:t.sender,updatedAt:r})}handleIncomingConversationMember(t){const s=this.conversationKeyOf(t);if(!s)return;const{state_key:i,content:a}=t,n=a==null?void 0:a.membership,r=(a==null?void 0:a.role)||"assigned",h=this.conversationsMap.has(s);let d=this.conversationsMap.get(s);d||(d={conversationKey:s,creator:null,members:new Set,memberRoles:new Map,currentUserRole:"assigned",state_events:{},created_at:t.origin_server_ts||Date.now(),updated_at:t.origin_server_ts||Date.now(),currentUserStatus:null},this.conversationsMap.set(s,d));const _=this.getUserUri(),g=this.extractSipUser(i),T=this.extractSipUser(_),S=i===_||!!g&&!!T&&g===T;let E=!1;if(n==="join")d.members.add(i),d.memberRoles.set(i,r),S&&(d.currentUserStatus="join",d.currentUserRole=r);else if(n==="leave"||n==="ban")d.members.delete(i),d.memberRoles.delete(i),S&&(d.currentUserStatus="leave",this.conversationsMap.delete(s),E=!0);else if(n==="invite"){if(!S)return;d.currentUserStatus="invite",d.memberRoles.set(i,r)}if(d.updated_at=t.origin_server_ts||Date.now(),E){this.context.emit("msrpConversationRemoved",{conversationKey:s});return}if(!h){this.context.emit("msrpConversationCreated",{conversationKey:s,conversation:this.snapshotConversation(d)});return}this.context.emit("msrpConversationUpdated",{conversationKey:s,patch:{members:new Set(d.members),memberRoles:new Map(d.memberRoles),currentUserRole:d.currentUserRole,currentUserStatus:d.currentUserStatus,updated_at:d.updated_at}})}handleIncomingUploadResponse(t){const s=t.content||{},i=s.request_id,a=this.pendingUploads.get(i);a&&(this.pendingUploads.delete(i),s.error?a.reject(new Error(s.error)):a.resolve({upload_url:s.upload_url,expires_in:s.expires_in,mime_type:s.mime_type,request_id:s.request_id,filename:s.filename,preview_url:s.preview_url,icon_url:s.icon_url,transcription:s.transcription,media_type:s.media_type}))}handleIncomingFileAccessResponse(t){const s=t.content||{},i=s.request_id,a=this.pendingFileAccessRequests.get(i);a&&(this.pendingFileAccessRequests.delete(i),s.error?a.reject(s.error):s.download_url?a.resolve(s.download_url):a.reject(new Error("No download URL in response")))}upsertConversationState(t,s){this.conversationsMap.set(t,{...s,conversationKey:t})}snapshotConversation(t){return{...t,members:new Set(t.members),memberRoles:new Map(t.memberRoles),state_events:{...t.state_events}}}snapshotConversationsMap(){const t={};return this.conversationsMap.forEach((s,i)=>{t[i]=this.snapshotConversation(s)}),t}isConversationClosed(t){var s,i;return!!((i=(s=t==null?void 0:t.state_events)==null?void 0:s[mo])!=null&&i[""])}conversationKeyOf(t){return t?typeof t=="string"?t:t.conversationKey??null:null}extractSipUser(t){if(!t)return null;const i=(typeof t=="string"?t:String(t)).match(/^sip:([^@]+)@/);return i?i[1]:null}extractDisplayName(t){if(!t)return"Unknown";const s=typeof t=="string"?t:String(t);if(s.startsWith("sip:")){const i=s.match(/^sip:([^@]+)@/);return i?i[1]:s}return s.startsWith("whatsapp:")?s.slice(9):s.startsWith("wa:")?s.slice(3):s.startsWith("greenapi:")?s.slice(9):s.startsWith("sms:")?s.slice(4):s}}const go={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Gd{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class Wd extends Gd{constructor(t,s){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=s}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const s=Me.cloneArray(t.extraHeaders),i={from_tag:this.session._from_tag};t.fromUserName&&(i.from_uri=new In("sip",t.fromUserName,this.session._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(i.from_display_name=t.fromDisplayName),s.push(`Contact: ${this.session._contact}`),s.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&s.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Ct.InitialOutgoingInviteRequest(this.session.target,this.session._ua,i,s),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let t;this._connection.onicecandidate=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(s=>{this._connection.addTrack(s)})}async _sendInitialRequest(){const t=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:n=>{this._request=n},onReceiveResponse:n=>{this._receiveInviteResponse(n)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const s={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(s),await this._connection.setLocalDescription(this.jsep_offer);const i={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},a=JSON.stringify(i);this._request.body=a,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const s=JSON.parse(t.body);this.handleId=s.data.id;const i={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},a=[this.session.getPTypeHeader(kt.PUBLISHER)];this.session.sendRequest(H.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async n=>{var r,h,d,_;if(n.status_code===200){if(this._subscribeSent=!0,n.body)try{const g=JSON.parse(n.body)||{};((h=(r=g.plugindata)==null?void 0:r.data)==null?void 0:h.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(_=(d=g.plugindata)==null?void 0:d.data)!=null&&_.publishers&&this.session.receivePublishers(g)}catch(g){console.error(g)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const s=this._candidates.map(r=>({janus:"trickle",candidate:r,handle_id:this.handleId,session_id:this.session.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...s]},n=["Content-Type: application/json",this.session.getPTypeHeader(kt.ICE)];this.session.sendRequest(H.INFO,{extraHeaders:n,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async r=>{this._configureSent=!0;const d=r.data.split(`\r
|
|
159
|
+
`),_=d[d.length-1],g=JSON.parse(_);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},s=[this.session.getPTypeHeader(kt.DETACH)];this.session.sendRequest(H.INFO,{extraHeaders:s,body:JSON.stringify(t)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const t=this._connection.getSenders();t.forEach(s=>{const i=s.track;i&&i.stop()}),t.forEach(s=>{this._connection.removeTrack(s)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Kd extends Gd{constructor(t,s,i={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=i.immediate||!1,this.type=s}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const s=await this.start(t);return this.running=!0,s}return t}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class NS extends ZT{constructor(t,s){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const i={...t.configuration,sockets:t.socketInterfaces.map(a=>new Ev.WebSocketInterface(a))};super(i),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.waitingForSessionHangup=!1,this.waitingForSessionTimeout=null,this.reconnectionAttemptsLimit=1/0,this.reconnectionAttemptsCounter=0,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,t.configuration.reconnectionAttemptsLimit&&(this.reconnectionAttemptsLimit=t.configuration.reconnectionAttemptsLimit),s&&ov(s)&&(this.logger=s)}isWaitingForSessionHangup(){return this.waitingForSessionHangup}stopSessionAfterWaiting(){this.setInitialized(!1),this.waitingForSessionHangup=!1,clearTimeout(this.waitingForSessionTimeout),this.waitingForSessionTimeout=null,this.activeConnection&&this.reconnect()}get hasActiveSessions(){return this.modules.includes(go.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(t,s){return super.on(t,s)}off(t,s){return super.off(t,s)}emit(t,s){return super.emit(t,s)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(s=>s.name===t.name)||this.processStreamPlugins.find(s=>s.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Wd)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Kd)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(s=>s.name===t)||this.processStreamPlugins.find(s=>s.name===t)}reconnect(){if(this.reconnectionAttemptsCounter<this.reconnectionAttemptsLimit){const s=5e3*Math.pow(2,this.reconnectionAttemptsCounter);this.reconnectionAttemptsCounter++,setTimeout(this.start.bind(this),s)}else this.emit("reconnectionAttemptsLimitReached",void 0)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(go.AUDIO)&&(this.audio=new AS(this)),this.modules.includes(go.MSRP)&&(this.msrp=new DS(this)),this.modules.includes(go.VIDEO)&&(this.video=new RS(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0,this.waitingForSessionHangup=!1,this.reconnectionAttemptsCounter=0}),this.on(this.disconnectedEventName,()=>{this.setConnected(!1),!this.isReconnecting&&(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.hasActiveSessions?(this.waitingForSessionHangup=!0,this.stop(!1),this.waitingForSessionTimeout=setTimeout(()=>{this.terminateAllSessions(),this.setInitialized(!1),this.waitingForSessionHangup=!1,this.activeConnection&&this.reconnect()},12e5)):(this.stop(),this.setInitialized(!1),this.activeConnection&&this.reconnect()))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(t,s){const a=!this.listenersList[t]||!this.listenersList[t].length?[s]:[...this.listenersList[t],s];this.listenersList={...this.listenersList,[t]:a}}removeIListener(t){const s={...this.listenersList};delete s[t],this.listenersList={...s}}triggerListener({listenerType:t,session:s,event:i}){const a=this.listenersList[t];!a||!a.length||a.forEach(n=>{n(s,i)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}setReconnecting(t){this.isReconnecting=t,this.emit("reconnecting",t)}}exports.BaseNewStreamPlugin=Wd;exports.BaseProcessStreamPlugin=Kd;exports.default=NS;
|