opensips-js 0.1.33 → 0.1.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,22 @@
1
- var OpensipsJS=function(Wt){"use strict";var Zv=Object.defineProperty;var eS=(Wt,cs,Me)=>cs in Wt?Zv(Wt,cs,{enumerable:!0,configurable:!0,writable:!0,value:Me}):Wt[cs]=Me;var es=(Wt,cs,Me)=>(eS(Wt,typeof cs!="symbol"?cs+"":cs,Me),Me);var cs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Me(c){return c&&c.__esModule&&Object.prototype.hasOwnProperty.call(c,"default")?c.default:c}const Tl={name:"jssip",title:"JsSIP",description:"the Javascript SIP library",version:"3.10.0",homepage:"https://jssip.net",contributors:["José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)","Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)"],types:"lib/JsSIP.d.ts",main:"lib-es5/JsSIP.js",keywords:["sip","websocket","webrtc","node","browser","library"],license:"MIT",repository:{type:"git",url:"https://github.com/versatica/JsSIP.git"},bugs:{url:"https://github.com/versatica/JsSIP/issues"},dependencies:{"@types/events":"^3.0.0","@types/debug":"^4.1.7",debug:"^4.3.1",events:"^3.3.0","sdp-transform":"^2.14.1"},devDependencies:{"@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"},scripts:{lint:"node npm-scripts.js lint",test:"node npm-scripts.js test",prepublish:"node npm-scripts.js prepublish",release:"node npm-scripts.js release"}};var Yu=Tl,nt={USER_AGENT:"".concat(Yu.title," ").concat(Yu.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 vl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?vl=function(n){return typeof n}:vl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},vl(c)}function Sl(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function El(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&&Er(c,t)}function yl(c){var t=Ju();return function(){var o=yr(c),a;if(t){var s=yr(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return Fd(this,a)}}function Fd(c,t){return t&&(vl(t)==="object"||typeof t=="function")?t:Vd(c)}function Vd(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function On(c){var t=typeof Map=="function"?new Map:void 0;return On=function(o){if(o===null||!jd(o))return o;if(typeof o!="function")throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(o))return t.get(o);t.set(o,a)}function a(){return Cl(o,arguments,yr(this).constructor)}return a.prototype=Object.create(o.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),Er(a,o)},On(c)}function Cl(c,t,n){return Ju()?Cl=Reflect.construct:Cl=function(a,s,r){var _=[null];_.push.apply(_,s);var d=Function.bind.apply(a,_),h=new d;return r&&Er(h,r.prototype),h},Cl.apply(null,arguments)}function Ju(){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 jd(c){return Function.toString.call(c).indexOf("[native code]")!==-1}function Er(c,t){return Er=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Er(c,t)}function yr(c){return yr=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},yr(c)}var qd=function(c){El(n,c);var t=yl(n);function n(o,a){var s;return Sl(this,n),s=t.call(this),s.code=1,s.name="CONFIGURATION_ERROR",s.parameter=o,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}(On(Error)),Bd=function(c){El(n,c);var t=yl(n);function n(o){var a;return Sl(this,n),a=t.call(this),a.code=2,a.name="INVALID_STATE_ERROR",a.status=o,a.message="Invalid status: ".concat(o),a}return n}(On(Error)),Gd=function(c){El(n,c);var t=yl(n);function n(o){var a;return Sl(this,n),a=t.call(this),a.code=3,a.name="NOT_SUPPORTED_ERROR",a.message=o,a}return n}(On(Error)),Wd=function(c){El(n,c);var t=yl(n);function n(o){var a;return Sl(this,n),a=t.call(this),a.code=4,a.name="NOT_READY_ERROR",a.message=o,a}return n}(On(Error)),bs={ConfigurationError:qd,InvalidStateError:Bd,NotSupportedError:Gd,NotReadyError:Wd},Ze={},Qo,zu;function Zo(){if(zu)return Qo;zu=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 _=0;_<r.length;_++){var d=r[_];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(s,d.key,d)}}function n(s,r,_){return r&&t(s.prototype,r),_&&t(s,_),s}var o=Is(),a=ts();return Qo=function(){n(s,null,[{key:"parse",value:function(_){if(_=a.parse(_,"Name_Addr_Header"),_!==-1)return _}}]);function s(r,_,d){if(c(this,s),!r||!(r instanceof o))throw new TypeError('missing or invalid "uri" parameter');this._uri=r,this._parameters={},this.display_name=_;for(var h in d)Object.prototype.hasOwnProperty.call(d,h)&&this.setParam(h,d[h])}return n(s,[{key:"setParam",value:function(_,d){_&&(this._parameters[_.toLowerCase()]=typeof d>"u"||d===null?null:d.toString())}},{key:"getParam",value:function(_){if(_)return this._parameters[_.toLowerCase()]}},{key:"hasParam",value:function(_){if(_)return this._parameters.hasOwnProperty(_.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(_){if(_=_.toLowerCase(),this._parameters.hasOwnProperty(_)){var d=this._parameters[_];return delete this._parameters[_],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(_){return _.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}},{key:"toString",value:function(){var _=this._display_name?'"'.concat(this._quote(this._display_name),'" '):"";_+="<".concat(this._uri.toString(),">");for(var d in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,d)&&(_+=";".concat(d),this._parameters[d]!==null&&(_+="=".concat(this._parameters[d])));return _}},{key:"uri",get:function(){return this._uri}},{key:"display_name",get:function(){return this._display_name},set:function(_){this._display_name=_===0?"0":_}}]),s}(),Qo}var ea,Xu;function ts(){return Xu||(Xu=1,ea=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(o,a){var s={CRLF:g,DIGIT:T,ALPHA:S,HEXDIG:E,WSP:A,OCTET:R,DQUOTE:C,SP:H,HTAB:k,alphanum:re,reserved:x,unreserved:F,mark:_e,escaped:pe,LWS:P,SWS:N,HCOLON:q,TEXT_UTF8_TRIM:j,TEXT_UTF8char:K,UTF8_NONASCII:V,UTF8_CONT:z,LHEX:D,token:U,token_nodot:X,separators:je,word:Q,STAR:W,SLASH:B,EQUAL:ie,LPAREN:ve,RPAREN:Ie,RAQUOT:Pe,LAQUOT:Re,COMMA:oe,SEMI:ye,COLON:lt,LDQUOT:at,RDQUOT:Ee,comment:Ce,ctext:be,quoted_string:Oe,quoted_string_clean:ge,qdtext:he,quoted_pair:me,SIP_URI_noparams:we,SIP_URI:Ne,uri_scheme:st,uri_scheme_sips:He,uri_scheme_sip:Vt,userinfo:At,user:qn,user_unreserved:Bn,password:un,hostport:ls,host:Cs,hostname:cn,domainlabel:Gn,toplabel:Wn,IPv6reference:fn,IPv6address:Te,h16:ae,ls32:ut,IPv4address:Zt,dec_octet:$s,port:ai,uri_parameters:Kn,uri_parameter:Yn,transport_param:ui,user_param:ci,method_param:fi,ttl_param:di,maddr_param:hi,lr_param:_i,other_param:pi,pname:mi,pvalue:Hs,paramchar:Fs,param_unreserved:gi,headers:dn,header:hn,hname:Ti,hvalue:Vs,hnv_unreserved:_n,Request_Response:Do,Request_Line:vi,Request_URI:Jn,absoluteURI:zn,hier_part:Si,net_path:pn,abs_path:mn,opaque_part:js,uric:qs,uric_no_slash:Ei,path_segments:gn,segment:Bs,param:As,pchar:Gs,scheme:yi,authority:Ci,srvr:Ai,reg_name:Ri,query:Xn,SIP_Version:Qn,INVITEm:bi,ACKm:Ii,OPTIONSm:wi,BYEm:Oi,CANCELm:Di,REGISTERm:Ni,SUBSCRIBEm:xi,NOTIFYm:Ui,REFERm:Tn,Method:vn,Status_Line:ki,Status_Code:Pi,extension_code:Mi,Reason_Phrase:No,Allow_Events:Nu,Call_ID:xu,Contact:Zn,contact_param:jt,name_addr:qt,display_name:Ws,contact_params:er,c_p_q:Li,c_p_expires:os,delta_seconds:as,qvalue:ze,generic_param:Xe,gen_value:xo,Content_Disposition:Uo,disp_type:tr,disp_param:sr,handling_param:ko,Content_Encoding:Uu,Content_Length:ku,Content_Type:Po,media_type:$i,m_type:Hi,discrete_type:Fi,composite_type:Sn,extension_token:En,x_token:Vi,m_subtype:nr,m_parameter:rr,m_value:Mo,CSeq:Lo,CSeq_value:$o,Expires:Pu,Event:yn,event_type:Cn,From:ji,from_param:An,tag_param:qi,Max_Forwards:Mu,Min_Expires:Lu,Name_Addr_Header:$u,Proxy_Authenticate:Bi,challenge:ir,other_challenge:Ks,auth_param:us,digest_cln:Rn,realm:Gi,realm_value:Wi,domain:bn,URI:In,nonce:Ki,nonce_value:Yi,opaque:Ji,stale:zi,algorithm:Xi,qop_options:wn,qop_value:lr,Proxy_Require:Hu,Record_Route:or,rec_route:ar,Reason:Qi,reason_param:ur,reason_cause:Ho,Require:Fu,Route:cr,route_param:fr,Subscription_State:Fo,substate_value:dr,subexp_params:hr,event_reason_value:Vo,Subject:Vu,Supported:ju,To:Zi,to_param:el,Via:_r,via_param:Ys,via_params:pr,via_ttl:tl,via_maddr:sl,via_received:nl,via_branch:rl,response_port:il,rport:ll,sent_protocol:ol,protocol_name:al,transport:ul,sent_by:cl,via_host:fl,via_port:mr,ttl:dl,WWW_Authenticate:qu,Session_Expires:jo,s_e_expires:gr,s_e_params:Tr,s_e_refresher:qo,extension_header:Bo,header_value:Go,message_body:Bu,uuid_URI:Wo,uuid:Bt,hex4:Gt,hex8:hl,hex12:Ko,Refer_To:Gu,Replaces:Yo,call_id:vr,replaces_param:Sr,to_tag:_l,from_tag:pl,early_flag:Jo};if(a!==void 0){if(s[a]===void 0)throw new Error("Invalid rule name: "+c(a)+".")}else a="CRLF";var r=0,_=0,d=[];function h(e){r<_||(r>_&&(_=r,d=[]),d.push(e))}function g(){var e;return o.substr(r,2)===`\r
1
+ var OpensipsJS=function(Wt){"use strict";var Zv=Object.defineProperty;var eS=(Wt,cs,Me)=>cs in Wt?Zv(Wt,cs,{enumerable:!0,configurable:!0,writable:!0,value:Me}):Wt[cs]=Me;var es=(Wt,cs,Me)=>(eS(Wt,typeof cs!="symbol"?cs+"":cs,Me),Me);var cs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Me(c){return c&&c.__esModule&&Object.prototype.hasOwnProperty.call(c,"default")?c.default:c}const Tl={name:"jssip",title:"JsSIP",description:"the Javascript SIP library",version:"3.10.0",homepage:"https://jssip.net",contributors:["José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)","Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)"],types:"lib/JsSIP.d.ts",main:"lib-es5/JsSIP.js",keywords:["sip","websocket","webrtc","node","browser","library"],license:"MIT",repository:{type:"git",url:"https://github.com/versatica/JsSIP.git"},bugs:{url:"https://github.com/versatica/JsSIP/issues"},dependencies:{"@types/events":"^3.0.0","@types/debug":"^4.1.7",debug:"^4.3.1",events:"^3.3.0","sdp-transform":"^2.14.1"},devDependencies:{"@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"},scripts:{lint:"node npm-scripts.js lint",test:"node npm-scripts.js test",prepublish:"node npm-scripts.js prepublish",release:"node npm-scripts.js release"}};var Yu=Tl,nt={USER_AGENT:"".concat(Yu.title," ").concat(Yu.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 vl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?vl=function(n){return typeof n}:vl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},vl(c)}function Sl(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function El(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&&Er(c,t)}function yl(c){var t=Ju();return function(){var o=yr(c),a;if(t){var s=yr(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return Fd(this,a)}}function Fd(c,t){return t&&(vl(t)==="object"||typeof t=="function")?t:Vd(c)}function Vd(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function On(c){var t=typeof Map=="function"?new Map:void 0;return On=function(o){if(o===null||!jd(o))return o;if(typeof o!="function")throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(o))return t.get(o);t.set(o,a)}function a(){return Cl(o,arguments,yr(this).constructor)}return a.prototype=Object.create(o.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),Er(a,o)},On(c)}function Cl(c,t,n){return Ju()?Cl=Reflect.construct:Cl=function(a,s,r){var _=[null];_.push.apply(_,s);var d=Function.bind.apply(a,_),h=new d;return r&&Er(h,r.prototype),h},Cl.apply(null,arguments)}function Ju(){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 jd(c){return Function.toString.call(c).indexOf("[native code]")!==-1}function Er(c,t){return Er=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Er(c,t)}function yr(c){return yr=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},yr(c)}var qd=function(c){El(n,c);var t=yl(n);function n(o,a){var s;return Sl(this,n),s=t.call(this),s.code=1,s.name="CONFIGURATION_ERROR",s.parameter=o,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}(On(Error)),Bd=function(c){El(n,c);var t=yl(n);function n(o){var a;return Sl(this,n),a=t.call(this),a.code=2,a.name="INVALID_STATE_ERROR",a.status=o,a.message="Invalid status: ".concat(o),a}return n}(On(Error)),Gd=function(c){El(n,c);var t=yl(n);function n(o){var a;return Sl(this,n),a=t.call(this),a.code=3,a.name="NOT_SUPPORTED_ERROR",a.message=o,a}return n}(On(Error)),Wd=function(c){El(n,c);var t=yl(n);function n(o){var a;return Sl(this,n),a=t.call(this),a.code=4,a.name="NOT_READY_ERROR",a.message=o,a}return n}(On(Error)),bs={ConfigurationError:qd,InvalidStateError:Bd,NotSupportedError:Gd,NotReadyError:Wd},Ze={},Qo,zu;function Zo(){if(zu)return Qo;zu=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 _=0;_<r.length;_++){var d=r[_];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(s,d.key,d)}}function n(s,r,_){return r&&t(s.prototype,r),_&&t(s,_),s}var o=Is(),a=ts();return Qo=function(){n(s,null,[{key:"parse",value:function(_){if(_=a.parse(_,"Name_Addr_Header"),_!==-1)return _}}]);function s(r,_,d){if(c(this,s),!r||!(r instanceof o))throw new TypeError('missing or invalid "uri" parameter');this._uri=r,this._parameters={},this.display_name=_;for(var h in d)Object.prototype.hasOwnProperty.call(d,h)&&this.setParam(h,d[h])}return n(s,[{key:"setParam",value:function(_,d){_&&(this._parameters[_.toLowerCase()]=typeof d>"u"||d===null?null:d.toString())}},{key:"getParam",value:function(_){if(_)return this._parameters[_.toLowerCase()]}},{key:"hasParam",value:function(_){if(_)return this._parameters.hasOwnProperty(_.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(_){if(_=_.toLowerCase(),this._parameters.hasOwnProperty(_)){var d=this._parameters[_];return delete this._parameters[_],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(_){return _.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}},{key:"toString",value:function(){var _=this._display_name?'"'.concat(this._quote(this._display_name),'" '):"";_+="<".concat(this._uri.toString(),">");for(var d in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,d)&&(_+=";".concat(d),this._parameters[d]!==null&&(_+="=".concat(this._parameters[d])));return _}},{key:"uri",get:function(){return this._uri}},{key:"display_name",get:function(){return this._display_name},set:function(_){this._display_name=_===0?"0":_}}]),s}(),Qo}var ea,Xu;function ts(){return Xu||(Xu=1,ea=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(o,a){var s={CRLF:m,DIGIT:T,ALPHA:S,HEXDIG:E,WSP:A,OCTET:R,DQUOTE:C,SP:H,HTAB:k,alphanum:re,reserved:x,unreserved:F,mark:_e,escaped:pe,LWS:P,SWS:N,HCOLON:q,TEXT_UTF8_TRIM:j,TEXT_UTF8char:K,UTF8_NONASCII:V,UTF8_CONT:z,LHEX:D,token:U,token_nodot:X,separators:je,word:Q,STAR:W,SLASH:B,EQUAL:ie,LPAREN:ve,RPAREN:Ie,RAQUOT:Pe,LAQUOT:Re,COMMA:oe,SEMI:ye,COLON:lt,LDQUOT:at,RDQUOT:Ee,comment:Ce,ctext:be,quoted_string:Oe,quoted_string_clean:me,qdtext:he,quoted_pair:ge,SIP_URI_noparams:we,SIP_URI:Ne,uri_scheme:st,uri_scheme_sips:He,uri_scheme_sip:Vt,userinfo:At,user:qn,user_unreserved:Bn,password:un,hostport:ls,host:Cs,hostname:cn,domainlabel:Gn,toplabel:Wn,IPv6reference:fn,IPv6address:Te,h16:ae,ls32:ut,IPv4address:Zt,dec_octet:$s,port:ai,uri_parameters:Kn,uri_parameter:Yn,transport_param:ui,user_param:ci,method_param:fi,ttl_param:di,maddr_param:hi,lr_param:_i,other_param:pi,pname:gi,pvalue:Hs,paramchar:Fs,param_unreserved:mi,headers:dn,header:hn,hname:Ti,hvalue:Vs,hnv_unreserved:_n,Request_Response:Do,Request_Line:vi,Request_URI:Jn,absoluteURI:zn,hier_part:Si,net_path:pn,abs_path:gn,opaque_part:js,uric:qs,uric_no_slash:Ei,path_segments:mn,segment:Bs,param:As,pchar:Gs,scheme:yi,authority:Ci,srvr:Ai,reg_name:Ri,query:Xn,SIP_Version:Qn,INVITEm:bi,ACKm:Ii,OPTIONSm:wi,BYEm:Oi,CANCELm:Di,REGISTERm:Ni,SUBSCRIBEm:xi,NOTIFYm:Ui,REFERm:Tn,Method:vn,Status_Line:ki,Status_Code:Pi,extension_code:Mi,Reason_Phrase:No,Allow_Events:Nu,Call_ID:xu,Contact:Zn,contact_param:jt,name_addr:qt,display_name:Ws,contact_params:er,c_p_q:Li,c_p_expires:os,delta_seconds:as,qvalue:ze,generic_param:Xe,gen_value:xo,Content_Disposition:Uo,disp_type:tr,disp_param:sr,handling_param:ko,Content_Encoding:Uu,Content_Length:ku,Content_Type:Po,media_type:$i,m_type:Hi,discrete_type:Fi,composite_type:Sn,extension_token:En,x_token:Vi,m_subtype:nr,m_parameter:rr,m_value:Mo,CSeq:Lo,CSeq_value:$o,Expires:Pu,Event:yn,event_type:Cn,From:ji,from_param:An,tag_param:qi,Max_Forwards:Mu,Min_Expires:Lu,Name_Addr_Header:$u,Proxy_Authenticate:Bi,challenge:ir,other_challenge:Ks,auth_param:us,digest_cln:Rn,realm:Gi,realm_value:Wi,domain:bn,URI:In,nonce:Ki,nonce_value:Yi,opaque:Ji,stale:zi,algorithm:Xi,qop_options:wn,qop_value:lr,Proxy_Require:Hu,Record_Route:or,rec_route:ar,Reason:Qi,reason_param:ur,reason_cause:Ho,Require:Fu,Route:cr,route_param:fr,Subscription_State:Fo,substate_value:dr,subexp_params:hr,event_reason_value:Vo,Subject:Vu,Supported:ju,To:Zi,to_param:el,Via:_r,via_param:Ys,via_params:pr,via_ttl:tl,via_maddr:sl,via_received:nl,via_branch:rl,response_port:il,rport:ll,sent_protocol:ol,protocol_name:al,transport:ul,sent_by:cl,via_host:fl,via_port:gr,ttl:dl,WWW_Authenticate:qu,Session_Expires:jo,s_e_expires:mr,s_e_params:Tr,s_e_refresher:qo,extension_header:Bo,header_value:Go,message_body:Bu,uuid_URI:Wo,uuid:Bt,hex4:Gt,hex8:hl,hex12:Ko,Refer_To:Gu,Replaces:Yo,call_id:vr,replaces_param:Sr,to_tag:_l,from_tag:pl,early_flag:Jo};if(a!==void 0){if(s[a]===void 0)throw new Error("Invalid rule name: "+c(a)+".")}else a="CRLF";var r=0,_=0,d=[];function h(e){r<_||(r>_&&(_=r,d=[]),d.push(e))}function m(){var e;return o.substr(r,2)===`\r
2
2
  `?(e=`\r
3
- `,r+=2):(e=null,h('"\\r\\n"')),e}function T(){var e;return/^[0-9]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[0-9]")),e}function S(){var e;return/^[a-zA-Z]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[a-zA-Z]")),e}function E(){var e;return/^[0-9a-fA-F]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[0-9a-fA-F]")),e}function A(){var e;return e=H(),e===null&&(e=k()),e}function R(){var e;return/^[\0-\xFF]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\0-\\xFF]")),e}function C(){var e;return/^["]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h('["]')),e}function H(){var e;return o.charCodeAt(r)===32?(e=" ",r++):(e=null,h('" "')),e}function k(){var e;return o.charCodeAt(r)===9?(e=" ",r++):(e=null,h('"\\t"')),e}function re(){var e;return/^[a-zA-Z0-9]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[a-zA-Z0-9]")),e}function x(){var e;return o.charCodeAt(r)===59?(e=";",r++):(e=null,h('";"')),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===64?(e="@",r++):(e=null,h('"@"')),e===null&&(o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","'))))))))))),e}function F(){var e;return e=re(),e===null&&(e=_e()),e}function _e(){var e;return o.charCodeAt(r)===45?(e="-",r++):(e=null,h('"-"')),e===null&&(o.charCodeAt(r)===95?(e="_",r++):(e=null,h('"_"')),e===null&&(o.charCodeAt(r)===46?(e=".",r++):(e=null,h('"."')),e===null&&(o.charCodeAt(r)===33?(e="!",r++):(e=null,h('"!"')),e===null&&(o.charCodeAt(r)===126?(e="~",r++):(e=null,h('"~"')),e===null&&(o.charCodeAt(r)===42?(e="*",r++):(e=null,h('"*"')),e===null&&(o.charCodeAt(r)===39?(e="'",r++):(e=null,h(`"'"`)),e===null&&(o.charCodeAt(r)===40?(e="(",r++):(e=null,h('"("')),e===null&&(o.charCodeAt(r)===41?(e=")",r++):(e=null,h('")"')))))))))),e}function pe(){var e,l,u,f,p;return f=r,p=r,o.charCodeAt(r)===37?(e="%",r++):(e=null,h('"%"')),e!==null?(l=E(),l!==null?(u=E(),u!==null?e=[e,l,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,l,u,f,p,m;for(f=r,p=r,m=r,e=[],l=A();l!==null;)e.push(l),l=A();if(e!==null?(l=g(),l!==null?e=[e,l]:(e=null,r=m)):(e=null,r=m),e=e!==null?e:"",e!==null){if(u=A(),u!==null)for(l=[];u!==null;)l.push(u),u=A();else l=null;l!==null?e=[e,l]:(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,l,u,f,p;for(f=r,p=r,e=[],l=H(),l===null&&(l=k());l!==null;)e.push(l),l=H(),l===null&&(l=k());return e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=N(),u!==null?e=[e,l,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,l,u,f,p,m,v;if(p=r,m=r,l=K(),l!==null)for(e=[];l!==null;)e.push(l),l=K();else e=null;if(e!==null){for(l=[],v=r,u=[],f=P();f!==null;)u.push(f),f=P();for(u!==null?(f=K(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;){for(l.push(u),v=r,u=[],f=P();f!==null;)u.push(f),f=P();u!==null?(f=K(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v)}l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){return o.substring(r,y)}(p)),e===null&&(r=p),e}function K(){var e;return/^[!-~]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[!-~]")),e===null&&(e=V()),e}function V(){var e;return/^[\x80-\uFFFF]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\x80-\\uFFFF]")),e}function z(){var e;return/^[\x80-\xBF]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\x80-\\xBF]")),e}function D(){var e;return e=T(),e===null&&(/^[a-f]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[a-f]"))),e}function U(){var e,l,u;if(u=r,l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"')))))))))))),l!==null)for(e=[];l!==null;)e.push(l),l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"'))))))))))));else e=null;return e!==null&&(e=function(f){return o.substring(r,f)}(u)),e===null&&(r=u),e}function X(){var e,l,u;if(u=r,l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"'))))))))))),l!==null)for(e=[];l!==null;)e.push(l),l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"')))))))))));else e=null;return e!==null&&(e=function(f){return o.substring(r,f)}(u)),e===null&&(r=u),e}function je(){var e;return o.charCodeAt(r)===40?(e="(",r++):(e=null,h('"("')),e===null&&(o.charCodeAt(r)===41?(e=")",r++):(e=null,h('")"')),e===null&&(o.charCodeAt(r)===60?(e="<",r++):(e=null,h('"<"')),e===null&&(o.charCodeAt(r)===62?(e=">",r++):(e=null,h('">"')),e===null&&(o.charCodeAt(r)===64?(e="@",r++):(e=null,h('"@"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","')),e===null&&(o.charCodeAt(r)===59?(e=";",r++):(e=null,h('";"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===92?(e="\\",r++):(e=null,h('"\\\\"')),e===null&&(e=C(),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e===null&&(o.charCodeAt(r)===91?(e="[",r++):(e=null,h('"["')),e===null&&(o.charCodeAt(r)===93?(e="]",r++):(e=null,h('"]"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===123?(e="{",r++):(e=null,h('"{"')),e===null&&(o.charCodeAt(r)===125?(e="}",r++):(e=null,h('"}"')),e===null&&(e=H(),e===null&&(e=k())))))))))))))))))),e}function Q(){var e,l,u;if(u=r,l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"')),l===null&&(o.charCodeAt(r)===40?(l="(",r++):(l=null,h('"("')),l===null&&(o.charCodeAt(r)===41?(l=")",r++):(l=null,h('")"')),l===null&&(o.charCodeAt(r)===60?(l="<",r++):(l=null,h('"<"')),l===null&&(o.charCodeAt(r)===62?(l=">",r++):(l=null,h('">"')),l===null&&(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l===null&&(o.charCodeAt(r)===92?(l="\\",r++):(l=null,h('"\\\\"')),l===null&&(l=C(),l===null&&(o.charCodeAt(r)===47?(l="/",r++):(l=null,h('"/"')),l===null&&(o.charCodeAt(r)===91?(l="[",r++):(l=null,h('"["')),l===null&&(o.charCodeAt(r)===93?(l="]",r++):(l=null,h('"]"')),l===null&&(o.charCodeAt(r)===63?(l="?",r++):(l=null,h('"?"')),l===null&&(o.charCodeAt(r)===123?(l="{",r++):(l=null,h('"{"')),l===null&&(o.charCodeAt(r)===125?(l="}",r++):(l=null,h('"}"'))))))))))))))))))))))))),l!==null)for(e=[];l!==null;)e.push(l),l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"')),l===null&&(o.charCodeAt(r)===40?(l="(",r++):(l=null,h('"("')),l===null&&(o.charCodeAt(r)===41?(l=")",r++):(l=null,h('")"')),l===null&&(o.charCodeAt(r)===60?(l="<",r++):(l=null,h('"<"')),l===null&&(o.charCodeAt(r)===62?(l=">",r++):(l=null,h('">"')),l===null&&(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l===null&&(o.charCodeAt(r)===92?(l="\\",r++):(l=null,h('"\\\\"')),l===null&&(l=C(),l===null&&(o.charCodeAt(r)===47?(l="/",r++):(l=null,h('"/"')),l===null&&(o.charCodeAt(r)===91?(l="[",r++):(l=null,h('"["')),l===null&&(o.charCodeAt(r)===93?(l="]",r++):(l=null,h('"]"')),l===null&&(o.charCodeAt(r)===63?(l="?",r++):(l=null,h('"?"')),l===null&&(o.charCodeAt(r)===123?(l="{",r++):(l=null,h('"{"')),l===null&&(o.charCodeAt(r)===125?(l="}",r++):(l=null,h('"}"')))))))))))))))))))))))));else e=null;return e!==null&&(e=function(f){return o.substring(r,f)}(u)),e===null&&(r=u),e}function W(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l!==null?(u=N(),u!==null?e=[e,l,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 B(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===47?(l="/",r++):(l=null,h('"/"')),l!==null?(u=N(),u!==null?e=[e,l,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,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l!==null?(u=N(),u!==null?e=[e,l,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 ve(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===40?(l="(",r++):(l=null,h('"("')),l!==null?(u=N(),u!==null?e=[e,l,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,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===41?(l=")",r++):(l=null,h('")"')),l!==null?(u=N(),u!==null?e=[e,l,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,l,u,f;return u=r,f=r,o.charCodeAt(r)===62?(e=">",r++):(e=null,h('">"')),e!==null?(l=N(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return">"}()),e===null&&(r=u),e}function Re(){var e,l,u,f;return u=r,f=r,e=N(),e!==null?(o.charCodeAt(r)===60?(l="<",r++):(l=null,h('"<"')),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return"<"}()),e===null&&(r=u),e}function oe(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","')),l!==null?(u=N(),u!==null?e=[e,l,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,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l!==null?(u=N(),u!==null?e=[e,l,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 lt(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=N(),u!==null?e=[e,l,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,l,u,f;return u=r,f=r,e=N(),e!==null?(l=C(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return'"'}()),e===null&&(r=u),e}function Ee(){var e,l,u,f;return u=r,f=r,e=C(),e!==null?(l=N(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return'"'}()),e===null&&(r=u),e}function Ce(){var e,l,u,f;if(f=r,e=ve(),e!==null){for(l=[],u=be(),u===null&&(u=me(),u===null&&(u=Ce()));u!==null;)l.push(u),u=be(),u===null&&(u=me(),u===null&&(u=Ce()));l!==null?(u=Ie(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)}else e=null,r=f;return e}function be(){var e;return/^[!-']/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[!-']")),e===null&&(/^[*-[]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[*-[]")),e===null&&(/^[\]-~]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\]-~]")),e===null&&(e=V(),e===null&&(e=P())))),e}function Oe(){var e,l,u,f,p,m;if(p=r,m=r,e=N(),e!==null)if(l=C(),l!==null){for(u=[],f=he(),f===null&&(f=me());f!==null;)u.push(f),f=he(),f===null&&(f=me());u!==null?(f=C(),f!==null?e=[e,l,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 o.substring(r,v)}(p)),e===null&&(r=p),e}function ge(){var e,l,u,f,p,m;if(p=r,m=r,e=N(),e!==null)if(l=C(),l!==null){for(u=[],f=he(),f===null&&(f=me());f!==null;)u.push(f),f=he(),f===null&&(f=me());u!==null?(f=C(),f!==null?e=[e,l,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=o.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 he(){var e;return e=P(),e===null&&(o.charCodeAt(r)===33?(e="!",r++):(e=null,h('"!"')),e===null&&(/^[#-[]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[#-[]")),e===null&&(/^[\]-~]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\]-~]")),e===null&&(e=V())))),e}function me(){var e,l,u;return u=r,o.charCodeAt(r)===92?(e="\\",r++):(e=null,h('"\\\\"')),e!==null?(/^[\0-\t]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[\\0-\\t]")),l===null&&(/^[\x0B-\f]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[\\x0B-\\f]")),l===null&&(/^[\x0E-]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[\\x0E-]")))),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function we(){var e,l,u,f,p,m;return p=r,m=r,e=st(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=At(),u=u!==null?u:"",u!==null?(f=ls(),f!==null?e=[e,l,u,f]:(e=null,r=m)):(e=null,r=m)):(e=null,r=m)):(e=null,r=m),e!==null&&(e=function(v){try{w.uri=new Rs(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}}()),e===null&&(r=p),e}function Ne(){var e,l,u,f,p,m,v,y;return v=r,y=r,e=st(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=At(),u=u!==null?u:"",u!==null?(f=ls(),f!==null?(p=Kn(),p!==null?(m=dn(),m=m!==null?m:"",m!==null?e=[e,l,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(O){try{w.uri=new Rs(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,a==="SIP_URI"&&(w=w.uri)}catch{w=-1}}()),e===null&&(r=v),e}function st(){var e;return e=He(),e===null&&(e=Vt()),e}function He(){var e,l;return l=r,o.substr(r,4).toLowerCase()==="sips"?(e=o.substr(r,4),r+=4):(e=null,h('"sips"')),e!==null&&(e=function(u,f){w.scheme=f.toLowerCase()}(l,e)),e===null&&(r=l),e}function Vt(){var e,l;return l=r,o.substr(r,3).toLowerCase()==="sip"?(e=o.substr(r,3),r+=3):(e=null,h('"sip"')),e!==null&&(e=function(u,f){w.scheme=f.toLowerCase()}(l,e)),e===null&&(r=l),e}function At(){var e,l,u,f,p,m;return f=r,p=r,e=qn(),e!==null?(m=r,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=un(),u!==null?l=[l,u]:(l=null,r=m)):(l=null,r=m),l=l!==null?l:"",l!==null?(o.charCodeAt(r)===64?(u="@",r++):(u=null,h('"@"')),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){w.user=decodeURIComponent(o.substring(r-1,v))}(f)),e===null&&(r=f),e}function qn(){var e,l;if(l=F(),l===null&&(l=pe(),l===null&&(l=Bn())),l!==null)for(e=[];l!==null;)e.push(l),l=F(),l===null&&(l=pe(),l===null&&(l=Bn()));else e=null;return e}function Bn(){var e;return o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","')),e===null&&(o.charCodeAt(r)===59?(e=";",r++):(e=null,h('";"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"'))))))))),e}function un(){var e,l,u;for(u=r,e=[],l=F(),l===null&&(l=pe(),l===null&&(o.charCodeAt(r)===38?(l="&",r++):(l=null,h('"&"')),l===null&&(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===36?(l="$",r++):(l=null,h('"$"')),l===null&&(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","'))))))));l!==null;)e.push(l),l=F(),l===null&&(l=pe(),l===null&&(o.charCodeAt(r)===38?(l="&",r++):(l=null,h('"&"')),l===null&&(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===36?(l="$",r++):(l=null,h('"$"')),l===null&&(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","'))))))));return e!==null&&(e=function(f){w.password=o.substring(r,f)}(u)),e===null&&(r=u),e}function ls(){var e,l,u,f,p;return f=r,e=Cs(),e!==null?(p=r,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ai(),u!==null?l=[l,u]:(l=null,r=p)):(l=null,r=p),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e}function Cs(){var e,l;return l=r,e=cn(),e===null&&(e=Zt(),e===null&&(e=fn())),e!==null&&(e=function(u){return w.host=o.substring(r,u).toLowerCase(),w.host}(l)),e===null&&(r=l),e}function cn(){var e,l,u,f,p,m;for(f=r,p=r,e=[],m=r,l=Gn(),l!==null?(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u!==null?l=[l,u]:(l=null,r=m)):(l=null,r=m);l!==null;)e.push(l),m=r,l=Gn(),l!==null?(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u!==null?l=[l,u]:(l=null,r=m)):(l=null,r=m);return e!==null?(l=Wn(),l!==null?(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u=u!==null?u:"",u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){return w.host_type="domain",o.substring(r,v)}(f)),e===null&&(r=f),e}function Gn(){var e,l,u,f;if(f=r,e=re(),e!==null){for(l=[],u=re(),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===95?(u="_",r++):(u=null,h('"_"'))));u!==null;)l.push(u),u=re(),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===95?(u="_",r++):(u=null,h('"_"'))));l!==null?e=[e,l]:(e=null,r=f)}else e=null,r=f;return e}function Wn(){var e,l,u,f;if(f=r,e=S(),e!==null){for(l=[],u=re(),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===95?(u="_",r++):(u=null,h('"_"'))));u!==null;)l.push(u),u=re(),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===95?(u="_",r++):(u=null,h('"_"'))));l!==null?e=[e,l]:(e=null,r=f)}else e=null,r=f;return e}function fn(){var e,l,u,f,p;return f=r,p=r,o.charCodeAt(r)===91?(e="[",r++):(e=null,h('"["')),e!==null?(l=Te(),l!==null?(o.charCodeAt(r)===93?(u="]",r++):(u=null,h('"]"')),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m){return w.host_type="IPv6",o.substring(r,m)}(f)),e===null&&(r=f),e}function Te(){var e,l,u,f,p,m,v,y,O,le,xe,Dt,Js,L,b,Se;return L=r,b=r,e=ae(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?(o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),f!==null?(p=ae(),p!==null?(o.charCodeAt(r)===58?(m=":",r++):(m=null,h('":"')),m!==null?(v=ae(),v!==null?(o.charCodeAt(r)===58?(y=":",r++):(y=null,h('":"')),y!==null?(O=ae(),O!==null?(o.charCodeAt(r)===58?(le=":",r++):(le=null,h('":"')),le!==null?(xe=ae(),xe!==null?(o.charCodeAt(r)===58?(Dt=":",r++):(Dt=null,h('":"')),Dt!==null?(Js=ut(),Js!==null?e=[e,l,u,f,p,m,v,y,O,le,xe,Dt,Js]:(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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(m=ae(),m!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ae(),y!==null?(o.charCodeAt(r)===58?(O=":",r++):(O=null,h('":"')),O!==null?(le=ae(),le!==null?(o.charCodeAt(r)===58?(xe=":",r++):(xe=null,h('":"')),xe!==null?(Dt=ut(),Dt!==null?e=[e,l,u,f,p,m,v,y,O,le,xe,Dt]:(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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(m=ae(),m!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ae(),y!==null?(o.charCodeAt(r)===58?(O=":",r++):(O=null,h('":"')),O!==null?(le=ut(),le!==null?e=[e,l,u,f,p,m,v,y,O,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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(m=ae(),m!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ut(),y!==null?e=[e,l,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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(m=ut(),m!==null?e=[e,l,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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ut(),f!==null?e=[e,l,u,f]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ut(),l!==null?e=[e,l]:(e=null,r=b)):(e=null,r=b),e===null&&(b=r,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?e=[e,l]:(e=null,r=b)):(e=null,r=b),e===null&&(b=r,e=ae(),e!==null?(o.substr(r,2)==="::"?(l="::",r+=2):(l=null,h('"::"')),l!==null?(u=ae(),u!==null?(o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),f!==null?(p=ae(),p!==null?(o.charCodeAt(r)===58?(m=":",r++):(m=null,h('":"')),m!==null?(v=ae(),v!==null?(o.charCodeAt(r)===58?(y=":",r++):(y=null,h('":"')),y!==null?(O=ae(),O!==null?(o.charCodeAt(r)===58?(le=":",r++):(le=null,h('":"')),le!==null?(xe=ut(),xe!==null?e=[e,l,u,f,p,m,v,y,O,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(o.substr(r,2)==="::"?(u="::",r+=2):(u=null,h('"::"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(m=ae(),m!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ae(),y!==null?(o.charCodeAt(r)===58?(O=":",r++):(O=null,h('":"')),O!==null?(le=ut(),le!==null?e=[e,l,u,f,p,m,v,y,O,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(o.substr(r,2)==="::"?(f="::",r+=2):(f=null,h('"::"')),f!==null?(p=ae(),p!==null?(o.charCodeAt(r)===58?(m=":",r++):(m=null,h('":"')),m!==null?(v=ae(),v!==null?(o.charCodeAt(r)===58?(y=":",r++):(y=null,h('":"')),y!==null?(O=ut(),O!==null?e=[e,l,u,f,p,m,v,y,O]:(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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),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,o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(o.substr(r,2)==="::"?(p="::",r+=2):(p=null,h('"::"')),p!==null?(m=ae(),m!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ut(),y!==null?e=[e,l,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),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,o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),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,o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(m=ae(),m!==null?p=[p,m]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(o.substr(r,2)==="::"?(m="::",r+=2):(m=null,h('"::"')),m!==null?(v=ut(),v!==null?e=[e,l,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),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,o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),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,o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),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,o.charCodeAt(r)===58?(m=":",r++):(m=null,h('":"')),m!==null?(v=ae(),v!==null?m=[m,v]:(m=null,r=Se)):(m=null,r=Se),m=m!==null?m:"",m!==null?(o.substr(r,2)==="::"?(v="::",r+=2):(v=null,h('"::"')),v!==null?(y=ae(),y!==null?e=[e,l,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),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,o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),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,o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),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,o.charCodeAt(r)===58?(m=":",r++):(m=null,h('":"')),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,o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ae(),y!==null?v=[v,y]:(v=null,r=Se)):(v=null,r=Se),v=v!==null?v:"",v!==null?(o.substr(r,2)==="::"?(y="::",r+=2):(y=null,h('"::"')),y!==null?e=[e,l,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(Qv){return w.host_type="IPv6",o.substring(r,Qv)}(L)),e===null&&(r=L),e}function ae(){var e,l,u,f,p;return p=r,e=E(),e!==null?(l=E(),l=l!==null?l:"",l!==null?(u=E(),u=u!==null?u:"",u!==null?(f=E(),f=f!==null?f:"",f!==null?e=[e,l,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function ut(){var e,l,u,f;return f=r,e=ae(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(e=Zt()),e}function Zt(){var e,l,u,f,p,m,v,y,O;return y=r,O=r,e=$s(),e!==null?(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l!==null?(u=$s(),u!==null?(o.charCodeAt(r)===46?(f=".",r++):(f=null,h('"."')),f!==null?(p=$s(),p!==null?(o.charCodeAt(r)===46?(m=".",r++):(m=null,h('"."')),m!==null?(v=$s(),v!==null?e=[e,l,u,f,p,m,v]:(e=null,r=O)):(e=null,r=O)):(e=null,r=O)):(e=null,r=O)):(e=null,r=O)):(e=null,r=O)):(e=null,r=O),e!==null&&(e=function(le){return w.host_type="IPv4",o.substring(r,le)}(y)),e===null&&(r=y),e}function $s(){var e,l,u,f;return f=r,o.substr(r,2)==="25"?(e="25",r+=2):(e=null,h('"25"')),e!==null?(/^[0-5]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[0-5]")),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e===null&&(f=r,o.charCodeAt(r)===50?(e="2",r++):(e=null,h('"2"')),e!==null?(/^[0-4]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[0-4]")),l!==null?(u=T(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(f=r,o.charCodeAt(r)===49?(e="1",r++):(e=null,h('"1"')),e!==null?(l=T(),l!==null?(u=T(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(f=r,/^[1-9]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[1-9]")),e!==null?(l=T(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e===null&&(e=T())))),e}function ai(){var e,l,u,f,p,m,v;return m=r,v=r,e=T(),e=e!==null?e:"",e!==null?(l=T(),l=l!==null?l:"",l!==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,l,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,O){return O=parseInt(O.join("")),w.port=O,O}(m,e)),e===null&&(r=m),e}function Kn(){var e,l,u,f;for(e=[],f=r,o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l!==null?(u=Yn(),u!==null?l=[l,u]:(l=null,r=f)):(l=null,r=f);l!==null;)e.push(l),f=r,o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l!==null?(u=Yn(),u!==null?l=[l,u]:(l=null,r=f)):(l=null,r=f);return e}function Yn(){var e;return e=ui(),e===null&&(e=ci(),e===null&&(e=fi(),e===null&&(e=di(),e===null&&(e=hi(),e===null&&(e=_i(),e===null&&(e=pi())))))),e}function ui(){var e,l,u,f;return u=r,f=r,o.substr(r,10).toLowerCase()==="transport="?(e=o.substr(r,10),r+=10):(e=null,h('"transport="')),e!==null?(o.substr(r,3).toLowerCase()==="udp"?(l=o.substr(r,3),r+=3):(l=null,h('"udp"')),l===null&&(o.substr(r,3).toLowerCase()==="tcp"?(l=o.substr(r,3),r+=3):(l=null,h('"tcp"')),l===null&&(o.substr(r,4).toLowerCase()==="sctp"?(l=o.substr(r,4),r+=4):(l=null,h('"sctp"')),l===null&&(o.substr(r,3).toLowerCase()==="tls"?(l=o.substr(r,3),r+=3):(l=null,h('"tls"')),l===null&&(l=U())))),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){w.uri_params||(w.uri_params={}),w.uri_params.transport=m.toLowerCase()}(u,e[1])),e===null&&(r=u),e}function ci(){var e,l,u,f;return u=r,f=r,o.substr(r,5).toLowerCase()==="user="?(e=o.substr(r,5),r+=5):(e=null,h('"user="')),e!==null?(o.substr(r,5).toLowerCase()==="phone"?(l=o.substr(r,5),r+=5):(l=null,h('"phone"')),l===null&&(o.substr(r,2).toLowerCase()==="ip"?(l=o.substr(r,2),r+=2):(l=null,h('"ip"')),l===null&&(l=U())),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){w.uri_params||(w.uri_params={}),w.uri_params.user=m.toLowerCase()}(u,e[1])),e===null&&(r=u),e}function fi(){var e,l,u,f;return u=r,f=r,o.substr(r,7).toLowerCase()==="method="?(e=o.substr(r,7),r+=7):(e=null,h('"method="')),e!==null?(l=vn(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){w.uri_params||(w.uri_params={}),w.uri_params.method=m}(u,e[1])),e===null&&(r=u),e}function di(){var e,l,u,f;return u=r,f=r,o.substr(r,4).toLowerCase()==="ttl="?(e=o.substr(r,4),r+=4):(e=null,h('"ttl="')),e!==null?(l=dl(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){w.params||(w.params={}),w.params.ttl=m}(u,e[1])),e===null&&(r=u),e}function hi(){var e,l,u,f;return u=r,f=r,o.substr(r,6).toLowerCase()==="maddr="?(e=o.substr(r,6),r+=6):(e=null,h('"maddr="')),e!==null?(l=Cs(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,m){w.uri_params||(w.uri_params={}),w.uri_params.maddr=m}(u,e[1])),e===null&&(r=u),e}function _i(){var e,l,u,f,p,m;return f=r,p=r,o.substr(r,2).toLowerCase()==="lr"?(e=o.substr(r,2),r+=2):(e=null,h('"lr"')),e!==null?(m=r,o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,r=m)):(l=null,r=m),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){w.uri_params||(w.uri_params={}),w.uri_params.lr=void 0}()),e===null&&(r=f),e}function pi(){var e,l,u,f,p,m;return f=r,p=r,e=mi(),e!==null?(m=r,o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l!==null?(u=Hs(),u!==null?l=[l,u]:(l=null,r=m)):(l=null,r=m),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v,y,O){w.uri_params||(w.uri_params={}),typeof O>"u"?O=void 0:O=O[1],w.uri_params[y.toLowerCase()]=O}(f,e[0],e[1])),e===null&&(r=f),e}function mi(){var e,l,u;if(u=r,l=Fs(),l!==null)for(e=[];l!==null;)e.push(l),l=Fs();else e=null;return e!==null&&(e=function(f,p){return p.join("")}(u,e)),e===null&&(r=u),e}function Hs(){var e,l,u;if(u=r,l=Fs(),l!==null)for(e=[];l!==null;)e.push(l),l=Fs();else e=null;return e!==null&&(e=function(f,p){return p.join("")}(u,e)),e===null&&(r=u),e}function Fs(){var e;return e=gi(),e===null&&(e=F(),e===null&&(e=pe())),e}function gi(){var e;return o.charCodeAt(r)===91?(e="[",r++):(e=null,h('"["')),e===null&&(o.charCodeAt(r)===93?(e="]",r++):(e=null,h('"]"')),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')))))))),e}function dn(){var e,l,u,f,p,m,v;if(m=r,o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e!==null)if(l=hn(),l!==null){for(u=[],v=r,o.charCodeAt(r)===38?(f="&",r++):(f=null,h('"&"')),f!==null?(p=hn(),p!==null?f=[f,p]:(f=null,r=v)):(f=null,r=v);f!==null;)u.push(f),v=r,o.charCodeAt(r)===38?(f="&",r++):(f=null,h('"&"')),f!==null?(p=hn(),p!==null?f=[f,p]:(f=null,r=v)):(f=null,r=v);u!==null?e=[e,l,u]:(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e}function hn(){var e,l,u,f,p;return f=r,p=r,e=Ti(),e!==null?(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l!==null?(u=Vs(),u!==null?e=[e,l,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(""),w.uri_headers||(w.uri_headers={}),w.uri_headers[v]?w.uri_headers[v].push(y):w.uri_headers[v]=[y]}(f,e[0],e[2])),e===null&&(r=f),e}function Ti(){var e,l;if(l=_n(),l===null&&(l=F(),l===null&&(l=pe())),l!==null)for(e=[];l!==null;)e.push(l),l=_n(),l===null&&(l=F(),l===null&&(l=pe()));else e=null;return e}function Vs(){var e,l;for(e=[],l=_n(),l===null&&(l=F(),l===null&&(l=pe()));l!==null;)e.push(l),l=_n(),l===null&&(l=F(),l===null&&(l=pe()));return e}function _n(){var e;return o.charCodeAt(r)===91?(e="[",r++):(e=null,h('"["')),e===null&&(o.charCodeAt(r)===93?(e="]",r++):(e=null,h('"]"')),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')))))))),e}function Do(){var e;return e=ki(),e===null&&(e=vi()),e}function vi(){var e,l,u,f,p,m;return m=r,e=vn(),e!==null?(l=H(),l!==null?(u=Jn(),u!==null?(f=H(),f!==null?(p=Qn(),p!==null?e=[e,l,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 Jn(){var e;return e=Ne(),e===null&&(e=zn()),e}function zn(){var e,l,u,f;return f=r,e=yi(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=Si(),u===null&&(u=js()),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Si(){var e,l,u,f,p;return f=r,e=pn(),e===null&&(e=mn()),e!==null?(p=r,o.charCodeAt(r)===63?(l="?",r++):(l=null,h('"?"')),l!==null?(u=Xn(),u!==null?l=[l,u]:(l=null,r=p)):(l=null,r=p),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e}function pn(){var e,l,u,f;return f=r,o.substr(r,2)==="//"?(e="//",r+=2):(e=null,h('"//"')),e!==null?(l=Ci(),l!==null?(u=mn(),u=u!==null?u:"",u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function mn(){var e,l,u;return u=r,o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e!==null?(l=gn(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function js(){var e,l,u,f;if(f=r,e=Ei(),e!==null){for(l=[],u=qs();u!==null;)l.push(u),u=qs();l!==null?e=[e,l]:(e=null,r=f)}else e=null,r=f;return e}function qs(){var e;return e=x(),e===null&&(e=F(),e===null&&(e=pe())),e}function Ei(){var e;return e=F(),e===null&&(e=pe(),e===null&&(o.charCodeAt(r)===59?(e=";",r++):(e=null,h('";"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===64?(e="@",r++):(e=null,h('"@"')),e===null&&(o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","')))))))))))),e}function gn(){var e,l,u,f,p,m;if(p=r,e=Bs(),e!==null){for(l=[],m=r,o.charCodeAt(r)===47?(u="/",r++):(u=null,h('"/"')),u!==null?(f=Bs(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,o.charCodeAt(r)===47?(u="/",r++):(u=null,h('"/"')),u!==null?(f=Bs(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function Bs(){var e,l,u,f,p,m;for(p=r,e=[],l=Gs();l!==null;)e.push(l),l=Gs();if(e!==null){for(l=[],m=r,o.charCodeAt(r)===59?(u=";",r++):(u=null,h('";"')),u!==null?(f=As(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,o.charCodeAt(r)===59?(u=";",r++):(u=null,h('";"')),u!==null?(f=As(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function As(){var e,l;for(e=[],l=Gs();l!==null;)e.push(l),l=Gs();return e}function Gs(){var e;return e=F(),e===null&&(e=pe(),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===64?(e="@",r++):(e=null,h('"@"')),e===null&&(o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","')))))))))),e}function yi(){var e,l,u,f,p;if(f=r,p=r,e=S(),e!==null){for(l=[],u=S(),u===null&&(u=T(),u===null&&(o.charCodeAt(r)===43?(u="+",r++):(u=null,h('"+"')),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."'))))));u!==null;)l.push(u),u=S(),u===null&&(u=T(),u===null&&(o.charCodeAt(r)===43?(u="+",r++):(u=null,h('"+"')),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."'))))));l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e!==null&&(e=function(m){w.scheme=o.substring(r,m)}(f)),e===null&&(r=f),e}function Ci(){var e;return e=Ai(),e===null&&(e=Ri()),e}function Ai(){var e,l,u,f;return u=r,f=r,e=At(),e!==null?(o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e=e!==null?e:"",e!==null?(l=ls(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e=e!==null?e:"",e}function Ri(){var e,l;if(l=F(),l===null&&(l=pe(),l===null&&(o.charCodeAt(r)===36?(l="$",r++):(l=null,h('"$"')),l===null&&(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","')),l===null&&(o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l===null&&(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l===null&&(o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l===null&&(o.charCodeAt(r)===38?(l="&",r++):(l=null,h('"&"')),l===null&&(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"'))))))))))),l!==null)for(e=[];l!==null;)e.push(l),l=F(),l===null&&(l=pe(),l===null&&(o.charCodeAt(r)===36?(l="$",r++):(l=null,h('"$"')),l===null&&(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","')),l===null&&(o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l===null&&(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l===null&&(o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l===null&&(o.charCodeAt(r)===38?(l="&",r++):(l=null,h('"&"')),l===null&&(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')))))))))));else e=null;return e}function Xn(){var e,l;for(e=[],l=qs();l!==null;)e.push(l),l=qs();return e}function Qn(){var e,l,u,f,p,m,v,y;if(v=r,y=r,o.substr(r,3).toLowerCase()==="sip"?(e=o.substr(r,3),r+=3):(e=null,h('"SIP"')),e!==null)if(o.charCodeAt(r)===47?(l="/",r++):(l=null,h('"/"')),l!==null){if(f=T(),f!==null)for(u=[];f!==null;)u.push(f),f=T();else u=null;if(u!==null)if(o.charCodeAt(r)===46?(f=".",r++):(f=null,h('"."')),f!==null){if(m=T(),m!==null)for(p=[];m!==null;)p.push(m),m=T();else p=null;p!==null?e=[e,l,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(O){w.sip_version=o.substring(r,O)}(v)),e===null&&(r=v),e}function bi(){var e;return o.substr(r,6)==="INVITE"?(e="INVITE",r+=6):(e=null,h('"INVITE"')),e}function Ii(){var e;return o.substr(r,3)==="ACK"?(e="ACK",r+=3):(e=null,h('"ACK"')),e}function wi(){var e;return o.substr(r,7)==="OPTIONS"?(e="OPTIONS",r+=7):(e=null,h('"OPTIONS"')),e}function Oi(){var e;return o.substr(r,3)==="BYE"?(e="BYE",r+=3):(e=null,h('"BYE"')),e}function Di(){var e;return o.substr(r,6)==="CANCEL"?(e="CANCEL",r+=6):(e=null,h('"CANCEL"')),e}function Ni(){var e;return o.substr(r,8)==="REGISTER"?(e="REGISTER",r+=8):(e=null,h('"REGISTER"')),e}function xi(){var e;return o.substr(r,9)==="SUBSCRIBE"?(e="SUBSCRIBE",r+=9):(e=null,h('"SUBSCRIBE"')),e}function Ui(){var e;return o.substr(r,6)==="NOTIFY"?(e="NOTIFY",r+=6):(e=null,h('"NOTIFY"')),e}function Tn(){var e;return o.substr(r,5)==="REFER"?(e="REFER",r+=5):(e=null,h('"REFER"')),e}function vn(){var e,l;return l=r,e=bi(),e===null&&(e=Ii(),e===null&&(e=wi(),e===null&&(e=Oi(),e===null&&(e=Di(),e===null&&(e=Ni(),e===null&&(e=xi(),e===null&&(e=Ui(),e===null&&(e=Tn(),e===null&&(e=U()))))))))),e!==null&&(e=function(u){return w.method=o.substring(r,u),w.method}(l)),e===null&&(r=l),e}function ki(){var e,l,u,f,p,m;return m=r,e=Qn(),e!==null?(l=H(),l!==null?(u=Pi(),u!==null?(f=H(),f!==null?(p=No(),p!==null?e=[e,l,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 Pi(){var e,l;return l=r,e=Mi(),e!==null&&(e=function(u,f){w.status_code=parseInt(f.join(""))}(l,e)),e===null&&(r=l),e}function Mi(){var e,l,u,f;return f=r,e=T(),e!==null?(l=T(),l!==null?(u=T(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function No(){var e,l,u;for(u=r,e=[],l=x(),l===null&&(l=F(),l===null&&(l=pe(),l===null&&(l=V(),l===null&&(l=z(),l===null&&(l=H(),l===null&&(l=k()))))));l!==null;)e.push(l),l=x(),l===null&&(l=F(),l===null&&(l=pe(),l===null&&(l=V(),l===null&&(l=z(),l===null&&(l=H(),l===null&&(l=k()))))));return e!==null&&(e=function(f){w.reason_phrase=o.substring(r,f)}(u)),e===null&&(r=u),e}function Nu(){var e,l,u,f,p,m;if(p=r,e=Cn(),e!==null){for(l=[],m=r,u=oe(),u!==null?(f=Cn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=oe(),u!==null?(f=Cn(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function xu(){var e,l,u,f,p,m;return f=r,p=r,e=Q(),e!==null?(m=r,o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l!==null?(u=Q(),u!==null?l=[l,u]:(l=null,r=m)):(l=null,r=m),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){w=o.substring(r,v)}(f)),e===null&&(r=f),e}function Zn(){var e,l,u,f,p,m,v;if(p=r,e=W(),e===null)if(m=r,e=jt(),e!==null){for(l=[],v=r,u=oe(),u!==null?(f=jt(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=oe(),u!==null?(f=jt(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var O,le;for(le=w.multi_header.length,O=0;O<le;O++)if(w.multi_header[O].parsed===null){w=null;break}w!==null?w=w.multi_header:w=-1}()),e===null&&(r=p),e}function jt(){var e,l,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=qt()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=er(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=er(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var O;w.multi_header||(w.multi_header=[]);try{O=new I(w.uri,w.display_name,w.params),delete w.uri,delete w.display_name,delete w.params}catch{O=null}w.multi_header.push({possition:r,offset:y,parsed:O})}(p)),e===null&&(r=p),e}function qt(){var e,l,u,f,p;return p=r,e=Ws(),e=e!==null?e:"",e!==null?(l=Re(),l!==null?(u=Ne(),u!==null?(f=Pe(),f!==null?e=[e,l,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function Ws(){var e,l,u,f,p,m,v;if(p=r,m=r,e=U(),e!==null){for(l=[],v=r,u=P(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=P(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e===null&&(e=ge()),e!==null&&(e=function(y,O){typeof O=="string"?w.display_name=O:w.display_name=O[1].reduce(function(le,xe){return le+xe[0]+xe[1]},O[0])}(p,e)),e===null&&(r=p),e}function er(){var e;return e=Li(),e===null&&(e=os(),e===null&&(e=Xe())),e}function Li(){var e,l,u,f,p;return f=r,p=r,o.substr(r,1).toLowerCase()==="q"?(e=o.substr(r,1),r++):(e=null,h('"q"')),e!==null?(l=ie(),l!==null?(u=ze(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.params||(w.params={}),w.params.q=v}(f,e[2])),e===null&&(r=f),e}function os(){var e,l,u,f,p;return f=r,p=r,o.substr(r,7).toLowerCase()==="expires"?(e=o.substr(r,7),r+=7):(e=null,h('"expires"')),e!==null?(l=ie(),l!==null?(u=as(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.params||(w.params={}),w.params.expires=v}(f,e[2])),e===null&&(r=f),e}function as(){var e,l,u;if(u=r,l=T(),l!==null)for(e=[];l!==null;)e.push(l),l=T();else e=null;return e!==null&&(e=function(f,p){return parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function ze(){var e,l,u,f,p,m,v,y;return m=r,v=r,o.charCodeAt(r)===48?(e="0",r++):(e=null,h('"0"')),e!==null?(y=r,o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l!==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?l=[l,u,f,p]:(l=null,r=y)):(l=null,r=y)):(l=null,r=y)):(l=null,r=y),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(O){return parseFloat(o.substring(r,O))}(m)),e===null&&(r=m),e}function Xe(){var e,l,u,f,p,m;return f=r,p=r,e=U(),e!==null?(m=r,l=ie(),l!==null?(u=xo(),u!==null?l=[l,u]:(l=null,r=m)):(l=null,r=m),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v,y,O){w.params||(w.params={}),typeof O>"u"?O=void 0:O=O[1],w.params[y.toLowerCase()]=O}(f,e[0],e[1])),e===null&&(r=f),e}function xo(){var e;return e=U(),e===null&&(e=Cs(),e===null&&(e=Oe())),e}function Uo(){var e,l,u,f,p,m;if(p=r,e=tr(),e!==null){for(l=[],m=r,u=ye(),u!==null?(f=sr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=ye(),u!==null?(f=sr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function tr(){var e;return o.substr(r,6).toLowerCase()==="render"?(e=o.substr(r,6),r+=6):(e=null,h('"render"')),e===null&&(o.substr(r,7).toLowerCase()==="session"?(e=o.substr(r,7),r+=7):(e=null,h('"session"')),e===null&&(o.substr(r,4).toLowerCase()==="icon"?(e=o.substr(r,4),r+=4):(e=null,h('"icon"')),e===null&&(o.substr(r,5).toLowerCase()==="alert"?(e=o.substr(r,5),r+=5):(e=null,h('"alert"')),e===null&&(e=U())))),e}function sr(){var e;return e=ko(),e===null&&(e=Xe()),e}function ko(){var e,l,u,f;return f=r,o.substr(r,8).toLowerCase()==="handling"?(e=o.substr(r,8),r+=8):(e=null,h('"handling"')),e!==null?(l=ie(),l!==null?(o.substr(r,8).toLowerCase()==="optional"?(u=o.substr(r,8),r+=8):(u=null,h('"optional"')),u===null&&(o.substr(r,8).toLowerCase()==="required"?(u=o.substr(r,8),r+=8):(u=null,h('"required"')),u===null&&(u=U())),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Uu(){var e,l,u,f,p,m;if(p=r,e=U(),e!==null){for(l=[],m=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function ku(){var e,l,u;if(u=r,l=T(),l!==null)for(e=[];l!==null;)e.push(l),l=T();else e=null;return e!==null&&(e=function(f,p){w=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function Po(){var e,l;return l=r,e=$i(),e!==null&&(e=function(u){w=o.substring(r,u)}(l)),e===null&&(r=l),e}function $i(){var e,l,u,f,p,m,v,y;if(v=r,e=Hi(),e!==null)if(l=B(),l!==null)if(u=nr(),u!==null){for(f=[],y=r,p=ye(),p!==null?(m=rr(),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=rr(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,l,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function Hi(){var e;return e=Fi(),e===null&&(e=Sn()),e}function Fi(){var e;return o.substr(r,4).toLowerCase()==="text"?(e=o.substr(r,4),r+=4):(e=null,h('"text"')),e===null&&(o.substr(r,5).toLowerCase()==="image"?(e=o.substr(r,5),r+=5):(e=null,h('"image"')),e===null&&(o.substr(r,5).toLowerCase()==="audio"?(e=o.substr(r,5),r+=5):(e=null,h('"audio"')),e===null&&(o.substr(r,5).toLowerCase()==="video"?(e=o.substr(r,5),r+=5):(e=null,h('"video"')),e===null&&(o.substr(r,11).toLowerCase()==="application"?(e=o.substr(r,11),r+=11):(e=null,h('"application"')),e===null&&(e=En()))))),e}function Sn(){var e;return o.substr(r,7).toLowerCase()==="message"?(e=o.substr(r,7),r+=7):(e=null,h('"message"')),e===null&&(o.substr(r,9).toLowerCase()==="multipart"?(e=o.substr(r,9),r+=9):(e=null,h('"multipart"')),e===null&&(e=En())),e}function En(){var e;return e=U(),e===null&&(e=Vi()),e}function Vi(){var e,l,u;return u=r,o.substr(r,2).toLowerCase()==="x-"?(e=o.substr(r,2),r+=2):(e=null,h('"x-"')),e!==null?(l=U(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function nr(){var e;return e=En(),e===null&&(e=U()),e}function rr(){var e,l,u,f;return f=r,e=U(),e!==null?(l=ie(),l!==null?(u=Mo(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Mo(){var e;return e=U(),e===null&&(e=Oe()),e}function Lo(){var e,l,u,f;return f=r,e=$o(),e!==null?(l=P(),l!==null?(u=vn(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function $o(){var e,l,u;if(u=r,l=T(),l!==null)for(e=[];l!==null;)e.push(l),l=T();else e=null;return e!==null&&(e=function(f,p){w.value=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function Pu(){var e,l;return l=r,e=as(),e!==null&&(e=function(u,f){w=f}(l,e)),e===null&&(r=l),e}function yn(){var e,l,u,f,p,m,v;if(p=r,m=r,e=Cn(),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y,O){w.event=O.join("").toLowerCase()}(p,e[0])),e===null&&(r=p),e}function Cn(){var e,l,u,f,p,m;if(p=r,e=X(),e!==null){for(l=[],m=r,o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u!==null?(f=X(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u!==null?(f=X(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function ji(){var e,l,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=qt()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=An(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=An(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var O=w.tag;try{w=new I(w.uri,w.display_name,w.params),O&&w.setParam("tag",O)}catch{w=-1}}()),e===null&&(r=p),e}function An(){var e;return e=qi(),e===null&&(e=Xe()),e}function qi(){var e,l,u,f,p;return f=r,p=r,o.substr(r,3).toLowerCase()==="tag"?(e=o.substr(r,3),r+=3):(e=null,h('"tag"')),e!==null?(l=ie(),l!==null?(u=U(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.tag=v}(f,e[2])),e===null&&(r=f),e}function Mu(){var e,l,u;if(u=r,l=T(),l!==null)for(e=[];l!==null;)e.push(l),l=T();else e=null;return e!==null&&(e=function(f,p){w=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function Lu(){var e,l;return l=r,e=as(),e!==null&&(e=function(u,f){w=f}(l,e)),e===null&&(r=l),e}function $u(){var e,l,u,f,p,m,v,y,O,le;for(y=r,O=r,e=[],l=Ws();l!==null;)e.push(l),l=Ws();if(e!==null)if(l=Re(),l!==null)if(u=Ne(),u!==null)if(f=Pe(),f!==null){for(p=[],le=r,m=ye(),m!==null?(v=Xe(),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=Xe(),v!==null?m=[m,v]:(m=null,r=le)):(m=null,r=le);p!==null?e=[e,l,u,f,p]:(e=null,r=O)}else e=null,r=O;else e=null,r=O;else e=null,r=O;else e=null,r=O;return e!==null&&(e=function(xe){try{w=new I(w.uri,w.display_name,w.params)}catch{w=-1}}()),e===null&&(r=y),e}function Bi(){var e;return e=ir(),e}function ir(){var e,l,u,f,p,m,v,y;if(v=r,o.substr(r,6).toLowerCase()==="digest"?(e=o.substr(r,6),r+=6):(e=null,h('"Digest"')),e!==null)if(l=P(),l!==null)if(u=Rn(),u!==null){for(f=[],y=r,p=oe(),p!==null?(m=Rn(),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=Rn(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,l,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,l,u,f,p,m,v,y;if(v=r,e=U(),e!==null)if(l=P(),l!==null)if(u=us(),u!==null){for(f=[],y=r,p=oe(),p!==null?(m=us(),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=us(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,l,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function us(){var e,l,u,f;return f=r,e=U(),e!==null?(l=ie(),l!==null?(u=U(),u===null&&(u=Oe()),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Rn(){var e;return e=Gi(),e===null&&(e=bn(),e===null&&(e=Ki(),e===null&&(e=Ji(),e===null&&(e=zi(),e===null&&(e=Xi(),e===null&&(e=wn(),e===null&&(e=us()))))))),e}function Gi(){var e,l,u,f;return f=r,o.substr(r,5).toLowerCase()==="realm"?(e=o.substr(r,5),r+=5):(e=null,h('"realm"')),e!==null?(l=ie(),l!==null?(u=Wi(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Wi(){var e,l;return l=r,e=ge(),e!==null&&(e=function(u,f){w.realm=f}(l,e)),e===null&&(r=l),e}function bn(){var e,l,u,f,p,m,v,y,O;if(y=r,o.substr(r,6).toLowerCase()==="domain"?(e=o.substr(r,6),r+=6):(e=null,h('"domain"')),e!==null)if(l=ie(),l!==null)if(u=at(),u!==null)if(f=In(),f!==null){if(p=[],O=r,v=H(),v!==null)for(m=[];v!==null;)m.push(v),v=H();else m=null;for(m!==null?(v=In(),v!==null?m=[m,v]:(m=null,r=O)):(m=null,r=O);m!==null;){if(p.push(m),O=r,v=H(),v!==null)for(m=[];v!==null;)m.push(v),v=H();else m=null;m!==null?(v=In(),v!==null?m=[m,v]:(m=null,r=O)):(m=null,r=O)}p!==null?(m=Ee(),m!==null?e=[e,l,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 In(){var e;return e=zn(),e===null&&(e=mn()),e}function Ki(){var e,l,u,f;return f=r,o.substr(r,5).toLowerCase()==="nonce"?(e=o.substr(r,5),r+=5):(e=null,h('"nonce"')),e!==null?(l=ie(),l!==null?(u=Yi(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Yi(){var e,l;return l=r,e=ge(),e!==null&&(e=function(u,f){w.nonce=f}(l,e)),e===null&&(r=l),e}function Ji(){var e,l,u,f,p;return f=r,p=r,o.substr(r,6).toLowerCase()==="opaque"?(e=o.substr(r,6),r+=6):(e=null,h('"opaque"')),e!==null?(l=ie(),l!==null?(u=ge(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.opaque=v}(f,e[2])),e===null&&(r=f),e}function zi(){var e,l,u,f,p;return f=r,o.substr(r,5).toLowerCase()==="stale"?(e=o.substr(r,5),r+=5):(e=null,h('"stale"')),e!==null?(l=ie(),l!==null?(p=r,o.substr(r,4).toLowerCase()==="true"?(u=o.substr(r,4),r+=4):(u=null,h('"true"')),u!==null&&(u=function(m){w.stale=!0}()),u===null&&(r=p),u===null&&(p=r,o.substr(r,5).toLowerCase()==="false"?(u=o.substr(r,5),r+=5):(u=null,h('"false"')),u!==null&&(u=function(m){w.stale=!1}()),u===null&&(r=p)),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Xi(){var e,l,u,f,p;return f=r,p=r,o.substr(r,9).toLowerCase()==="algorithm"?(e=o.substr(r,9),r+=9):(e=null,h('"algorithm"')),e!==null?(l=ie(),l!==null?(o.substr(r,3).toLowerCase()==="md5"?(u=o.substr(r,3),r+=3):(u=null,h('"MD5"')),u===null&&(o.substr(r,8).toLowerCase()==="md5-sess"?(u=o.substr(r,8),r+=8):(u=null,h('"MD5-sess"')),u===null&&(u=U())),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.algorithm=v.toUpperCase()}(f,e[2])),e===null&&(r=f),e}function wn(){var e,l,u,f,p,m,v,y,O,le;if(y=r,o.substr(r,3).toLowerCase()==="qop"?(e=o.substr(r,3),r+=3):(e=null,h('"qop"')),e!==null)if(l=ie(),l!==null)if(u=at(),u!==null){if(O=r,f=lr(),f!==null){for(p=[],le=r,o.charCodeAt(r)===44?(m=",",r++):(m=null,h('","')),m!==null?(v=lr(),v!==null?m=[m,v]:(m=null,r=le)):(m=null,r=le);m!==null;)p.push(m),le=r,o.charCodeAt(r)===44?(m=",",r++):(m=null,h('","')),m!==null?(v=lr(),v!==null?m=[m,v]:(m=null,r=le)):(m=null,r=le);p!==null?f=[f,p]:(f=null,r=O)}else f=null,r=O;f!==null?(p=Ee(),p!==null?e=[e,l,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 lr(){var e,l;return l=r,o.substr(r,8).toLowerCase()==="auth-int"?(e=o.substr(r,8),r+=8):(e=null,h('"auth-int"')),e===null&&(o.substr(r,4).toLowerCase()==="auth"?(e=o.substr(r,4),r+=4):(e=null,h('"auth"')),e===null&&(e=U())),e!==null&&(e=function(u,f){w.qop||(w.qop=[]),w.qop.push(f.toLowerCase())}(l,e)),e===null&&(r=l),e}function Hu(){var e,l,u,f,p,m;if(p=r,e=U(),e!==null){for(l=[],m=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function or(){var e,l,u,f,p,m,v;if(p=r,m=r,e=ar(),e!==null){for(l=[],v=r,u=oe(),u!==null?(f=ar(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=oe(),u!==null?(f=ar(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var O,le;for(le=w.multi_header.length,O=0;O<le;O++)if(w.multi_header[O].parsed===null){w=null;break}w!==null?w=w.multi_header:w=-1}()),e===null&&(r=p),e}function ar(){var e,l,u,f,p,m,v;if(p=r,m=r,e=qt(),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var O;w.multi_header||(w.multi_header=[]);try{O=new I(w.uri,w.display_name,w.params),delete w.uri,delete w.display_name,delete w.params}catch{O=null}w.multi_header.push({possition:r,offset:y,parsed:O})}(p)),e===null&&(r=p),e}function Qi(){var e,l,u,f,p,m,v;if(p=r,m=r,o.substr(r,3).toLowerCase()==="sip"?(e=o.substr(r,3),r+=3):(e=null,h('"SIP"')),e===null&&(e=U()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=ur(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=ur(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y,O){if(w.protocol=O.toLowerCase(),w.params||(w.params={}),w.params.text&&w.params.text[0]==='"'){var le=w.params.text;w.text=le.substring(1,le.length-1),delete w.params.text}}(p,e[0])),e===null&&(r=p),e}function ur(){var e;return e=Ho(),e===null&&(e=Xe()),e}function Ho(){var e,l,u,f,p,m;if(p=r,m=r,o.substr(r,5).toLowerCase()==="cause"?(e=o.substr(r,5),r+=5):(e=null,h('"cause"')),e!==null)if(l=ie(),l!==null){if(f=T(),f!==null)for(u=[];f!==null;)u.push(f),f=T();else u=null;u!==null?e=[e,l,u]:(e=null,r=m)}else e=null,r=m;else e=null,r=m;return e!==null&&(e=function(v,y){w.cause=parseInt(y.join(""))}(p,e[2])),e===null&&(r=p),e}function Fu(){var e,l,u,f,p,m;if(p=r,e=U(),e!==null){for(l=[],m=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function cr(){var e,l,u,f,p,m;if(p=r,e=fr(),e!==null){for(l=[],m=r,u=oe(),u!==null?(f=fr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=oe(),u!==null?(f=fr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function fr(){var e,l,u,f,p,m;if(p=r,e=qt(),e!==null){for(l=[],m=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function Fo(){var e,l,u,f,p,m;if(p=r,e=dr(),e!==null){for(l=[],m=r,u=ye(),u!==null?(f=hr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=ye(),u!==null?(f=hr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function dr(){var e,l;return l=r,o.substr(r,6).toLowerCase()==="active"?(e=o.substr(r,6),r+=6):(e=null,h('"active"')),e===null&&(o.substr(r,7).toLowerCase()==="pending"?(e=o.substr(r,7),r+=7):(e=null,h('"pending"')),e===null&&(o.substr(r,10).toLowerCase()==="terminated"?(e=o.substr(r,10),r+=10):(e=null,h('"terminated"')),e===null&&(e=U()))),e!==null&&(e=function(u){w.state=o.substring(r,u)}(l)),e===null&&(r=l),e}function hr(){var e,l,u,f,p;return f=r,p=r,o.substr(r,6).toLowerCase()==="reason"?(e=o.substr(r,6),r+=6):(e=null,h('"reason"')),e!==null?(l=ie(),l!==null?(u=Vo(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){typeof v<"u"&&(w.reason=v)}(f,e[2])),e===null&&(r=f),e===null&&(f=r,p=r,o.substr(r,7).toLowerCase()==="expires"?(e=o.substr(r,7),r+=7):(e=null,h('"expires"')),e!==null?(l=ie(),l!==null?(u=as(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){typeof v<"u"&&(w.expires=v)}(f,e[2])),e===null&&(r=f),e===null&&(f=r,p=r,o.substr(r,11).toLowerCase()==="retry_after"?(e=o.substr(r,11),r+=11):(e=null,h('"retry_after"')),e!==null?(l=ie(),l!==null?(u=as(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){typeof v<"u"&&(w.retry_after=v)}(f,e[2])),e===null&&(r=f),e===null&&(e=Xe()))),e}function Vo(){var e;return o.substr(r,11).toLowerCase()==="deactivated"?(e=o.substr(r,11),r+=11):(e=null,h('"deactivated"')),e===null&&(o.substr(r,9).toLowerCase()==="probation"?(e=o.substr(r,9),r+=9):(e=null,h('"probation"')),e===null&&(o.substr(r,8).toLowerCase()==="rejected"?(e=o.substr(r,8),r+=8):(e=null,h('"rejected"')),e===null&&(o.substr(r,7).toLowerCase()==="timeout"?(e=o.substr(r,7),r+=7):(e=null,h('"timeout"')),e===null&&(o.substr(r,6).toLowerCase()==="giveup"?(e=o.substr(r,6),r+=6):(e=null,h('"giveup"')),e===null&&(o.substr(r,10).toLowerCase()==="noresource"?(e=o.substr(r,10),r+=10):(e=null,h('"noresource"')),e===null&&(o.substr(r,9).toLowerCase()==="invariant"?(e=o.substr(r,9),r+=9):(e=null,h('"invariant"')),e===null&&(e=U()))))))),e}function Vu(){var e;return e=j(),e=e!==null?e:"",e}function ju(){var e,l,u,f,p,m;if(p=r,e=U(),e!==null){for(l=[],m=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e=e!==null?e:"",e}function Zi(){var e,l,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=qt()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=el(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=el(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){var O=w.tag;try{w=new I(w.uri,w.display_name,w.params),O&&w.setParam("tag",O)}catch{w=-1}}()),e===null&&(r=p),e}function el(){var e;return e=qi(),e===null&&(e=Xe()),e}function _r(){var e,l,u,f,p,m;if(p=r,e=Ys(),e!==null){for(l=[],m=r,u=oe(),u!==null?(f=Ys(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=oe(),u!==null?(f=Ys(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function Ys(){var e,l,u,f,p,m,v,y;if(v=r,e=ol(),e!==null)if(l=P(),l!==null)if(u=cl(),u!==null){for(f=[],y=r,p=ye(),p!==null?(m=pr(),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=pr(),m!==null?p=[p,m]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,l,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function pr(){var e;return e=tl(),e===null&&(e=sl(),e===null&&(e=nl(),e===null&&(e=rl(),e===null&&(e=il(),e===null&&(e=Xe()))))),e}function tl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,3).toLowerCase()==="ttl"?(e=o.substr(r,3),r+=3):(e=null,h('"ttl"')),e!==null?(l=ie(),l!==null?(u=dl(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.ttl=v}(f,e[2])),e===null&&(r=f),e}function sl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,5).toLowerCase()==="maddr"?(e=o.substr(r,5),r+=5):(e=null,h('"maddr"')),e!==null?(l=ie(),l!==null?(u=Cs(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.maddr=v}(f,e[2])),e===null&&(r=f),e}function nl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,8).toLowerCase()==="received"?(e=o.substr(r,8),r+=8):(e=null,h('"received"')),e!==null?(l=ie(),l!==null?(u=Zt(),u===null&&(u=Te()),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.received=v}(f,e[2])),e===null&&(r=f),e}function rl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,6).toLowerCase()==="branch"?(e=o.substr(r,6),r+=6):(e=null,h('"branch"')),e!==null?(l=ie(),l!==null?(u=U(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.branch=v}(f,e[2])),e===null&&(r=f),e}function il(){var e,l,u,f,p;return f=r,o.substr(r,5).toLowerCase()==="rport"?(e=o.substr(r,5),r+=5):(e=null,h('"rport"')),e!==null?(p=r,l=ie(),l!==null?(u=ll(),u!==null?l=[l,u]:(l=null,r=p)):(l=null,r=p),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e}function ll(){var e,l,u,f,p,m,v;return m=r,v=r,e=T(),e=e!==null?e:"",e!==null?(l=T(),l=l!==null?l:"",l!==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,l,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,O){w.rport=parseInt(O.join(""))}(m,e)),e===null&&(r=m),e}function ol(){var e,l,u,f,p,m;return m=r,e=al(),e!==null?(l=B(),l!==null?(u=U(),u!==null?(f=B(),f!==null?(p=ul(),p!==null?e=[e,l,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 al(){var e,l;return l=r,o.substr(r,3).toLowerCase()==="sip"?(e=o.substr(r,3),r+=3):(e=null,h('"SIP"')),e===null&&(e=U()),e!==null&&(e=function(u,f){w.protocol=f}(l,e)),e===null&&(r=l),e}function ul(){var e,l;return l=r,o.substr(r,3).toLowerCase()==="udp"?(e=o.substr(r,3),r+=3):(e=null,h('"UDP"')),e===null&&(o.substr(r,3).toLowerCase()==="tcp"?(e=o.substr(r,3),r+=3):(e=null,h('"TCP"')),e===null&&(o.substr(r,3).toLowerCase()==="tls"?(e=o.substr(r,3),r+=3):(e=null,h('"TLS"')),e===null&&(o.substr(r,4).toLowerCase()==="sctp"?(e=o.substr(r,4),r+=4):(e=null,h('"SCTP"')),e===null&&(e=U())))),e!==null&&(e=function(u,f){w.transport=f}(l,e)),e===null&&(r=l),e}function cl(){var e,l,u,f,p;return f=r,e=fl(),e!==null?(p=r,l=lt(),l!==null?(u=mr(),u!==null?l=[l,u]:(l=null,r=p)):(l=null,r=p),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e}function fl(){var e,l;return l=r,e=Zt(),e===null&&(e=fn(),e===null&&(e=cn())),e!==null&&(e=function(u){w.host=o.substring(r,u)}(l)),e===null&&(r=l),e}function mr(){var e,l,u,f,p,m,v;return m=r,v=r,e=T(),e=e!==null?e:"",e!==null?(l=T(),l=l!==null?l:"",l!==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,l,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,O){w.port=parseInt(O.join(""))}(m,e)),e===null&&(r=m),e}function dl(){var e,l,u,f,p;return f=r,p=r,e=T(),e!==null?(l=T(),l=l!==null?l:"",l!==null?(u=T(),u=u!==null?u:"",u!==null?e=[e,l,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 qu(){var e;return e=ir(),e}function jo(){var e,l,u,f,p,m;if(p=r,e=gr(),e!==null){for(l=[],m=r,u=ye(),u!==null?(f=Tr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=ye(),u!==null?(f=Tr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function gr(){var e,l;return l=r,e=as(),e!==null&&(e=function(u,f){w.expires=f}(l,e)),e===null&&(r=l),e}function Tr(){var e;return e=qo(),e===null&&(e=Xe()),e}function qo(){var e,l,u,f,p;return f=r,p=r,o.substr(r,9).toLowerCase()==="refresher"?(e=o.substr(r,9),r+=9):(e=null,h('"refresher"')),e!==null?(l=ie(),l!==null?(o.substr(r,3).toLowerCase()==="uac"?(u=o.substr(r,3),r+=3):(u=null,h('"uac"')),u===null&&(o.substr(r,3).toLowerCase()==="uas"?(u=o.substr(r,3),r+=3):(u=null,h('"uas"'))),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.refresher=v.toLowerCase()}(f,e[2])),e===null&&(r=f),e}function Bo(){var e,l,u,f;return f=r,e=U(),e!==null?(l=q(),l!==null?(u=Go(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Go(){var e,l;for(e=[],l=K(),l===null&&(l=z(),l===null&&(l=P()));l!==null;)e.push(l),l=K(),l===null&&(l=z(),l===null&&(l=P()));return e}function Bu(){var e,l;for(e=[],l=R();l!==null;)e.push(l),l=R();return e}function Wo(){var e,l,u;return u=r,o.substr(r,5)==="uuid:"?(e="uuid:",r+=5):(e=null,h('"uuid:"')),e!==null?(l=Bt(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function Bt(){var e,l,u,f,p,m,v,y,O,le,xe;return le=r,xe=r,e=hl(),e!==null?(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l!==null?(u=Gt(),u!==null?(o.charCodeAt(r)===45?(f="-",r++):(f=null,h('"-"')),f!==null?(p=Gt(),p!==null?(o.charCodeAt(r)===45?(m="-",r++):(m=null,h('"-"')),m!==null?(v=Gt(),v!==null?(o.charCodeAt(r)===45?(y="-",r++):(y=null,h('"-"')),y!==null?(O=Ko(),O!==null?e=[e,l,u,f,p,m,v,y,O]:(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(Dt,Js){w=o.substring(r+5,Dt)}(le,e[0])),e===null&&(r=le),e}function Gt(){var e,l,u,f,p;return p=r,e=E(),e!==null?(l=E(),l!==null?(u=E(),u!==null?(f=E(),f!==null?e=[e,l,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function hl(){var e,l,u;return u=r,e=Gt(),e!==null?(l=Gt(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function Ko(){var e,l,u,f;return f=r,e=Gt(),e!==null?(l=Gt(),l!==null?(u=Gt(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Gu(){var e,l,u,f,p,m,v;if(p=r,m=r,e=we(),e===null&&(e=qt()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=m)}else e=null,r=m;return e!==null&&(e=function(y){try{w=new I(w.uri,w.display_name,w.params)}catch{w=-1}}()),e===null&&(r=p),e}function Yo(){var e,l,u,f,p,m;if(p=r,e=vr(),e!==null){for(l=[],m=r,u=ye(),u!==null?(f=Sr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);u!==null;)l.push(u),m=r,u=ye(),u!==null?(f=Sr(),f!==null?u=[u,f]:(u=null,r=m)):(u=null,r=m);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function vr(){var e,l,u,f,p,m;return f=r,p=r,e=Q(),e!==null?(m=r,o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l!==null?(u=Q(),u!==null?l=[l,u]:(l=null,r=m)):(l=null,r=m),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){w.call_id=o.substring(r,v)}(f)),e===null&&(r=f),e}function Sr(){var e;return e=_l(),e===null&&(e=pl(),e===null&&(e=Jo(),e===null&&(e=Xe()))),e}function _l(){var e,l,u,f,p;return f=r,p=r,o.substr(r,6)==="to-tag"?(e="to-tag",r+=6):(e=null,h('"to-tag"')),e!==null?(l=ie(),l!==null?(u=U(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.to_tag=v}(f,e[2])),e===null&&(r=f),e}function pl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,8)==="from-tag"?(e="from-tag",r+=8):(e=null,h('"from-tag"')),e!==null?(l=ie(),l!==null?(u=U(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(m,v){w.from_tag=v}(f,e[2])),e===null&&(r=f),e}function Jo(){var e,l;return l=r,o.substr(r,10)==="early-only"?(e="early-only",r+=10):(e=null,h('"early-only"')),e!==null&&(e=function(u){w.early_only=!0}()),e===null&&(r=l),e}function Wu(e){e.sort();for(var l=null,u=[],f=0;f<e.length;f++)e[f]!==l&&(u.push(e[f]),l=e[f]);return u}function zo(){for(var e=1,l=1,u=!1,f=0;f<Math.max(r,_);f++){var p=o.charAt(f);p===`
4
- `?(u||e++,l=1,u=!1):p==="\r"||p==="\u2028"||p==="\u2029"?(e++,l=1,u=!0):(l++,u=!1)}return{line:e,column:l}}var Rs=Is(),I=Zo(),w={},ml=s[a]();if(ml===null||r!==o.length){var gl=Math.max(r,_),Xo=gl<o.length?o.charAt(gl):null,i=zo();return new this.SyntaxError(Wu(d),Xo,gl,i.line,i.column),-1}return w},toSource:function(){return this._source}};return t.SyntaxError=function(n,o,a,s,r){function _(d,h){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=h?c(h):"end of input","Expected "+g+" but "+T+" found."}this.name="SyntaxError",this.expected=n,this.found=o,this.message=_(n,o),this.offset=a,this.line=s,this.column=r},t.SyntaxError.prototype=Error.prototype,t}()),ea}var ta,Qu;function Is(){if(Qu)return ta;Qu=1;function c(h,g){var T;if(typeof Symbol>"u"||h[Symbol.iterator]==null){if(Array.isArray(h)||(T=t(h))||g&&h&&typeof h.length=="number"){T&&(h=T);var S=0,E=function(){};return{s:E,n:function(){return S>=h.length?{done:!0}:{done:!1,value:h[S++]}},e:function(k){throw k},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 A=!0,R=!1,C;return{s:function(){T=h[Symbol.iterator]()},n:function(){var k=T.next();return A=k.done,k},e:function(k){R=!0,C=k},f:function(){try{!A&&T.return!=null&&T.return()}finally{if(R)throw C}}}}function t(h,g){if(h){if(typeof h=="string")return n(h,g);var T=Object.prototype.toString.call(h).slice(8,-1);if(T==="Object"&&h.constructor&&(T=h.constructor.name),T==="Map"||T==="Set")return Array.from(h);if(T==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(T))return n(h,g)}}function n(h,g){(g==null||g>h.length)&&(g=h.length);for(var T=0,S=new Array(g);T<g;T++)S[T]=h[T];return S}function o(h,g){if(!(h instanceof g))throw new TypeError("Cannot call a class as a function")}function a(h,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(h,S.key,S)}}function s(h,g,T){return g&&a(h.prototype,g),T&&a(h,T),h}var r=nt,_=Rt(),d=ts();return ta=function(){s(h,null,[{key:"parse",value:function(T){if(T=d.parse(T,"SIP_URI"),T!==-1)return T}}]);function h(g,T,S,E){var A=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},R=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{};if(o(this,h),!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 C in A)Object.prototype.hasOwnProperty.call(A,C)&&this.setParam(C,A[C]);for(var H in R)Object.prototype.hasOwnProperty.call(R,H)&&this.setHeader(H,R[H])}return s(h,[{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[_.headerize(T)]=Array.isArray(S)?S:[S]}},{key:"getHeader",value:function(T){if(T)return this._headers[_.headerize(T)]}},{key:"hasHeader",value:function(T){if(T)return this._headers.hasOwnProperty(_.headerize(T))&&!0||!1}},{key:"deleteHeader",value:function(T){if(T=_.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 h(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(_.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 A in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,A)){var R=c(this._headers[A]),C;try{for(R.s();!(C=R.n()).done;){var H=C.value;T.push("".concat(A,"=").concat(H))}}catch(k){R.e(k)}finally{R.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(_.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}}]),h}(),ta}var Zu;function Rt(){if(Zu)return Ze;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=n(g))||T&&g&&typeof g.length=="number"){S&&(g=S);var E=0,A=function(){};return{s:A,n:function(){return E>=g.length?{done:!0}:{done:!1,value:g[E++]}},e:function(re){throw re},f:A}}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 R=!0,C=!1,H;return{s:function(){S=g[Symbol.iterator]()},n:function(){var re=S.next();return R=re.done,re},e:function(re){C=!0,H=re},f:function(){try{!R&&S.return!=null&&S.return()}finally{if(C)throw H}}}}function n(g,T){if(g){if(typeof g=="string")return o(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 o(g,T)}}function o(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=nt,s=Is(),r=ts();Ze.str_utf8_length=function(g){return unescape(encodeURIComponent(g)).length};var _=Ze.isFunction=function(g){return g!==void 0?Object.prototype.toString.call(g)==="[object Function]":!1};Ze.isString=function(g){return g!==void 0?Object.prototype.toString.call(g)==="[object String]":!1},Ze.isDecimal=function(g){return!isNaN(g)&&parseFloat(g)===parseInt(g,10)},Ze.isEmpty=function(g){return g===null||g===""||g===void 0||Array.isArray(g)&&g.length===0||typeof g=="number"&&isNaN(g)},Ze.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 A=0,R=S;A<R.length;A++){var C=R[A];if(_(g[C]))return!1}return!0};var d=Ze.createRandomToken=function(g){var T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:32,S,E,A="";for(S=0;S<g;S++)E=Math.random()*T|0,A+=E.toString(T);return A};Ze.newTag=function(){return d(10)},Ze.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},Ze.hostType=function(g){if(g){if(g=r.parse(g,"host"),g!==-1)return g.host_type}else return};var h=Ze.escapeUser=function(g){return encodeURIComponent(decodeURIComponent(g)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/")};return Ze.normalizeTarget=function(g,T){if(g){if(g instanceof s)return g;if(typeof g=="string"){var S=g.split("@"),E,A;switch(S.length){case 1:if(!T)return;E=g,A=T;break;case 2:E=S[0],A=S[1];break;default:E=S.slice(0,S.length-1).join("@"),A=S[S.length-1]}E=E.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(E)&&(E=E.replace(/[-.()]/g,"")),g="".concat(a.SIP,":").concat(h(E),"@").concat(A);var R;return(R=s.parse(g))?R:void 0}else return}else return},Ze.headerize=function(g){var T={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},S=g.toLowerCase().replace(/_/g,"-").split("-"),E="",A=S.length,R;for(R=0;R<A;R++)R!==0&&(E+="-"),E+=S[R].charAt(0).toUpperCase()+S[R].substring(1);return T[E]&&(E=T[E]),E},Ze.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},Ze.getRandomTestNetIP=function(){function g(T,S){return Math.floor(Math.random()*(S-T+1)+T)}return"192.0.2.".concat(g(1,254))},Ze.calculateMD5=function(g){function T(ge,he){return ge<<he|ge>>>32-he}function S(ge,he){var me=ge&2147483648,we=he&2147483648,Ne=ge&1073741824,st=he&1073741824,He=(ge&1073741823)+(he&1073741823);return Ne&st?He^2147483648^me^we:Ne|st?He&1073741824?He^3221225472^me^we:He^1073741824^me^we:He^me^we}function E(ge,he,me){return ge&he|~ge&me}function A(ge,he,me){return ge&me|he&~me}function R(ge,he,me){return ge^he^me}function C(ge,he,me){return he^(ge|~me)}function H(ge,he,me,we,Ne,st,He){return ge=S(ge,S(S(E(he,me,we),Ne),He)),S(T(ge,st),he)}function k(ge,he,me,we,Ne,st,He){return ge=S(ge,S(S(A(he,me,we),Ne),He)),S(T(ge,st),he)}function re(ge,he,me,we,Ne,st,He){return ge=S(ge,S(S(R(he,me,we),Ne),He)),S(T(ge,st),he)}function x(ge,he,me,we,Ne,st,He){return ge=S(ge,S(S(C(he,me,we),Ne),He)),S(T(ge,st),he)}function F(ge){for(var he,me=ge.length,we=me+8,Ne=(we-we%64)/64,st=(Ne+1)*16,He=new Array(st-1),Vt=0,At=0;At<me;)he=(At-At%4)/4,Vt=At%4*8,He[he]=He[he]|ge.charCodeAt(At)<<Vt,At++;return he=(At-At%4)/4,Vt=At%4*8,He[he]=He[he]|128<<Vt,He[st-2]=me<<3,He[st-1]=me>>>29,He}function _e(ge){var he="",me="",we,Ne;for(Ne=0;Ne<=3;Ne++)we=ge>>>Ne*8&255,me="0".concat(we.toString(16)),he=he+me.substr(me.length-2,2);return he}function pe(ge){for(var he="",me=0;me<ge.length;me++){var we=ge.charCodeAt(me);we<128?he+=String.fromCharCode(we):we>127&&we<2048?(he+=String.fromCharCode(we>>6|192),he+=String.fromCharCode(we&63|128)):(he+=String.fromCharCode(we>>12|224),he+=String.fromCharCode(we>>6&63|128),he+=String.fromCharCode(we&63|128))}return he}var P=[],N,q,j,K,V,z,D,U,X,je=7,Q=12,W=17,B=22,ie=5,ve=9,Ie=14,Pe=20,Re=4,oe=11,ye=16,lt=23,at=6,Ee=10,Ce=15,be=21;for(g=pe(g),P=F(g),z=1732584193,D=4023233417,U=2562383102,X=271733878,N=0;N<P.length;N+=16)q=z,j=D,K=U,V=X,z=H(z,D,U,X,P[N+0],je,3614090360),X=H(X,z,D,U,P[N+1],Q,3905402710),U=H(U,X,z,D,P[N+2],W,606105819),D=H(D,U,X,z,P[N+3],B,3250441966),z=H(z,D,U,X,P[N+4],je,4118548399),X=H(X,z,D,U,P[N+5],Q,1200080426),U=H(U,X,z,D,P[N+6],W,2821735955),D=H(D,U,X,z,P[N+7],B,4249261313),z=H(z,D,U,X,P[N+8],je,1770035416),X=H(X,z,D,U,P[N+9],Q,2336552879),U=H(U,X,z,D,P[N+10],W,4294925233),D=H(D,U,X,z,P[N+11],B,2304563134),z=H(z,D,U,X,P[N+12],je,1804603682),X=H(X,z,D,U,P[N+13],Q,4254626195),U=H(U,X,z,D,P[N+14],W,2792965006),D=H(D,U,X,z,P[N+15],B,1236535329),z=k(z,D,U,X,P[N+1],ie,4129170786),X=k(X,z,D,U,P[N+6],ve,3225465664),U=k(U,X,z,D,P[N+11],Ie,643717713),D=k(D,U,X,z,P[N+0],Pe,3921069994),z=k(z,D,U,X,P[N+5],ie,3593408605),X=k(X,z,D,U,P[N+10],ve,38016083),U=k(U,X,z,D,P[N+15],Ie,3634488961),D=k(D,U,X,z,P[N+4],Pe,3889429448),z=k(z,D,U,X,P[N+9],ie,568446438),X=k(X,z,D,U,P[N+14],ve,3275163606),U=k(U,X,z,D,P[N+3],Ie,4107603335),D=k(D,U,X,z,P[N+8],Pe,1163531501),z=k(z,D,U,X,P[N+13],ie,2850285829),X=k(X,z,D,U,P[N+2],ve,4243563512),U=k(U,X,z,D,P[N+7],Ie,1735328473),D=k(D,U,X,z,P[N+12],Pe,2368359562),z=re(z,D,U,X,P[N+5],Re,4294588738),X=re(X,z,D,U,P[N+8],oe,2272392833),U=re(U,X,z,D,P[N+11],ye,1839030562),D=re(D,U,X,z,P[N+14],lt,4259657740),z=re(z,D,U,X,P[N+1],Re,2763975236),X=re(X,z,D,U,P[N+4],oe,1272893353),U=re(U,X,z,D,P[N+7],ye,4139469664),D=re(D,U,X,z,P[N+10],lt,3200236656),z=re(z,D,U,X,P[N+13],Re,681279174),X=re(X,z,D,U,P[N+0],oe,3936430074),U=re(U,X,z,D,P[N+3],ye,3572445317),D=re(D,U,X,z,P[N+6],lt,76029189),z=re(z,D,U,X,P[N+9],Re,3654602809),X=re(X,z,D,U,P[N+12],oe,3873151461),U=re(U,X,z,D,P[N+15],ye,530742520),D=re(D,U,X,z,P[N+2],lt,3299628645),z=x(z,D,U,X,P[N+0],at,4096336452),X=x(X,z,D,U,P[N+7],Ee,1126891415),U=x(U,X,z,D,P[N+14],Ce,2878612391),D=x(D,U,X,z,P[N+5],be,4237533241),z=x(z,D,U,X,P[N+12],at,1700485571),X=x(X,z,D,U,P[N+3],Ee,2399980690),U=x(U,X,z,D,P[N+10],Ce,4293915773),D=x(D,U,X,z,P[N+1],be,2240044497),z=x(z,D,U,X,P[N+8],at,1873313359),X=x(X,z,D,U,P[N+15],Ee,4264355552),U=x(U,X,z,D,P[N+6],Ce,2734768916),D=x(D,U,X,z,P[N+13],be,1309151649),z=x(z,D,U,X,P[N+4],at,4149444226),X=x(X,z,D,U,P[N+11],Ee,3174756917),U=x(U,X,z,D,P[N+2],Ce,718787259),D=x(D,U,X,z,P[N+9],be,3951481745),z=S(z,q),D=S(D,j),U=S(U,K),X=S(X,V);var Oe=_e(z)+_e(D)+_e(U)+_e(X);return Oe.toLowerCase()},Ze.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 A=E.value;A.stop()}}catch(F){S.e(F)}finally{S.f()}}else{T=g.getAudioTracks();var R=t(T),C;try{for(R.s();!(C=R.n()).done;){var H=C.value;H.stop()}}catch(F){R.e(F)}finally{R.f()}T=g.getVideoTracks();var k=t(T),re;try{for(k.s();!(re=k.n()).done;){var x=re.value;x.stop()}}catch(F){k.e(F)}finally{k.f()}}}catch{(typeof g.stop=="function"||c(g.stop)==="object")&&g.stop()}},Ze.cloneArray=function(g){return g&&g.slice()||[]},Ze.cloneObject=function(g){var T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return g&&Object.assign({},g)||T},Ze}var sa={exports:{}},Dn=typeof Reflect=="object"?Reflect:null,ec=Dn&&typeof Dn.apply=="function"?Dn.apply:function(t,n,o){return Function.prototype.apply.call(t,n,o)},Al;Dn&&typeof Dn.ownKeys=="function"?Al=Dn.ownKeys:Object.getOwnPropertySymbols?Al=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Al=function(t){return Object.getOwnPropertyNames(t)};function Kd(c){console&&console.warn&&console.warn(c)}var tc=Number.isNaN||function(t){return t!==t};function Le(){Le.init.call(this)}sa.exports=Le,sa.exports.once=Xd,Le.EventEmitter=Le,Le.prototype._events=void 0,Le.prototype._eventsCount=0,Le.prototype._maxListeners=void 0;var sc=10;function Rl(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 sc},set:function(c){if(typeof c!="number"||c<0||tc(c))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+c+".");sc=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||tc(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 nc(c){return c._maxListeners===void 0?Le.defaultMaxListeners:c._maxListeners}Le.prototype.getMaxListeners=function(){return nc(this)},Le.prototype.emit=function(t){for(var n=[],o=1;o<arguments.length;o++)n.push(arguments[o]);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 _=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw _.context=r,_}var d=s[t];if(d===void 0)return!1;if(typeof d=="function")ec(d,this,n);else for(var h=d.length,g=ac(d,h),o=0;o<h;++o)ec(g[o],this,n);return!0};function rc(c,t,n,o){var a,s,r;if(Rl(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]=o?[n,r]:[r,n]:o?r.unshift(n):r.push(n),a=nc(c),a>0&&r.length>a&&!r.warned){r.warned=!0;var _=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");_.name="MaxListenersExceededWarning",_.emitter=c,_.type=t,_.count=r.length,Kd(_)}return c}Le.prototype.addListener=function(t,n){return rc(this,t,n,!1)},Le.prototype.on=Le.prototype.addListener,Le.prototype.prependListener=function(t,n){return rc(this,t,n,!0)};function Yd(){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 ic(c,t,n){var o={fired:!1,wrapFn:void 0,target:c,type:t,listener:n},a=Yd.bind(o);return a.listener=n,o.wrapFn=a,a}Le.prototype.once=function(t,n){return Rl(n),this.on(t,ic(this,t,n)),this},Le.prototype.prependOnceListener=function(t,n){return Rl(n),this.prependListener(t,ic(this,t,n)),this},Le.prototype.removeListener=function(t,n){var o,a,s,r,_;if(Rl(n),a=this._events,a===void 0)return this;if(o=a[t],o===void 0)return this;if(o===n||o.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete a[t],a.removeListener&&this.emit("removeListener",t,o.listener||n));else if(typeof o!="function"){for(s=-1,r=o.length-1;r>=0;r--)if(o[r]===n||o[r].listener===n){_=o[r].listener,s=r;break}if(s<0)return this;s===0?o.shift():Jd(o,s),o.length===1&&(a[t]=o[0]),a.removeListener!==void 0&&this.emit("removeListener",t,_||n)}return this},Le.prototype.off=Le.prototype.removeListener,Le.prototype.removeAllListeners=function(t){var n,o,a;if(o=this._events,o===void 0)return this;if(o.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):o[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete o[t]),this;if(arguments.length===0){var s=Object.keys(o),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=o[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 lc(c,t,n){var o=c._events;if(o===void 0)return[];var a=o[t];return a===void 0?[]:typeof a=="function"?n?[a.listener||a]:[a]:n?zd(a):ac(a,a.length)}Le.prototype.listeners=function(t){return lc(this,t,!0)},Le.prototype.rawListeners=function(t){return lc(this,t,!1)},Le.listenerCount=function(c,t){return typeof c.listenerCount=="function"?c.listenerCount(t):oc.call(c,t)},Le.prototype.listenerCount=oc;function oc(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}Le.prototype.eventNames=function(){return this._eventsCount>0?Al(this._events):[]};function ac(c,t){for(var n=new Array(t),o=0;o<t;++o)n[o]=c[o];return n}function Jd(c,t){for(;t+1<c.length;t++)c[t]=c[t+1];c.pop()}function zd(c){for(var t=new Array(c.length),n=0;n<t.length;++n)t[n]=c[n].listener||c[n];return t}function Xd(c,t){return new Promise(function(n,o){function a(r){c.removeListener(t,s),o(r)}function s(){typeof c.removeListener=="function"&&c.removeListener("error",a),n([].slice.call(arguments))}uc(c,t,s,{once:!0}),t!=="error"&&Qd(c,a,{once:!0})})}function Qd(c,t,n){typeof c.on=="function"&&uc(c,"error",t,n)}function uc(c,t,n,o){if(typeof c.on=="function")o.once?c.once(t,n):c.on(t,n);else if(typeof c.addEventListener=="function")c.addEventListener(t,function a(s){o.once&&c.removeEventListener(t,a),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof c)}var ct=sa.exports,na={exports:{}},ra,cc;function Zd(){if(cc)return ra;cc=1;var c=1e3,t=c*60,n=t*60,o=n*24,a=o*7,s=o*365.25;ra=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):_(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*o;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 _(g){var T=Math.abs(g);return T>=o?Math.round(g/o)+"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>=o?h(g,T,o,"day"):T>=n?h(g,T,n,"hour"):T>=t?h(g,T,t,"minute"):T>=c?h(g,T,c,"second"):g+" ms"}function h(g,T,S,E){var A=T>=S*1.5;return Math.round(g/S)+" "+E+(A?"s":"")}return ra}function eh(c){n.debug=n,n.default=n,n.coerce=d,n.disable=s,n.enable=a,n.enabled=r,n.humanize=Zd(),n.destroy=h,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,A;function R(...C){if(!R.enabled)return;const H=R,k=Number(new Date),re=k-(T||k);H.diff=re,H.prev=T,H.curr=k,T=k,C[0]=n.coerce(C[0]),typeof C[0]!="string"&&C.unshift("%O");let x=0;C[0]=C[0].replace(/%([a-zA-Z%])/g,(_e,pe)=>{if(_e==="%%")return"%";x++;const P=n.formatters[pe];if(typeof P=="function"){const N=C[x];_e=P.call(H,N),C.splice(x,1),x--}return _e}),n.formatArgs.call(H,C),(H.log||n.log).apply(H,C)}return R.namespace=g,R.useColors=n.useColors(),R.color=n.selectColor(g),R.extend=o,R.destroy=n.destroy,Object.defineProperty(R,"enabled",{enumerable:!0,configurable:!1,get:()=>S!==null?S:(E!==n.namespaces&&(E=n.namespaces,A=n.enabled(g)),A),set:C=>{S=C}}),typeof n.init=="function"&&n.init(R),R}function o(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(_),...n.skips.map(_).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 _(g){return g.toString().substring(2,g.toString().length-2).replace(/\.\*\?$/,"*")}function d(g){return g instanceof Error?g.stack||g.message:g}function h(){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 th=eh;(function(c,t){t.formatArgs=o,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 o(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 h="color: "+this.color;d.splice(1,0,h,"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,h)}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=th(t);const{formatters:_}=c.exports;_.j=function(d){try{return JSON.stringify(d)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(na,na.exports);var Nn=na.exports;function sh(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function fc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function nh(c,t,n){return t&&fc(c.prototype,t),n&&fc(c,n),c}var xn=Nn,Un="JsSIP",ft=function(){function c(t){sh(this,c),t?(this._debug=xn.default("".concat(Un,":").concat(t)),this._warn=xn.default("".concat(Un,":WARN:").concat(t)),this._error=xn.default("".concat(Un,":ERROR:").concat(t))):(this._debug=xn.default(Un),this._warn=xn.default("".concat(Un,":WARN")),this._error=xn.default("".concat(Un,":ERROR"))),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}return nh(c,[{key:"debug",get:function(){return this._debug}},{key:"warn",get:function(){return this._warn}},{key:"error",get:function(){return this._error}}]),c}(),Nt={},dc={},hc={exports:{}},_c=hc.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(_c).forEach(function(c){var t=_c[c];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})});var pc=hc.exports;(function(c){var t=function(_){return String(Number(_))===_?Number(_):_},n=function(_,d,h,g){if(g&&!h)d[g]=t(_[1]);else for(var T=0;T<h.length;T+=1)_[T+1]!=null&&(d[h[T]]=t(_[T+1]))},o=function(_,d,h){var g=_.name&&_.names;_.push&&!d[_.push]?d[_.push]=[]:g&&!d[_.name]&&(d[_.name]={});var T=_.push?{}:g?d[_.name]:d;n(h.match(_.reg),T,_.names,_.name),_.push&&d[_.push].push(T)},a=pc,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);c.parse=function(_){var d={},h=[],g=d;return _.split(/(\r\n|\r|\n)/).filter(s).forEach(function(T){var S=T[0],E=T.slice(2);S==="m"&&(h.push({rtp:[],fmtp:[]}),g=h[h.length-1]);for(var A=0;A<(a[S]||[]).length;A+=1){var R=a[S][A];if(R.reg.test(E))return o(R,g,E)}}),d.media=h,d};var r=function(_,d){var h=d.split(/=(.+)/,2);return h.length===2?_[h[0]]=t(h[1]):h.length===1&&d.length>1&&(_[h[0]]=void 0),_};c.parseParams=function(_){return _.split(/;\s?/).reduce(r,{})},c.parseFmtpConfig=c.parseParams,c.parsePayloads=function(_){return _.toString().split(" ").map(Number)},c.parseRemoteCandidates=function(_){for(var d=[],h=_.split(" ").map(t),g=0;g<h.length;g+=3)d.push({component:h[g],ip:h[g+1],port:h[g+2]});return d},c.parseImageAttributes=function(_){return _.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(r,{})})},c.parseSimulcastStreamList=function(_){return _.split(";").map(function(d){return d.split(",").map(function(h){var g,T=!1;return h[0]!=="~"?g=t(h):(g=t(h.substring(1,h.length)),T=!0),{scid:g,paused:T}})})}})(dc);var ia=pc,rh=/%[sdv%]/g,ih=function(c){var t=1,n=arguments,o=n.length;return c.replace(rh,function(a){if(t>=o)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""}})},Cr=function(c,t,n){var o=t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format,a=[c+"="+o];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 ih.apply(null,a)},lh=["v","o","s","i","u","e","p","c","b","t","r","z","a"],oh=["i","c","b","a"],ah=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||lh,o=t.innerOrder||oh,a=[];return n.forEach(function(s){ia[s].forEach(function(r){r.name in c&&c[r.name]!=null?a.push(Cr(s,r,c)):r.push in c&&c[r.push]!=null&&c[r.push].forEach(function(_){a.push(Cr(s,r,_))})})}),c.media.forEach(function(s){a.push(Cr("m",ia.m[0],s)),o.forEach(function(r){ia[r].forEach(function(_){_.name in s&&s[_.name]!=null?a.push(Cr(r,_,s)):_.push in s&&s[_.push]!=null&&s[_.push].forEach(function(d){a.push(Cr(r,_,d))})})})}),a.join(`\r
3
+ `,r+=2):(e=null,h('"\\r\\n"')),e}function T(){var e;return/^[0-9]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[0-9]")),e}function S(){var e;return/^[a-zA-Z]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[a-zA-Z]")),e}function E(){var e;return/^[0-9a-fA-F]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[0-9a-fA-F]")),e}function A(){var e;return e=H(),e===null&&(e=k()),e}function R(){var e;return/^[\0-\xFF]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\0-\\xFF]")),e}function C(){var e;return/^["]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h('["]')),e}function H(){var e;return o.charCodeAt(r)===32?(e=" ",r++):(e=null,h('" "')),e}function k(){var e;return o.charCodeAt(r)===9?(e=" ",r++):(e=null,h('"\\t"')),e}function re(){var e;return/^[a-zA-Z0-9]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[a-zA-Z0-9]")),e}function x(){var e;return o.charCodeAt(r)===59?(e=";",r++):(e=null,h('";"')),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===64?(e="@",r++):(e=null,h('"@"')),e===null&&(o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","'))))))))))),e}function F(){var e;return e=re(),e===null&&(e=_e()),e}function _e(){var e;return o.charCodeAt(r)===45?(e="-",r++):(e=null,h('"-"')),e===null&&(o.charCodeAt(r)===95?(e="_",r++):(e=null,h('"_"')),e===null&&(o.charCodeAt(r)===46?(e=".",r++):(e=null,h('"."')),e===null&&(o.charCodeAt(r)===33?(e="!",r++):(e=null,h('"!"')),e===null&&(o.charCodeAt(r)===126?(e="~",r++):(e=null,h('"~"')),e===null&&(o.charCodeAt(r)===42?(e="*",r++):(e=null,h('"*"')),e===null&&(o.charCodeAt(r)===39?(e="'",r++):(e=null,h(`"'"`)),e===null&&(o.charCodeAt(r)===40?(e="(",r++):(e=null,h('"("')),e===null&&(o.charCodeAt(r)===41?(e=")",r++):(e=null,h('")"')))))))))),e}function pe(){var e,l,u,f,p;return f=r,p=r,o.charCodeAt(r)===37?(e="%",r++):(e=null,h('"%"')),e!==null?(l=E(),l!==null?(u=E(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){return v.join("")}(f,e)),e===null&&(r=f),e}function P(){var e,l,u,f,p,g;for(f=r,p=r,g=r,e=[],l=A();l!==null;)e.push(l),l=A();if(e!==null?(l=m(),l!==null?e=[e,l]:(e=null,r=g)):(e=null,r=g),e=e!==null?e:"",e!==null){if(u=A(),u!==null)for(l=[];u!==null;)l.push(u),u=A();else l=null;l!==null?e=[e,l]:(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,l,u,f,p;for(f=r,p=r,e=[],l=H(),l===null&&(l=k());l!==null;)e.push(l),l=H(),l===null&&(l=k());return e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=N(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return":"}()),e===null&&(r=f),e}function j(){var e,l,u,f,p,g,v;if(p=r,g=r,l=K(),l!==null)for(e=[];l!==null;)e.push(l),l=K();else e=null;if(e!==null){for(l=[],v=r,u=[],f=P();f!==null;)u.push(f),f=P();for(u!==null?(f=K(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;){for(l.push(u),v=r,u=[],f=P();f!==null;)u.push(f),f=P();u!==null?(f=K(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v)}l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y){return o.substring(r,y)}(p)),e===null&&(r=p),e}function K(){var e;return/^[!-~]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[!-~]")),e===null&&(e=V()),e}function V(){var e;return/^[\x80-\uFFFF]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\x80-\\uFFFF]")),e}function z(){var e;return/^[\x80-\xBF]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\x80-\\xBF]")),e}function D(){var e;return e=T(),e===null&&(/^[a-f]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[a-f]"))),e}function U(){var e,l,u;if(u=r,l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"')))))))))))),l!==null)for(e=[];l!==null;)e.push(l),l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"'))))))))))));else e=null;return e!==null&&(e=function(f){return o.substring(r,f)}(u)),e===null&&(r=u),e}function X(){var e,l,u;if(u=r,l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"'))))))))))),l!==null)for(e=[];l!==null;)e.push(l),l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"')))))))))));else e=null;return e!==null&&(e=function(f){return o.substring(r,f)}(u)),e===null&&(r=u),e}function je(){var e;return o.charCodeAt(r)===40?(e="(",r++):(e=null,h('"("')),e===null&&(o.charCodeAt(r)===41?(e=")",r++):(e=null,h('")"')),e===null&&(o.charCodeAt(r)===60?(e="<",r++):(e=null,h('"<"')),e===null&&(o.charCodeAt(r)===62?(e=">",r++):(e=null,h('">"')),e===null&&(o.charCodeAt(r)===64?(e="@",r++):(e=null,h('"@"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","')),e===null&&(o.charCodeAt(r)===59?(e=";",r++):(e=null,h('";"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===92?(e="\\",r++):(e=null,h('"\\\\"')),e===null&&(e=C(),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e===null&&(o.charCodeAt(r)===91?(e="[",r++):(e=null,h('"["')),e===null&&(o.charCodeAt(r)===93?(e="]",r++):(e=null,h('"]"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===123?(e="{",r++):(e=null,h('"{"')),e===null&&(o.charCodeAt(r)===125?(e="}",r++):(e=null,h('"}"')),e===null&&(e=H(),e===null&&(e=k())))))))))))))))))),e}function Q(){var e,l,u;if(u=r,l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"')),l===null&&(o.charCodeAt(r)===40?(l="(",r++):(l=null,h('"("')),l===null&&(o.charCodeAt(r)===41?(l=")",r++):(l=null,h('")"')),l===null&&(o.charCodeAt(r)===60?(l="<",r++):(l=null,h('"<"')),l===null&&(o.charCodeAt(r)===62?(l=">",r++):(l=null,h('">"')),l===null&&(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l===null&&(o.charCodeAt(r)===92?(l="\\",r++):(l=null,h('"\\\\"')),l===null&&(l=C(),l===null&&(o.charCodeAt(r)===47?(l="/",r++):(l=null,h('"/"')),l===null&&(o.charCodeAt(r)===91?(l="[",r++):(l=null,h('"["')),l===null&&(o.charCodeAt(r)===93?(l="]",r++):(l=null,h('"]"')),l===null&&(o.charCodeAt(r)===63?(l="?",r++):(l=null,h('"?"')),l===null&&(o.charCodeAt(r)===123?(l="{",r++):(l=null,h('"{"')),l===null&&(o.charCodeAt(r)===125?(l="}",r++):(l=null,h('"}"'))))))))))))))))))))))))),l!==null)for(e=[];l!==null;)e.push(l),l=re(),l===null&&(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l===null&&(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l===null&&(o.charCodeAt(r)===33?(l="!",r++):(l=null,h('"!"')),l===null&&(o.charCodeAt(r)===37?(l="%",r++):(l=null,h('"%"')),l===null&&(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l===null&&(o.charCodeAt(r)===95?(l="_",r++):(l=null,h('"_"')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===96?(l="`",r++):(l=null,h('"`"')),l===null&&(o.charCodeAt(r)===39?(l="'",r++):(l=null,h(`"'"`)),l===null&&(o.charCodeAt(r)===126?(l="~",r++):(l=null,h('"~"')),l===null&&(o.charCodeAt(r)===40?(l="(",r++):(l=null,h('"("')),l===null&&(o.charCodeAt(r)===41?(l=")",r++):(l=null,h('")"')),l===null&&(o.charCodeAt(r)===60?(l="<",r++):(l=null,h('"<"')),l===null&&(o.charCodeAt(r)===62?(l=">",r++):(l=null,h('">"')),l===null&&(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l===null&&(o.charCodeAt(r)===92?(l="\\",r++):(l=null,h('"\\\\"')),l===null&&(l=C(),l===null&&(o.charCodeAt(r)===47?(l="/",r++):(l=null,h('"/"')),l===null&&(o.charCodeAt(r)===91?(l="[",r++):(l=null,h('"["')),l===null&&(o.charCodeAt(r)===93?(l="]",r++):(l=null,h('"]"')),l===null&&(o.charCodeAt(r)===63?(l="?",r++):(l=null,h('"?"')),l===null&&(o.charCodeAt(r)===123?(l="{",r++):(l=null,h('"{"')),l===null&&(o.charCodeAt(r)===125?(l="}",r++):(l=null,h('"}"')))))))))))))))))))))))));else e=null;return e!==null&&(e=function(f){return o.substring(r,f)}(u)),e===null&&(r=u),e}function W(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===42?(l="*",r++):(l=null,h('"*"')),l!==null?(u=N(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return"*"}()),e===null&&(r=f),e}function B(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===47?(l="/",r++):(l=null,h('"/"')),l!==null?(u=N(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return"/"}()),e===null&&(r=f),e}function ie(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l!==null?(u=N(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return"="}()),e===null&&(r=f),e}function ve(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===40?(l="(",r++):(l=null,h('"("')),l!==null?(u=N(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return"("}()),e===null&&(r=f),e}function Ie(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===41?(l=")",r++):(l=null,h('")"')),l!==null?(u=N(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return")"}()),e===null&&(r=f),e}function Pe(){var e,l,u,f;return u=r,f=r,o.charCodeAt(r)===62?(e=">",r++):(e=null,h('">"')),e!==null?(l=N(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return">"}()),e===null&&(r=u),e}function Re(){var e,l,u,f;return u=r,f=r,e=N(),e!==null?(o.charCodeAt(r)===60?(l="<",r++):(l=null,h('"<"')),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return"<"}()),e===null&&(r=u),e}function oe(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","')),l!==null?(u=N(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return","}()),e===null&&(r=f),e}function ye(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l!==null?(u=N(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return";"}()),e===null&&(r=f),e}function lt(){var e,l,u,f,p;return f=r,p=r,e=N(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=N(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return":"}()),e===null&&(r=f),e}function at(){var e,l,u,f;return u=r,f=r,e=N(),e!==null?(l=C(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return'"'}()),e===null&&(r=u),e}function Ee(){var e,l,u,f;return u=r,f=r,e=C(),e!==null?(l=N(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p){return'"'}()),e===null&&(r=u),e}function Ce(){var e,l,u,f;if(f=r,e=ve(),e!==null){for(l=[],u=be(),u===null&&(u=ge(),u===null&&(u=Ce()));u!==null;)l.push(u),u=be(),u===null&&(u=ge(),u===null&&(u=Ce()));l!==null?(u=Ie(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)}else e=null,r=f;return e}function be(){var e;return/^[!-']/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[!-']")),e===null&&(/^[*-[]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[*-[]")),e===null&&(/^[\]-~]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\]-~]")),e===null&&(e=V(),e===null&&(e=P())))),e}function Oe(){var e,l,u,f,p,g;if(p=r,g=r,e=N(),e!==null)if(l=C(),l!==null){for(u=[],f=he(),f===null&&(f=ge());f!==null;)u.push(f),f=he(),f===null&&(f=ge());u!==null?(f=C(),f!==null?e=[e,l,u,f]:(e=null,r=g)):(e=null,r=g)}else e=null,r=g;else e=null,r=g;return e!==null&&(e=function(v){return o.substring(r,v)}(p)),e===null&&(r=p),e}function me(){var e,l,u,f,p,g;if(p=r,g=r,e=N(),e!==null)if(l=C(),l!==null){for(u=[],f=he(),f===null&&(f=ge());f!==null;)u.push(f),f=he(),f===null&&(f=ge());u!==null?(f=C(),f!==null?e=[e,l,u,f]:(e=null,r=g)):(e=null,r=g)}else e=null,r=g;else e=null,r=g;return e!==null&&(e=function(v){var y=o.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 he(){var e;return e=P(),e===null&&(o.charCodeAt(r)===33?(e="!",r++):(e=null,h('"!"')),e===null&&(/^[#-[]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[#-[]")),e===null&&(/^[\]-~]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[\\]-~]")),e===null&&(e=V())))),e}function ge(){var e,l,u;return u=r,o.charCodeAt(r)===92?(e="\\",r++):(e=null,h('"\\\\"')),e!==null?(/^[\0-\t]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[\\0-\\t]")),l===null&&(/^[\x0B-\f]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[\\x0B-\\f]")),l===null&&(/^[\x0E-]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[\\x0E-]")))),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function we(){var e,l,u,f,p,g;return p=r,g=r,e=st(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=At(),u=u!==null?u:"",u!==null?(f=ls(),f!==null?e=[e,l,u,f]:(e=null,r=g)):(e=null,r=g)):(e=null,r=g)):(e=null,r=g),e!==null&&(e=function(v){try{w.uri=new Rs(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}}()),e===null&&(r=p),e}function Ne(){var e,l,u,f,p,g,v,y;return v=r,y=r,e=st(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=At(),u=u!==null?u:"",u!==null?(f=ls(),f!==null?(p=Kn(),p!==null?(g=dn(),g=g!==null?g:"",g!==null?e=[e,l,u,f,p,g]:(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(O){try{w.uri=new Rs(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,a==="SIP_URI"&&(w=w.uri)}catch{w=-1}}()),e===null&&(r=v),e}function st(){var e;return e=He(),e===null&&(e=Vt()),e}function He(){var e,l;return l=r,o.substr(r,4).toLowerCase()==="sips"?(e=o.substr(r,4),r+=4):(e=null,h('"sips"')),e!==null&&(e=function(u,f){w.scheme=f.toLowerCase()}(l,e)),e===null&&(r=l),e}function Vt(){var e,l;return l=r,o.substr(r,3).toLowerCase()==="sip"?(e=o.substr(r,3),r+=3):(e=null,h('"sip"')),e!==null&&(e=function(u,f){w.scheme=f.toLowerCase()}(l,e)),e===null&&(r=l),e}function At(){var e,l,u,f,p,g;return f=r,p=r,e=qn(),e!==null?(g=r,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=un(),u!==null?l=[l,u]:(l=null,r=g)):(l=null,r=g),l=l!==null?l:"",l!==null?(o.charCodeAt(r)===64?(u="@",r++):(u=null,h('"@"')),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){w.user=decodeURIComponent(o.substring(r-1,v))}(f)),e===null&&(r=f),e}function qn(){var e,l;if(l=F(),l===null&&(l=pe(),l===null&&(l=Bn())),l!==null)for(e=[];l!==null;)e.push(l),l=F(),l===null&&(l=pe(),l===null&&(l=Bn()));else e=null;return e}function Bn(){var e;return o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","')),e===null&&(o.charCodeAt(r)===59?(e=";",r++):(e=null,h('";"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"'))))))))),e}function un(){var e,l,u;for(u=r,e=[],l=F(),l===null&&(l=pe(),l===null&&(o.charCodeAt(r)===38?(l="&",r++):(l=null,h('"&"')),l===null&&(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===36?(l="$",r++):(l=null,h('"$"')),l===null&&(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","'))))))));l!==null;)e.push(l),l=F(),l===null&&(l=pe(),l===null&&(o.charCodeAt(r)===38?(l="&",r++):(l=null,h('"&"')),l===null&&(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')),l===null&&(o.charCodeAt(r)===36?(l="$",r++):(l=null,h('"$"')),l===null&&(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","'))))))));return e!==null&&(e=function(f){w.password=o.substring(r,f)}(u)),e===null&&(r=u),e}function ls(){var e,l,u,f,p;return f=r,e=Cs(),e!==null?(p=r,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ai(),u!==null?l=[l,u]:(l=null,r=p)):(l=null,r=p),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e}function Cs(){var e,l;return l=r,e=cn(),e===null&&(e=Zt(),e===null&&(e=fn())),e!==null&&(e=function(u){return w.host=o.substring(r,u).toLowerCase(),w.host}(l)),e===null&&(r=l),e}function cn(){var e,l,u,f,p,g;for(f=r,p=r,e=[],g=r,l=Gn(),l!==null?(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u!==null?l=[l,u]:(l=null,r=g)):(l=null,r=g);l!==null;)e.push(l),g=r,l=Gn(),l!==null?(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u!==null?l=[l,u]:(l=null,r=g)):(l=null,r=g);return e!==null?(l=Wn(),l!==null?(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u=u!==null?u:"",u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){return w.host_type="domain",o.substring(r,v)}(f)),e===null&&(r=f),e}function Gn(){var e,l,u,f;if(f=r,e=re(),e!==null){for(l=[],u=re(),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===95?(u="_",r++):(u=null,h('"_"'))));u!==null;)l.push(u),u=re(),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===95?(u="_",r++):(u=null,h('"_"'))));l!==null?e=[e,l]:(e=null,r=f)}else e=null,r=f;return e}function Wn(){var e,l,u,f;if(f=r,e=S(),e!==null){for(l=[],u=re(),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===95?(u="_",r++):(u=null,h('"_"'))));u!==null;)l.push(u),u=re(),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===95?(u="_",r++):(u=null,h('"_"'))));l!==null?e=[e,l]:(e=null,r=f)}else e=null,r=f;return e}function fn(){var e,l,u,f,p;return f=r,p=r,o.charCodeAt(r)===91?(e="[",r++):(e=null,h('"["')),e!==null?(l=Te(),l!==null?(o.charCodeAt(r)===93?(u="]",r++):(u=null,h('"]"')),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g){return w.host_type="IPv6",o.substring(r,g)}(f)),e===null&&(r=f),e}function Te(){var e,l,u,f,p,g,v,y,O,le,xe,Dt,Js,L,b,Se;return L=r,b=r,e=ae(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?(o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),f!==null?(p=ae(),p!==null?(o.charCodeAt(r)===58?(g=":",r++):(g=null,h('":"')),g!==null?(v=ae(),v!==null?(o.charCodeAt(r)===58?(y=":",r++):(y=null,h('":"')),y!==null?(O=ae(),O!==null?(o.charCodeAt(r)===58?(le=":",r++):(le=null,h('":"')),le!==null?(xe=ae(),xe!==null?(o.charCodeAt(r)===58?(Dt=":",r++):(Dt=null,h('":"')),Dt!==null?(Js=ut(),Js!==null?e=[e,l,u,f,p,g,v,y,O,le,xe,Dt,Js]:(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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(g=ae(),g!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ae(),y!==null?(o.charCodeAt(r)===58?(O=":",r++):(O=null,h('":"')),O!==null?(le=ae(),le!==null?(o.charCodeAt(r)===58?(xe=":",r++):(xe=null,h('":"')),xe!==null?(Dt=ut(),Dt!==null?e=[e,l,u,f,p,g,v,y,O,le,xe,Dt]:(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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(g=ae(),g!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ae(),y!==null?(o.charCodeAt(r)===58?(O=":",r++):(O=null,h('":"')),O!==null?(le=ut(),le!==null?e=[e,l,u,f,p,g,v,y,O,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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(g=ae(),g!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ut(),y!==null?e=[e,l,u,f,p,g,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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(g=ut(),g!==null?e=[e,l,u,f,p,g]:(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,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?(o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ut(),f!==null?e=[e,l,u,f]:(e=null,r=b)):(e=null,r=b)):(e=null,r=b)):(e=null,r=b),e===null&&(b=r,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ut(),l!==null?e=[e,l]:(e=null,r=b)):(e=null,r=b),e===null&&(b=r,o.substr(r,2)==="::"?(e="::",r+=2):(e=null,h('"::"')),e!==null?(l=ae(),l!==null?e=[e,l]:(e=null,r=b)):(e=null,r=b),e===null&&(b=r,e=ae(),e!==null?(o.substr(r,2)==="::"?(l="::",r+=2):(l=null,h('"::"')),l!==null?(u=ae(),u!==null?(o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),f!==null?(p=ae(),p!==null?(o.charCodeAt(r)===58?(g=":",r++):(g=null,h('":"')),g!==null?(v=ae(),v!==null?(o.charCodeAt(r)===58?(y=":",r++):(y=null,h('":"')),y!==null?(O=ae(),O!==null?(o.charCodeAt(r)===58?(le=":",r++):(le=null,h('":"')),le!==null?(xe=ut(),xe!==null?e=[e,l,u,f,p,g,v,y,O,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(o.substr(r,2)==="::"?(u="::",r+=2):(u=null,h('"::"')),u!==null?(f=ae(),f!==null?(o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(g=ae(),g!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ae(),y!==null?(o.charCodeAt(r)===58?(O=":",r++):(O=null,h('":"')),O!==null?(le=ut(),le!==null?e=[e,l,u,f,p,g,v,y,O,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),u!==null?(f=ae(),f!==null?u=[u,f]:(u=null,r=Se)):(u=null,r=Se),u=u!==null?u:"",u!==null?(o.substr(r,2)==="::"?(f="::",r+=2):(f=null,h('"::"')),f!==null?(p=ae(),p!==null?(o.charCodeAt(r)===58?(g=":",r++):(g=null,h('":"')),g!==null?(v=ae(),v!==null?(o.charCodeAt(r)===58?(y=":",r++):(y=null,h('":"')),y!==null?(O=ut(),O!==null?e=[e,l,u,f,p,g,v,y,O]:(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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),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,o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),f!==null?(p=ae(),p!==null?f=[f,p]:(f=null,r=Se)):(f=null,r=Se),f=f!==null?f:"",f!==null?(o.substr(r,2)==="::"?(p="::",r+=2):(p=null,h('"::"')),p!==null?(g=ae(),g!==null?(o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ut(),y!==null?e=[e,l,u,f,p,g,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),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,o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),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,o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(g=ae(),g!==null?p=[p,g]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(o.substr(r,2)==="::"?(g="::",r+=2):(g=null,h('"::"')),g!==null?(v=ut(),v!==null?e=[e,l,u,f,p,g,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),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,o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),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,o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(g=ae(),g!==null?p=[p,g]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(Se=r,o.charCodeAt(r)===58?(g=":",r++):(g=null,h('":"')),g!==null?(v=ae(),v!==null?g=[g,v]:(g=null,r=Se)):(g=null,r=Se),g=g!==null?g:"",g!==null?(o.substr(r,2)==="::"?(v="::",r+=2):(v=null,h('"::"')),v!==null?(y=ae(),y!==null?e=[e,l,u,f,p,g,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,o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?l=[l,u]:(l=null,r=Se)):(l=null,r=Se),l=l!==null?l:"",l!==null?(Se=r,o.charCodeAt(r)===58?(u=":",r++):(u=null,h('":"')),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,o.charCodeAt(r)===58?(f=":",r++):(f=null,h('":"')),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,o.charCodeAt(r)===58?(p=":",r++):(p=null,h('":"')),p!==null?(g=ae(),g!==null?p=[p,g]:(p=null,r=Se)):(p=null,r=Se),p=p!==null?p:"",p!==null?(Se=r,o.charCodeAt(r)===58?(g=":",r++):(g=null,h('":"')),g!==null?(v=ae(),v!==null?g=[g,v]:(g=null,r=Se)):(g=null,r=Se),g=g!==null?g:"",g!==null?(Se=r,o.charCodeAt(r)===58?(v=":",r++):(v=null,h('":"')),v!==null?(y=ae(),y!==null?v=[v,y]:(v=null,r=Se)):(v=null,r=Se),v=v!==null?v:"",v!==null?(o.substr(r,2)==="::"?(y="::",r+=2):(y=null,h('"::"')),y!==null?e=[e,l,u,f,p,g,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(Qv){return w.host_type="IPv6",o.substring(r,Qv)}(L)),e===null&&(r=L),e}function ae(){var e,l,u,f,p;return p=r,e=E(),e!==null?(l=E(),l=l!==null?l:"",l!==null?(u=E(),u=u!==null?u:"",u!==null?(f=E(),f=f!==null?f:"",f!==null?e=[e,l,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function ut(){var e,l,u,f;return f=r,e=ae(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=ae(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(e=Zt()),e}function Zt(){var e,l,u,f,p,g,v,y,O;return y=r,O=r,e=$s(),e!==null?(o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l!==null?(u=$s(),u!==null?(o.charCodeAt(r)===46?(f=".",r++):(f=null,h('"."')),f!==null?(p=$s(),p!==null?(o.charCodeAt(r)===46?(g=".",r++):(g=null,h('"."')),g!==null?(v=$s(),v!==null?e=[e,l,u,f,p,g,v]:(e=null,r=O)):(e=null,r=O)):(e=null,r=O)):(e=null,r=O)):(e=null,r=O)):(e=null,r=O)):(e=null,r=O),e!==null&&(e=function(le){return w.host_type="IPv4",o.substring(r,le)}(y)),e===null&&(r=y),e}function $s(){var e,l,u,f;return f=r,o.substr(r,2)==="25"?(e="25",r+=2):(e=null,h('"25"')),e!==null?(/^[0-5]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[0-5]")),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e===null&&(f=r,o.charCodeAt(r)===50?(e="2",r++):(e=null,h('"2"')),e!==null?(/^[0-4]/.test(o.charAt(r))?(l=o.charAt(r),r++):(l=null,h("[0-4]")),l!==null?(u=T(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(f=r,o.charCodeAt(r)===49?(e="1",r++):(e=null,h('"1"')),e!==null?(l=T(),l!==null?(u=T(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e===null&&(f=r,/^[1-9]/.test(o.charAt(r))?(e=o.charAt(r),r++):(e=null,h("[1-9]")),e!==null?(l=T(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e===null&&(e=T())))),e}function ai(){var e,l,u,f,p,g,v;return g=r,v=r,e=T(),e=e!==null?e:"",e!==null?(l=T(),l=l!==null?l:"",l!==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,l,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,O){return O=parseInt(O.join("")),w.port=O,O}(g,e)),e===null&&(r=g),e}function Kn(){var e,l,u,f;for(e=[],f=r,o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l!==null?(u=Yn(),u!==null?l=[l,u]:(l=null,r=f)):(l=null,r=f);l!==null;)e.push(l),f=r,o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l!==null?(u=Yn(),u!==null?l=[l,u]:(l=null,r=f)):(l=null,r=f);return e}function Yn(){var e;return e=ui(),e===null&&(e=ci(),e===null&&(e=fi(),e===null&&(e=di(),e===null&&(e=hi(),e===null&&(e=_i(),e===null&&(e=pi())))))),e}function ui(){var e,l,u,f;return u=r,f=r,o.substr(r,10).toLowerCase()==="transport="?(e=o.substr(r,10),r+=10):(e=null,h('"transport="')),e!==null?(o.substr(r,3).toLowerCase()==="udp"?(l=o.substr(r,3),r+=3):(l=null,h('"udp"')),l===null&&(o.substr(r,3).toLowerCase()==="tcp"?(l=o.substr(r,3),r+=3):(l=null,h('"tcp"')),l===null&&(o.substr(r,4).toLowerCase()==="sctp"?(l=o.substr(r,4),r+=4):(l=null,h('"sctp"')),l===null&&(o.substr(r,3).toLowerCase()==="tls"?(l=o.substr(r,3),r+=3):(l=null,h('"tls"')),l===null&&(l=U())))),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,g){w.uri_params||(w.uri_params={}),w.uri_params.transport=g.toLowerCase()}(u,e[1])),e===null&&(r=u),e}function ci(){var e,l,u,f;return u=r,f=r,o.substr(r,5).toLowerCase()==="user="?(e=o.substr(r,5),r+=5):(e=null,h('"user="')),e!==null?(o.substr(r,5).toLowerCase()==="phone"?(l=o.substr(r,5),r+=5):(l=null,h('"phone"')),l===null&&(o.substr(r,2).toLowerCase()==="ip"?(l=o.substr(r,2),r+=2):(l=null,h('"ip"')),l===null&&(l=U())),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,g){w.uri_params||(w.uri_params={}),w.uri_params.user=g.toLowerCase()}(u,e[1])),e===null&&(r=u),e}function fi(){var e,l,u,f;return u=r,f=r,o.substr(r,7).toLowerCase()==="method="?(e=o.substr(r,7),r+=7):(e=null,h('"method="')),e!==null?(l=vn(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,g){w.uri_params||(w.uri_params={}),w.uri_params.method=g}(u,e[1])),e===null&&(r=u),e}function di(){var e,l,u,f;return u=r,f=r,o.substr(r,4).toLowerCase()==="ttl="?(e=o.substr(r,4),r+=4):(e=null,h('"ttl="')),e!==null?(l=dl(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,g){w.params||(w.params={}),w.params.ttl=g}(u,e[1])),e===null&&(r=u),e}function hi(){var e,l,u,f;return u=r,f=r,o.substr(r,6).toLowerCase()==="maddr="?(e=o.substr(r,6),r+=6):(e=null,h('"maddr="')),e!==null?(l=Cs(),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e!==null&&(e=function(p,g){w.uri_params||(w.uri_params={}),w.uri_params.maddr=g}(u,e[1])),e===null&&(r=u),e}function _i(){var e,l,u,f,p,g;return f=r,p=r,o.substr(r,2).toLowerCase()==="lr"?(e=o.substr(r,2),r+=2):(e=null,h('"lr"')),e!==null?(g=r,o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,r=g)):(l=null,r=g),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){w.uri_params||(w.uri_params={}),w.uri_params.lr=void 0}()),e===null&&(r=f),e}function pi(){var e,l,u,f,p,g;return f=r,p=r,e=gi(),e!==null?(g=r,o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l!==null?(u=Hs(),u!==null?l=[l,u]:(l=null,r=g)):(l=null,r=g),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v,y,O){w.uri_params||(w.uri_params={}),typeof O>"u"?O=void 0:O=O[1],w.uri_params[y.toLowerCase()]=O}(f,e[0],e[1])),e===null&&(r=f),e}function gi(){var e,l,u;if(u=r,l=Fs(),l!==null)for(e=[];l!==null;)e.push(l),l=Fs();else e=null;return e!==null&&(e=function(f,p){return p.join("")}(u,e)),e===null&&(r=u),e}function Hs(){var e,l,u;if(u=r,l=Fs(),l!==null)for(e=[];l!==null;)e.push(l),l=Fs();else e=null;return e!==null&&(e=function(f,p){return p.join("")}(u,e)),e===null&&(r=u),e}function Fs(){var e;return e=mi(),e===null&&(e=F(),e===null&&(e=pe())),e}function mi(){var e;return o.charCodeAt(r)===91?(e="[",r++):(e=null,h('"["')),e===null&&(o.charCodeAt(r)===93?(e="]",r++):(e=null,h('"]"')),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')))))))),e}function dn(){var e,l,u,f,p,g,v;if(g=r,o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e!==null)if(l=hn(),l!==null){for(u=[],v=r,o.charCodeAt(r)===38?(f="&",r++):(f=null,h('"&"')),f!==null?(p=hn(),p!==null?f=[f,p]:(f=null,r=v)):(f=null,r=v);f!==null;)u.push(f),v=r,o.charCodeAt(r)===38?(f="&",r++):(f=null,h('"&"')),f!==null?(p=hn(),p!==null?f=[f,p]:(f=null,r=v)):(f=null,r=v);u!==null?e=[e,l,u]:(e=null,r=g)}else e=null,r=g;else e=null,r=g;return e}function hn(){var e,l,u,f,p;return f=r,p=r,e=Ti(),e!==null?(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l!==null?(u=Vs(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v,y){v=v.join("").toLowerCase(),y=y.join(""),w.uri_headers||(w.uri_headers={}),w.uri_headers[v]?w.uri_headers[v].push(y):w.uri_headers[v]=[y]}(f,e[0],e[2])),e===null&&(r=f),e}function Ti(){var e,l;if(l=_n(),l===null&&(l=F(),l===null&&(l=pe())),l!==null)for(e=[];l!==null;)e.push(l),l=_n(),l===null&&(l=F(),l===null&&(l=pe()));else e=null;return e}function Vs(){var e,l;for(e=[],l=_n(),l===null&&(l=F(),l===null&&(l=pe()));l!==null;)e.push(l),l=_n(),l===null&&(l=F(),l===null&&(l=pe()));return e}function _n(){var e;return o.charCodeAt(r)===91?(e="[",r++):(e=null,h('"["')),e===null&&(o.charCodeAt(r)===93?(e="]",r++):(e=null,h('"]"')),e===null&&(o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')))))))),e}function Do(){var e;return e=ki(),e===null&&(e=vi()),e}function vi(){var e,l,u,f,p,g;return g=r,e=vn(),e!==null?(l=H(),l!==null?(u=Jn(),u!==null?(f=H(),f!==null?(p=Qn(),p!==null?e=[e,l,u,f,p]:(e=null,r=g)):(e=null,r=g)):(e=null,r=g)):(e=null,r=g)):(e=null,r=g),e}function Jn(){var e;return e=Ne(),e===null&&(e=zn()),e}function zn(){var e,l,u,f;return f=r,e=yi(),e!==null?(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l!==null?(u=Si(),u===null&&(u=js()),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Si(){var e,l,u,f,p;return f=r,e=pn(),e===null&&(e=gn()),e!==null?(p=r,o.charCodeAt(r)===63?(l="?",r++):(l=null,h('"?"')),l!==null?(u=Xn(),u!==null?l=[l,u]:(l=null,r=p)):(l=null,r=p),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e}function pn(){var e,l,u,f;return f=r,o.substr(r,2)==="//"?(e="//",r+=2):(e=null,h('"//"')),e!==null?(l=Ci(),l!==null?(u=gn(),u=u!==null?u:"",u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function gn(){var e,l,u;return u=r,o.charCodeAt(r)===47?(e="/",r++):(e=null,h('"/"')),e!==null?(l=mn(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function js(){var e,l,u,f;if(f=r,e=Ei(),e!==null){for(l=[],u=qs();u!==null;)l.push(u),u=qs();l!==null?e=[e,l]:(e=null,r=f)}else e=null,r=f;return e}function qs(){var e;return e=x(),e===null&&(e=F(),e===null&&(e=pe())),e}function Ei(){var e;return e=F(),e===null&&(e=pe(),e===null&&(o.charCodeAt(r)===59?(e=";",r++):(e=null,h('";"')),e===null&&(o.charCodeAt(r)===63?(e="?",r++):(e=null,h('"?"')),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===64?(e="@",r++):(e=null,h('"@"')),e===null&&(o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","')))))))))))),e}function mn(){var e,l,u,f,p,g;if(p=r,e=Bs(),e!==null){for(l=[],g=r,o.charCodeAt(r)===47?(u="/",r++):(u=null,h('"/"')),u!==null?(f=Bs(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,o.charCodeAt(r)===47?(u="/",r++):(u=null,h('"/"')),u!==null?(f=Bs(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function Bs(){var e,l,u,f,p,g;for(p=r,e=[],l=Gs();l!==null;)e.push(l),l=Gs();if(e!==null){for(l=[],g=r,o.charCodeAt(r)===59?(u=";",r++):(u=null,h('";"')),u!==null?(f=As(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,o.charCodeAt(r)===59?(u=";",r++):(u=null,h('";"')),u!==null?(f=As(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function As(){var e,l;for(e=[],l=Gs();l!==null;)e.push(l),l=Gs();return e}function Gs(){var e;return e=F(),e===null&&(e=pe(),e===null&&(o.charCodeAt(r)===58?(e=":",r++):(e=null,h('":"')),e===null&&(o.charCodeAt(r)===64?(e="@",r++):(e=null,h('"@"')),e===null&&(o.charCodeAt(r)===38?(e="&",r++):(e=null,h('"&"')),e===null&&(o.charCodeAt(r)===61?(e="=",r++):(e=null,h('"="')),e===null&&(o.charCodeAt(r)===43?(e="+",r++):(e=null,h('"+"')),e===null&&(o.charCodeAt(r)===36?(e="$",r++):(e=null,h('"$"')),e===null&&(o.charCodeAt(r)===44?(e=",",r++):(e=null,h('","')))))))))),e}function yi(){var e,l,u,f,p;if(f=r,p=r,e=S(),e!==null){for(l=[],u=S(),u===null&&(u=T(),u===null&&(o.charCodeAt(r)===43?(u="+",r++):(u=null,h('"+"')),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."'))))));u!==null;)l.push(u),u=S(),u===null&&(u=T(),u===null&&(o.charCodeAt(r)===43?(u="+",r++):(u=null,h('"+"')),u===null&&(o.charCodeAt(r)===45?(u="-",r++):(u=null,h('"-"')),u===null&&(o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."'))))));l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e!==null&&(e=function(g){w.scheme=o.substring(r,g)}(f)),e===null&&(r=f),e}function Ci(){var e;return e=Ai(),e===null&&(e=Ri()),e}function Ai(){var e,l,u,f;return u=r,f=r,e=At(),e!==null?(o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e=e!==null?e:"",e!==null?(l=ls(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e=e!==null?e:"",e}function Ri(){var e,l;if(l=F(),l===null&&(l=pe(),l===null&&(o.charCodeAt(r)===36?(l="$",r++):(l=null,h('"$"')),l===null&&(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","')),l===null&&(o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l===null&&(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l===null&&(o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l===null&&(o.charCodeAt(r)===38?(l="&",r++):(l=null,h('"&"')),l===null&&(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"'))))))))))),l!==null)for(e=[];l!==null;)e.push(l),l=F(),l===null&&(l=pe(),l===null&&(o.charCodeAt(r)===36?(l="$",r++):(l=null,h('"$"')),l===null&&(o.charCodeAt(r)===44?(l=",",r++):(l=null,h('","')),l===null&&(o.charCodeAt(r)===59?(l=";",r++):(l=null,h('";"')),l===null&&(o.charCodeAt(r)===58?(l=":",r++):(l=null,h('":"')),l===null&&(o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l===null&&(o.charCodeAt(r)===38?(l="&",r++):(l=null,h('"&"')),l===null&&(o.charCodeAt(r)===61?(l="=",r++):(l=null,h('"="')),l===null&&(o.charCodeAt(r)===43?(l="+",r++):(l=null,h('"+"')))))))))));else e=null;return e}function Xn(){var e,l;for(e=[],l=qs();l!==null;)e.push(l),l=qs();return e}function Qn(){var e,l,u,f,p,g,v,y;if(v=r,y=r,o.substr(r,3).toLowerCase()==="sip"?(e=o.substr(r,3),r+=3):(e=null,h('"SIP"')),e!==null)if(o.charCodeAt(r)===47?(l="/",r++):(l=null,h('"/"')),l!==null){if(f=T(),f!==null)for(u=[];f!==null;)u.push(f),f=T();else u=null;if(u!==null)if(o.charCodeAt(r)===46?(f=".",r++):(f=null,h('"."')),f!==null){if(g=T(),g!==null)for(p=[];g!==null;)p.push(g),g=T();else p=null;p!==null?e=[e,l,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(O){w.sip_version=o.substring(r,O)}(v)),e===null&&(r=v),e}function bi(){var e;return o.substr(r,6)==="INVITE"?(e="INVITE",r+=6):(e=null,h('"INVITE"')),e}function Ii(){var e;return o.substr(r,3)==="ACK"?(e="ACK",r+=3):(e=null,h('"ACK"')),e}function wi(){var e;return o.substr(r,7)==="OPTIONS"?(e="OPTIONS",r+=7):(e=null,h('"OPTIONS"')),e}function Oi(){var e;return o.substr(r,3)==="BYE"?(e="BYE",r+=3):(e=null,h('"BYE"')),e}function Di(){var e;return o.substr(r,6)==="CANCEL"?(e="CANCEL",r+=6):(e=null,h('"CANCEL"')),e}function Ni(){var e;return o.substr(r,8)==="REGISTER"?(e="REGISTER",r+=8):(e=null,h('"REGISTER"')),e}function xi(){var e;return o.substr(r,9)==="SUBSCRIBE"?(e="SUBSCRIBE",r+=9):(e=null,h('"SUBSCRIBE"')),e}function Ui(){var e;return o.substr(r,6)==="NOTIFY"?(e="NOTIFY",r+=6):(e=null,h('"NOTIFY"')),e}function Tn(){var e;return o.substr(r,5)==="REFER"?(e="REFER",r+=5):(e=null,h('"REFER"')),e}function vn(){var e,l;return l=r,e=bi(),e===null&&(e=Ii(),e===null&&(e=wi(),e===null&&(e=Oi(),e===null&&(e=Di(),e===null&&(e=Ni(),e===null&&(e=xi(),e===null&&(e=Ui(),e===null&&(e=Tn(),e===null&&(e=U()))))))))),e!==null&&(e=function(u){return w.method=o.substring(r,u),w.method}(l)),e===null&&(r=l),e}function ki(){var e,l,u,f,p,g;return g=r,e=Qn(),e!==null?(l=H(),l!==null?(u=Pi(),u!==null?(f=H(),f!==null?(p=No(),p!==null?e=[e,l,u,f,p]:(e=null,r=g)):(e=null,r=g)):(e=null,r=g)):(e=null,r=g)):(e=null,r=g),e}function Pi(){var e,l;return l=r,e=Mi(),e!==null&&(e=function(u,f){w.status_code=parseInt(f.join(""))}(l,e)),e===null&&(r=l),e}function Mi(){var e,l,u,f;return f=r,e=T(),e!==null?(l=T(),l!==null?(u=T(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function No(){var e,l,u;for(u=r,e=[],l=x(),l===null&&(l=F(),l===null&&(l=pe(),l===null&&(l=V(),l===null&&(l=z(),l===null&&(l=H(),l===null&&(l=k()))))));l!==null;)e.push(l),l=x(),l===null&&(l=F(),l===null&&(l=pe(),l===null&&(l=V(),l===null&&(l=z(),l===null&&(l=H(),l===null&&(l=k()))))));return e!==null&&(e=function(f){w.reason_phrase=o.substring(r,f)}(u)),e===null&&(r=u),e}function Nu(){var e,l,u,f,p,g;if(p=r,e=Cn(),e!==null){for(l=[],g=r,u=oe(),u!==null?(f=Cn(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=oe(),u!==null?(f=Cn(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function xu(){var e,l,u,f,p,g;return f=r,p=r,e=Q(),e!==null?(g=r,o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l!==null?(u=Q(),u!==null?l=[l,u]:(l=null,r=g)):(l=null,r=g),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){w=o.substring(r,v)}(f)),e===null&&(r=f),e}function Zn(){var e,l,u,f,p,g,v;if(p=r,e=W(),e===null)if(g=r,e=jt(),e!==null){for(l=[],v=r,u=oe(),u!==null?(f=jt(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=oe(),u!==null?(f=jt(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y){var O,le;for(le=w.multi_header.length,O=0;O<le;O++)if(w.multi_header[O].parsed===null){w=null;break}w!==null?w=w.multi_header:w=-1}()),e===null&&(r=p),e}function jt(){var e,l,u,f,p,g,v;if(p=r,g=r,e=we(),e===null&&(e=qt()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=er(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=er(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y){var O;w.multi_header||(w.multi_header=[]);try{O=new I(w.uri,w.display_name,w.params),delete w.uri,delete w.display_name,delete w.params}catch{O=null}w.multi_header.push({possition:r,offset:y,parsed:O})}(p)),e===null&&(r=p),e}function qt(){var e,l,u,f,p;return p=r,e=Ws(),e=e!==null?e:"",e!==null?(l=Re(),l!==null?(u=Ne(),u!==null?(f=Pe(),f!==null?e=[e,l,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function Ws(){var e,l,u,f,p,g,v;if(p=r,g=r,e=U(),e!==null){for(l=[],v=r,u=P(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=P(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e===null&&(e=me()),e!==null&&(e=function(y,O){typeof O=="string"?w.display_name=O:w.display_name=O[1].reduce(function(le,xe){return le+xe[0]+xe[1]},O[0])}(p,e)),e===null&&(r=p),e}function er(){var e;return e=Li(),e===null&&(e=os(),e===null&&(e=Xe())),e}function Li(){var e,l,u,f,p;return f=r,p=r,o.substr(r,1).toLowerCase()==="q"?(e=o.substr(r,1),r++):(e=null,h('"q"')),e!==null?(l=ie(),l!==null?(u=ze(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.params||(w.params={}),w.params.q=v}(f,e[2])),e===null&&(r=f),e}function os(){var e,l,u,f,p;return f=r,p=r,o.substr(r,7).toLowerCase()==="expires"?(e=o.substr(r,7),r+=7):(e=null,h('"expires"')),e!==null?(l=ie(),l!==null?(u=as(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.params||(w.params={}),w.params.expires=v}(f,e[2])),e===null&&(r=f),e}function as(){var e,l,u;if(u=r,l=T(),l!==null)for(e=[];l!==null;)e.push(l),l=T();else e=null;return e!==null&&(e=function(f,p){return parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function ze(){var e,l,u,f,p,g,v,y;return g=r,v=r,o.charCodeAt(r)===48?(e="0",r++):(e=null,h('"0"')),e!==null?(y=r,o.charCodeAt(r)===46?(l=".",r++):(l=null,h('"."')),l!==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?l=[l,u,f,p]:(l=null,r=y)):(l=null,r=y)):(l=null,r=y)):(l=null,r=y),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=v)):(e=null,r=v),e!==null&&(e=function(O){return parseFloat(o.substring(r,O))}(g)),e===null&&(r=g),e}function Xe(){var e,l,u,f,p,g;return f=r,p=r,e=U(),e!==null?(g=r,l=ie(),l!==null?(u=xo(),u!==null?l=[l,u]:(l=null,r=g)):(l=null,r=g),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v,y,O){w.params||(w.params={}),typeof O>"u"?O=void 0:O=O[1],w.params[y.toLowerCase()]=O}(f,e[0],e[1])),e===null&&(r=f),e}function xo(){var e;return e=U(),e===null&&(e=Cs(),e===null&&(e=Oe())),e}function Uo(){var e,l,u,f,p,g;if(p=r,e=tr(),e!==null){for(l=[],g=r,u=ye(),u!==null?(f=sr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=ye(),u!==null?(f=sr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function tr(){var e;return o.substr(r,6).toLowerCase()==="render"?(e=o.substr(r,6),r+=6):(e=null,h('"render"')),e===null&&(o.substr(r,7).toLowerCase()==="session"?(e=o.substr(r,7),r+=7):(e=null,h('"session"')),e===null&&(o.substr(r,4).toLowerCase()==="icon"?(e=o.substr(r,4),r+=4):(e=null,h('"icon"')),e===null&&(o.substr(r,5).toLowerCase()==="alert"?(e=o.substr(r,5),r+=5):(e=null,h('"alert"')),e===null&&(e=U())))),e}function sr(){var e;return e=ko(),e===null&&(e=Xe()),e}function ko(){var e,l,u,f;return f=r,o.substr(r,8).toLowerCase()==="handling"?(e=o.substr(r,8),r+=8):(e=null,h('"handling"')),e!==null?(l=ie(),l!==null?(o.substr(r,8).toLowerCase()==="optional"?(u=o.substr(r,8),r+=8):(u=null,h('"optional"')),u===null&&(o.substr(r,8).toLowerCase()==="required"?(u=o.substr(r,8),r+=8):(u=null,h('"required"')),u===null&&(u=U())),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Uu(){var e,l,u,f,p,g;if(p=r,e=U(),e!==null){for(l=[],g=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function ku(){var e,l,u;if(u=r,l=T(),l!==null)for(e=[];l!==null;)e.push(l),l=T();else e=null;return e!==null&&(e=function(f,p){w=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function Po(){var e,l;return l=r,e=$i(),e!==null&&(e=function(u){w=o.substring(r,u)}(l)),e===null&&(r=l),e}function $i(){var e,l,u,f,p,g,v,y;if(v=r,e=Hi(),e!==null)if(l=B(),l!==null)if(u=nr(),u!==null){for(f=[],y=r,p=ye(),p!==null?(g=rr(),g!==null?p=[p,g]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=ye(),p!==null?(g=rr(),g!==null?p=[p,g]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,l,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function Hi(){var e;return e=Fi(),e===null&&(e=Sn()),e}function Fi(){var e;return o.substr(r,4).toLowerCase()==="text"?(e=o.substr(r,4),r+=4):(e=null,h('"text"')),e===null&&(o.substr(r,5).toLowerCase()==="image"?(e=o.substr(r,5),r+=5):(e=null,h('"image"')),e===null&&(o.substr(r,5).toLowerCase()==="audio"?(e=o.substr(r,5),r+=5):(e=null,h('"audio"')),e===null&&(o.substr(r,5).toLowerCase()==="video"?(e=o.substr(r,5),r+=5):(e=null,h('"video"')),e===null&&(o.substr(r,11).toLowerCase()==="application"?(e=o.substr(r,11),r+=11):(e=null,h('"application"')),e===null&&(e=En()))))),e}function Sn(){var e;return o.substr(r,7).toLowerCase()==="message"?(e=o.substr(r,7),r+=7):(e=null,h('"message"')),e===null&&(o.substr(r,9).toLowerCase()==="multipart"?(e=o.substr(r,9),r+=9):(e=null,h('"multipart"')),e===null&&(e=En())),e}function En(){var e;return e=U(),e===null&&(e=Vi()),e}function Vi(){var e,l,u;return u=r,o.substr(r,2).toLowerCase()==="x-"?(e=o.substr(r,2),r+=2):(e=null,h('"x-"')),e!==null?(l=U(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function nr(){var e;return e=En(),e===null&&(e=U()),e}function rr(){var e,l,u,f;return f=r,e=U(),e!==null?(l=ie(),l!==null?(u=Mo(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Mo(){var e;return e=U(),e===null&&(e=Oe()),e}function Lo(){var e,l,u,f;return f=r,e=$o(),e!==null?(l=P(),l!==null?(u=vn(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function $o(){var e,l,u;if(u=r,l=T(),l!==null)for(e=[];l!==null;)e.push(l),l=T();else e=null;return e!==null&&(e=function(f,p){w.value=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function Pu(){var e,l;return l=r,e=as(),e!==null&&(e=function(u,f){w=f}(l,e)),e===null&&(r=l),e}function yn(){var e,l,u,f,p,g,v;if(p=r,g=r,e=Cn(),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y,O){w.event=O.join("").toLowerCase()}(p,e[0])),e===null&&(r=p),e}function Cn(){var e,l,u,f,p,g;if(p=r,e=X(),e!==null){for(l=[],g=r,o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u!==null?(f=X(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,o.charCodeAt(r)===46?(u=".",r++):(u=null,h('"."')),u!==null?(f=X(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function ji(){var e,l,u,f,p,g,v;if(p=r,g=r,e=we(),e===null&&(e=qt()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=An(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=An(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y){var O=w.tag;try{w=new I(w.uri,w.display_name,w.params),O&&w.setParam("tag",O)}catch{w=-1}}()),e===null&&(r=p),e}function An(){var e;return e=qi(),e===null&&(e=Xe()),e}function qi(){var e,l,u,f,p;return f=r,p=r,o.substr(r,3).toLowerCase()==="tag"?(e=o.substr(r,3),r+=3):(e=null,h('"tag"')),e!==null?(l=ie(),l!==null?(u=U(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.tag=v}(f,e[2])),e===null&&(r=f),e}function Mu(){var e,l,u;if(u=r,l=T(),l!==null)for(e=[];l!==null;)e.push(l),l=T();else e=null;return e!==null&&(e=function(f,p){w=parseInt(p.join(""))}(u,e)),e===null&&(r=u),e}function Lu(){var e,l;return l=r,e=as(),e!==null&&(e=function(u,f){w=f}(l,e)),e===null&&(r=l),e}function $u(){var e,l,u,f,p,g,v,y,O,le;for(y=r,O=r,e=[],l=Ws();l!==null;)e.push(l),l=Ws();if(e!==null)if(l=Re(),l!==null)if(u=Ne(),u!==null)if(f=Pe(),f!==null){for(p=[],le=r,g=ye(),g!==null?(v=Xe(),v!==null?g=[g,v]:(g=null,r=le)):(g=null,r=le);g!==null;)p.push(g),le=r,g=ye(),g!==null?(v=Xe(),v!==null?g=[g,v]:(g=null,r=le)):(g=null,r=le);p!==null?e=[e,l,u,f,p]:(e=null,r=O)}else e=null,r=O;else e=null,r=O;else e=null,r=O;else e=null,r=O;return e!==null&&(e=function(xe){try{w=new I(w.uri,w.display_name,w.params)}catch{w=-1}}()),e===null&&(r=y),e}function Bi(){var e;return e=ir(),e}function ir(){var e,l,u,f,p,g,v,y;if(v=r,o.substr(r,6).toLowerCase()==="digest"?(e=o.substr(r,6),r+=6):(e=null,h('"Digest"')),e!==null)if(l=P(),l!==null)if(u=Rn(),u!==null){for(f=[],y=r,p=oe(),p!==null?(g=Rn(),g!==null?p=[p,g]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=oe(),p!==null?(g=Rn(),g!==null?p=[p,g]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,l,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,l,u,f,p,g,v,y;if(v=r,e=U(),e!==null)if(l=P(),l!==null)if(u=us(),u!==null){for(f=[],y=r,p=oe(),p!==null?(g=us(),g!==null?p=[p,g]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=oe(),p!==null?(g=us(),g!==null?p=[p,g]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,l,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function us(){var e,l,u,f;return f=r,e=U(),e!==null?(l=ie(),l!==null?(u=U(),u===null&&(u=Oe()),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Rn(){var e;return e=Gi(),e===null&&(e=bn(),e===null&&(e=Ki(),e===null&&(e=Ji(),e===null&&(e=zi(),e===null&&(e=Xi(),e===null&&(e=wn(),e===null&&(e=us()))))))),e}function Gi(){var e,l,u,f;return f=r,o.substr(r,5).toLowerCase()==="realm"?(e=o.substr(r,5),r+=5):(e=null,h('"realm"')),e!==null?(l=ie(),l!==null?(u=Wi(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Wi(){var e,l;return l=r,e=me(),e!==null&&(e=function(u,f){w.realm=f}(l,e)),e===null&&(r=l),e}function bn(){var e,l,u,f,p,g,v,y,O;if(y=r,o.substr(r,6).toLowerCase()==="domain"?(e=o.substr(r,6),r+=6):(e=null,h('"domain"')),e!==null)if(l=ie(),l!==null)if(u=at(),u!==null)if(f=In(),f!==null){if(p=[],O=r,v=H(),v!==null)for(g=[];v!==null;)g.push(v),v=H();else g=null;for(g!==null?(v=In(),v!==null?g=[g,v]:(g=null,r=O)):(g=null,r=O);g!==null;){if(p.push(g),O=r,v=H(),v!==null)for(g=[];v!==null;)g.push(v),v=H();else g=null;g!==null?(v=In(),v!==null?g=[g,v]:(g=null,r=O)):(g=null,r=O)}p!==null?(g=Ee(),g!==null?e=[e,l,u,f,p,g]:(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 In(){var e;return e=zn(),e===null&&(e=gn()),e}function Ki(){var e,l,u,f;return f=r,o.substr(r,5).toLowerCase()==="nonce"?(e=o.substr(r,5),r+=5):(e=null,h('"nonce"')),e!==null?(l=ie(),l!==null?(u=Yi(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Yi(){var e,l;return l=r,e=me(),e!==null&&(e=function(u,f){w.nonce=f}(l,e)),e===null&&(r=l),e}function Ji(){var e,l,u,f,p;return f=r,p=r,o.substr(r,6).toLowerCase()==="opaque"?(e=o.substr(r,6),r+=6):(e=null,h('"opaque"')),e!==null?(l=ie(),l!==null?(u=me(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.opaque=v}(f,e[2])),e===null&&(r=f),e}function zi(){var e,l,u,f,p;return f=r,o.substr(r,5).toLowerCase()==="stale"?(e=o.substr(r,5),r+=5):(e=null,h('"stale"')),e!==null?(l=ie(),l!==null?(p=r,o.substr(r,4).toLowerCase()==="true"?(u=o.substr(r,4),r+=4):(u=null,h('"true"')),u!==null&&(u=function(g){w.stale=!0}()),u===null&&(r=p),u===null&&(p=r,o.substr(r,5).toLowerCase()==="false"?(u=o.substr(r,5),r+=5):(u=null,h('"false"')),u!==null&&(u=function(g){w.stale=!1}()),u===null&&(r=p)),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Xi(){var e,l,u,f,p;return f=r,p=r,o.substr(r,9).toLowerCase()==="algorithm"?(e=o.substr(r,9),r+=9):(e=null,h('"algorithm"')),e!==null?(l=ie(),l!==null?(o.substr(r,3).toLowerCase()==="md5"?(u=o.substr(r,3),r+=3):(u=null,h('"MD5"')),u===null&&(o.substr(r,8).toLowerCase()==="md5-sess"?(u=o.substr(r,8),r+=8):(u=null,h('"MD5-sess"')),u===null&&(u=U())),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.algorithm=v.toUpperCase()}(f,e[2])),e===null&&(r=f),e}function wn(){var e,l,u,f,p,g,v,y,O,le;if(y=r,o.substr(r,3).toLowerCase()==="qop"?(e=o.substr(r,3),r+=3):(e=null,h('"qop"')),e!==null)if(l=ie(),l!==null)if(u=at(),u!==null){if(O=r,f=lr(),f!==null){for(p=[],le=r,o.charCodeAt(r)===44?(g=",",r++):(g=null,h('","')),g!==null?(v=lr(),v!==null?g=[g,v]:(g=null,r=le)):(g=null,r=le);g!==null;)p.push(g),le=r,o.charCodeAt(r)===44?(g=",",r++):(g=null,h('","')),g!==null?(v=lr(),v!==null?g=[g,v]:(g=null,r=le)):(g=null,r=le);p!==null?f=[f,p]:(f=null,r=O)}else f=null,r=O;f!==null?(p=Ee(),p!==null?e=[e,l,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 lr(){var e,l;return l=r,o.substr(r,8).toLowerCase()==="auth-int"?(e=o.substr(r,8),r+=8):(e=null,h('"auth-int"')),e===null&&(o.substr(r,4).toLowerCase()==="auth"?(e=o.substr(r,4),r+=4):(e=null,h('"auth"')),e===null&&(e=U())),e!==null&&(e=function(u,f){w.qop||(w.qop=[]),w.qop.push(f.toLowerCase())}(l,e)),e===null&&(r=l),e}function Hu(){var e,l,u,f,p,g;if(p=r,e=U(),e!==null){for(l=[],g=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function or(){var e,l,u,f,p,g,v;if(p=r,g=r,e=ar(),e!==null){for(l=[],v=r,u=oe(),u!==null?(f=ar(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=oe(),u!==null?(f=ar(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y){var O,le;for(le=w.multi_header.length,O=0;O<le;O++)if(w.multi_header[O].parsed===null){w=null;break}w!==null?w=w.multi_header:w=-1}()),e===null&&(r=p),e}function ar(){var e,l,u,f,p,g,v;if(p=r,g=r,e=qt(),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y){var O;w.multi_header||(w.multi_header=[]);try{O=new I(w.uri,w.display_name,w.params),delete w.uri,delete w.display_name,delete w.params}catch{O=null}w.multi_header.push({possition:r,offset:y,parsed:O})}(p)),e===null&&(r=p),e}function Qi(){var e,l,u,f,p,g,v;if(p=r,g=r,o.substr(r,3).toLowerCase()==="sip"?(e=o.substr(r,3),r+=3):(e=null,h('"SIP"')),e===null&&(e=U()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=ur(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=ur(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y,O){if(w.protocol=O.toLowerCase(),w.params||(w.params={}),w.params.text&&w.params.text[0]==='"'){var le=w.params.text;w.text=le.substring(1,le.length-1),delete w.params.text}}(p,e[0])),e===null&&(r=p),e}function ur(){var e;return e=Ho(),e===null&&(e=Xe()),e}function Ho(){var e,l,u,f,p,g;if(p=r,g=r,o.substr(r,5).toLowerCase()==="cause"?(e=o.substr(r,5),r+=5):(e=null,h('"cause"')),e!==null)if(l=ie(),l!==null){if(f=T(),f!==null)for(u=[];f!==null;)u.push(f),f=T();else u=null;u!==null?e=[e,l,u]:(e=null,r=g)}else e=null,r=g;else e=null,r=g;return e!==null&&(e=function(v,y){w.cause=parseInt(y.join(""))}(p,e[2])),e===null&&(r=p),e}function Fu(){var e,l,u,f,p,g;if(p=r,e=U(),e!==null){for(l=[],g=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function cr(){var e,l,u,f,p,g;if(p=r,e=fr(),e!==null){for(l=[],g=r,u=oe(),u!==null?(f=fr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=oe(),u!==null?(f=fr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function fr(){var e,l,u,f,p,g;if(p=r,e=qt(),e!==null){for(l=[],g=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function Fo(){var e,l,u,f,p,g;if(p=r,e=dr(),e!==null){for(l=[],g=r,u=ye(),u!==null?(f=hr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=ye(),u!==null?(f=hr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function dr(){var e,l;return l=r,o.substr(r,6).toLowerCase()==="active"?(e=o.substr(r,6),r+=6):(e=null,h('"active"')),e===null&&(o.substr(r,7).toLowerCase()==="pending"?(e=o.substr(r,7),r+=7):(e=null,h('"pending"')),e===null&&(o.substr(r,10).toLowerCase()==="terminated"?(e=o.substr(r,10),r+=10):(e=null,h('"terminated"')),e===null&&(e=U()))),e!==null&&(e=function(u){w.state=o.substring(r,u)}(l)),e===null&&(r=l),e}function hr(){var e,l,u,f,p;return f=r,p=r,o.substr(r,6).toLowerCase()==="reason"?(e=o.substr(r,6),r+=6):(e=null,h('"reason"')),e!==null?(l=ie(),l!==null?(u=Vo(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){typeof v<"u"&&(w.reason=v)}(f,e[2])),e===null&&(r=f),e===null&&(f=r,p=r,o.substr(r,7).toLowerCase()==="expires"?(e=o.substr(r,7),r+=7):(e=null,h('"expires"')),e!==null?(l=ie(),l!==null?(u=as(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){typeof v<"u"&&(w.expires=v)}(f,e[2])),e===null&&(r=f),e===null&&(f=r,p=r,o.substr(r,11).toLowerCase()==="retry_after"?(e=o.substr(r,11),r+=11):(e=null,h('"retry_after"')),e!==null?(l=ie(),l!==null?(u=as(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){typeof v<"u"&&(w.retry_after=v)}(f,e[2])),e===null&&(r=f),e===null&&(e=Xe()))),e}function Vo(){var e;return o.substr(r,11).toLowerCase()==="deactivated"?(e=o.substr(r,11),r+=11):(e=null,h('"deactivated"')),e===null&&(o.substr(r,9).toLowerCase()==="probation"?(e=o.substr(r,9),r+=9):(e=null,h('"probation"')),e===null&&(o.substr(r,8).toLowerCase()==="rejected"?(e=o.substr(r,8),r+=8):(e=null,h('"rejected"')),e===null&&(o.substr(r,7).toLowerCase()==="timeout"?(e=o.substr(r,7),r+=7):(e=null,h('"timeout"')),e===null&&(o.substr(r,6).toLowerCase()==="giveup"?(e=o.substr(r,6),r+=6):(e=null,h('"giveup"')),e===null&&(o.substr(r,10).toLowerCase()==="noresource"?(e=o.substr(r,10),r+=10):(e=null,h('"noresource"')),e===null&&(o.substr(r,9).toLowerCase()==="invariant"?(e=o.substr(r,9),r+=9):(e=null,h('"invariant"')),e===null&&(e=U()))))))),e}function Vu(){var e;return e=j(),e=e!==null?e:"",e}function ju(){var e,l,u,f,p,g;if(p=r,e=U(),e!==null){for(l=[],g=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=oe(),u!==null?(f=U(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e=e!==null?e:"",e}function Zi(){var e,l,u,f,p,g,v;if(p=r,g=r,e=we(),e===null&&(e=qt()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=el(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=el(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y){var O=w.tag;try{w=new I(w.uri,w.display_name,w.params),O&&w.setParam("tag",O)}catch{w=-1}}()),e===null&&(r=p),e}function el(){var e;return e=qi(),e===null&&(e=Xe()),e}function _r(){var e,l,u,f,p,g;if(p=r,e=Ys(),e!==null){for(l=[],g=r,u=oe(),u!==null?(f=Ys(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=oe(),u!==null?(f=Ys(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function Ys(){var e,l,u,f,p,g,v,y;if(v=r,e=ol(),e!==null)if(l=P(),l!==null)if(u=cl(),u!==null){for(f=[],y=r,p=ye(),p!==null?(g=pr(),g!==null?p=[p,g]:(p=null,r=y)):(p=null,r=y);p!==null;)f.push(p),y=r,p=ye(),p!==null?(g=pr(),g!==null?p=[p,g]:(p=null,r=y)):(p=null,r=y);f!==null?e=[e,l,u,f]:(e=null,r=v)}else e=null,r=v;else e=null,r=v;else e=null,r=v;return e}function pr(){var e;return e=tl(),e===null&&(e=sl(),e===null&&(e=nl(),e===null&&(e=rl(),e===null&&(e=il(),e===null&&(e=Xe()))))),e}function tl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,3).toLowerCase()==="ttl"?(e=o.substr(r,3),r+=3):(e=null,h('"ttl"')),e!==null?(l=ie(),l!==null?(u=dl(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.ttl=v}(f,e[2])),e===null&&(r=f),e}function sl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,5).toLowerCase()==="maddr"?(e=o.substr(r,5),r+=5):(e=null,h('"maddr"')),e!==null?(l=ie(),l!==null?(u=Cs(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.maddr=v}(f,e[2])),e===null&&(r=f),e}function nl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,8).toLowerCase()==="received"?(e=o.substr(r,8),r+=8):(e=null,h('"received"')),e!==null?(l=ie(),l!==null?(u=Zt(),u===null&&(u=Te()),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.received=v}(f,e[2])),e===null&&(r=f),e}function rl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,6).toLowerCase()==="branch"?(e=o.substr(r,6),r+=6):(e=null,h('"branch"')),e!==null?(l=ie(),l!==null?(u=U(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.branch=v}(f,e[2])),e===null&&(r=f),e}function il(){var e,l,u,f,p;return f=r,o.substr(r,5).toLowerCase()==="rport"?(e=o.substr(r,5),r+=5):(e=null,h('"rport"')),e!==null?(p=r,l=ie(),l!==null?(u=ll(),u!==null?l=[l,u]:(l=null,r=p)):(l=null,r=p),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e}function ll(){var e,l,u,f,p,g,v;return g=r,v=r,e=T(),e=e!==null?e:"",e!==null?(l=T(),l=l!==null?l:"",l!==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,l,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,O){w.rport=parseInt(O.join(""))}(g,e)),e===null&&(r=g),e}function ol(){var e,l,u,f,p,g;return g=r,e=al(),e!==null?(l=B(),l!==null?(u=U(),u!==null?(f=B(),f!==null?(p=ul(),p!==null?e=[e,l,u,f,p]:(e=null,r=g)):(e=null,r=g)):(e=null,r=g)):(e=null,r=g)):(e=null,r=g),e}function al(){var e,l;return l=r,o.substr(r,3).toLowerCase()==="sip"?(e=o.substr(r,3),r+=3):(e=null,h('"SIP"')),e===null&&(e=U()),e!==null&&(e=function(u,f){w.protocol=f}(l,e)),e===null&&(r=l),e}function ul(){var e,l;return l=r,o.substr(r,3).toLowerCase()==="udp"?(e=o.substr(r,3),r+=3):(e=null,h('"UDP"')),e===null&&(o.substr(r,3).toLowerCase()==="tcp"?(e=o.substr(r,3),r+=3):(e=null,h('"TCP"')),e===null&&(o.substr(r,3).toLowerCase()==="tls"?(e=o.substr(r,3),r+=3):(e=null,h('"TLS"')),e===null&&(o.substr(r,4).toLowerCase()==="sctp"?(e=o.substr(r,4),r+=4):(e=null,h('"SCTP"')),e===null&&(e=U())))),e!==null&&(e=function(u,f){w.transport=f}(l,e)),e===null&&(r=l),e}function cl(){var e,l,u,f,p;return f=r,e=fl(),e!==null?(p=r,l=lt(),l!==null?(u=gr(),u!==null?l=[l,u]:(l=null,r=p)):(l=null,r=p),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=f)):(e=null,r=f),e}function fl(){var e,l;return l=r,e=Zt(),e===null&&(e=fn(),e===null&&(e=cn())),e!==null&&(e=function(u){w.host=o.substring(r,u)}(l)),e===null&&(r=l),e}function gr(){var e,l,u,f,p,g,v;return g=r,v=r,e=T(),e=e!==null?e:"",e!==null?(l=T(),l=l!==null?l:"",l!==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,l,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,O){w.port=parseInt(O.join(""))}(g,e)),e===null&&(r=g),e}function dl(){var e,l,u,f,p;return f=r,p=r,e=T(),e!==null?(l=T(),l=l!==null?l:"",l!==null?(u=T(),u=u!==null?u:"",u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){return parseInt(v.join(""))}(f,e)),e===null&&(r=f),e}function qu(){var e;return e=ir(),e}function jo(){var e,l,u,f,p,g;if(p=r,e=mr(),e!==null){for(l=[],g=r,u=ye(),u!==null?(f=Tr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=ye(),u!==null?(f=Tr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function mr(){var e,l;return l=r,e=as(),e!==null&&(e=function(u,f){w.expires=f}(l,e)),e===null&&(r=l),e}function Tr(){var e;return e=qo(),e===null&&(e=Xe()),e}function qo(){var e,l,u,f,p;return f=r,p=r,o.substr(r,9).toLowerCase()==="refresher"?(e=o.substr(r,9),r+=9):(e=null,h('"refresher"')),e!==null?(l=ie(),l!==null?(o.substr(r,3).toLowerCase()==="uac"?(u=o.substr(r,3),r+=3):(u=null,h('"uac"')),u===null&&(o.substr(r,3).toLowerCase()==="uas"?(u=o.substr(r,3),r+=3):(u=null,h('"uas"'))),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.refresher=v.toLowerCase()}(f,e[2])),e===null&&(r=f),e}function Bo(){var e,l,u,f;return f=r,e=U(),e!==null?(l=q(),l!==null?(u=Go(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Go(){var e,l;for(e=[],l=K(),l===null&&(l=z(),l===null&&(l=P()));l!==null;)e.push(l),l=K(),l===null&&(l=z(),l===null&&(l=P()));return e}function Bu(){var e,l;for(e=[],l=R();l!==null;)e.push(l),l=R();return e}function Wo(){var e,l,u;return u=r,o.substr(r,5)==="uuid:"?(e="uuid:",r+=5):(e=null,h('"uuid:"')),e!==null?(l=Bt(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function Bt(){var e,l,u,f,p,g,v,y,O,le,xe;return le=r,xe=r,e=hl(),e!==null?(o.charCodeAt(r)===45?(l="-",r++):(l=null,h('"-"')),l!==null?(u=Gt(),u!==null?(o.charCodeAt(r)===45?(f="-",r++):(f=null,h('"-"')),f!==null?(p=Gt(),p!==null?(o.charCodeAt(r)===45?(g="-",r++):(g=null,h('"-"')),g!==null?(v=Gt(),v!==null?(o.charCodeAt(r)===45?(y="-",r++):(y=null,h('"-"')),y!==null?(O=Ko(),O!==null?e=[e,l,u,f,p,g,v,y,O]:(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(Dt,Js){w=o.substring(r+5,Dt)}(le,e[0])),e===null&&(r=le),e}function Gt(){var e,l,u,f,p;return p=r,e=E(),e!==null?(l=E(),l!==null?(u=E(),u!==null?(f=E(),f!==null?e=[e,l,u,f]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e}function hl(){var e,l,u;return u=r,e=Gt(),e!==null?(l=Gt(),l!==null?e=[e,l]:(e=null,r=u)):(e=null,r=u),e}function Ko(){var e,l,u,f;return f=r,e=Gt(),e!==null?(l=Gt(),l!==null?(u=Gt(),u!==null?e=[e,l,u]:(e=null,r=f)):(e=null,r=f)):(e=null,r=f),e}function Gu(){var e,l,u,f,p,g,v;if(p=r,g=r,e=we(),e===null&&(e=qt()),e!==null){for(l=[],v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);u!==null;)l.push(u),v=r,u=ye(),u!==null?(f=Xe(),f!==null?u=[u,f]:(u=null,r=v)):(u=null,r=v);l!==null?e=[e,l]:(e=null,r=g)}else e=null,r=g;return e!==null&&(e=function(y){try{w=new I(w.uri,w.display_name,w.params)}catch{w=-1}}()),e===null&&(r=p),e}function Yo(){var e,l,u,f,p,g;if(p=r,e=vr(),e!==null){for(l=[],g=r,u=ye(),u!==null?(f=Sr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);u!==null;)l.push(u),g=r,u=ye(),u!==null?(f=Sr(),f!==null?u=[u,f]:(u=null,r=g)):(u=null,r=g);l!==null?e=[e,l]:(e=null,r=p)}else e=null,r=p;return e}function vr(){var e,l,u,f,p,g;return f=r,p=r,e=Q(),e!==null?(g=r,o.charCodeAt(r)===64?(l="@",r++):(l=null,h('"@"')),l!==null?(u=Q(),u!==null?l=[l,u]:(l=null,r=g)):(l=null,r=g),l=l!==null?l:"",l!==null?e=[e,l]:(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(v){w.call_id=o.substring(r,v)}(f)),e===null&&(r=f),e}function Sr(){var e;return e=_l(),e===null&&(e=pl(),e===null&&(e=Jo(),e===null&&(e=Xe()))),e}function _l(){var e,l,u,f,p;return f=r,p=r,o.substr(r,6)==="to-tag"?(e="to-tag",r+=6):(e=null,h('"to-tag"')),e!==null?(l=ie(),l!==null?(u=U(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.to_tag=v}(f,e[2])),e===null&&(r=f),e}function pl(){var e,l,u,f,p;return f=r,p=r,o.substr(r,8)==="from-tag"?(e="from-tag",r+=8):(e=null,h('"from-tag"')),e!==null?(l=ie(),l!==null?(u=U(),u!==null?e=[e,l,u]:(e=null,r=p)):(e=null,r=p)):(e=null,r=p),e!==null&&(e=function(g,v){w.from_tag=v}(f,e[2])),e===null&&(r=f),e}function Jo(){var e,l;return l=r,o.substr(r,10)==="early-only"?(e="early-only",r+=10):(e=null,h('"early-only"')),e!==null&&(e=function(u){w.early_only=!0}()),e===null&&(r=l),e}function Wu(e){e.sort();for(var l=null,u=[],f=0;f<e.length;f++)e[f]!==l&&(u.push(e[f]),l=e[f]);return u}function zo(){for(var e=1,l=1,u=!1,f=0;f<Math.max(r,_);f++){var p=o.charAt(f);p===`
4
+ `?(u||e++,l=1,u=!1):p==="\r"||p==="\u2028"||p==="\u2029"?(e++,l=1,u=!0):(l++,u=!1)}return{line:e,column:l}}var Rs=Is(),I=Zo(),w={},gl=s[a]();if(gl===null||r!==o.length){var ml=Math.max(r,_),Xo=ml<o.length?o.charAt(ml):null,i=zo();return new this.SyntaxError(Wu(d),Xo,ml,i.line,i.column),-1}return w},toSource:function(){return this._source}};return t.SyntaxError=function(n,o,a,s,r){function _(d,h){var m,T;switch(d.length){case 0:m="end of input";break;case 1:m=d[0];break;default:m=d.slice(0,d.length-1).join(", ")+" or "+d[d.length-1]}return T=h?c(h):"end of input","Expected "+m+" but "+T+" found."}this.name="SyntaxError",this.expected=n,this.found=o,this.message=_(n,o),this.offset=a,this.line=s,this.column=r},t.SyntaxError.prototype=Error.prototype,t}()),ea}var ta,Qu;function Is(){if(Qu)return ta;Qu=1;function c(h,m){var T;if(typeof Symbol>"u"||h[Symbol.iterator]==null){if(Array.isArray(h)||(T=t(h))||m&&h&&typeof h.length=="number"){T&&(h=T);var S=0,E=function(){};return{s:E,n:function(){return S>=h.length?{done:!0}:{done:!1,value:h[S++]}},e:function(k){throw k},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 A=!0,R=!1,C;return{s:function(){T=h[Symbol.iterator]()},n:function(){var k=T.next();return A=k.done,k},e:function(k){R=!0,C=k},f:function(){try{!A&&T.return!=null&&T.return()}finally{if(R)throw C}}}}function t(h,m){if(h){if(typeof h=="string")return n(h,m);var T=Object.prototype.toString.call(h).slice(8,-1);if(T==="Object"&&h.constructor&&(T=h.constructor.name),T==="Map"||T==="Set")return Array.from(h);if(T==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(T))return n(h,m)}}function n(h,m){(m==null||m>h.length)&&(m=h.length);for(var T=0,S=new Array(m);T<m;T++)S[T]=h[T];return S}function o(h,m){if(!(h instanceof m))throw new TypeError("Cannot call a class as a function")}function a(h,m){for(var T=0;T<m.length;T++){var S=m[T];S.enumerable=S.enumerable||!1,S.configurable=!0,"value"in S&&(S.writable=!0),Object.defineProperty(h,S.key,S)}}function s(h,m,T){return m&&a(h.prototype,m),T&&a(h,T),h}var r=nt,_=Rt(),d=ts();return ta=function(){s(h,null,[{key:"parse",value:function(T){if(T=d.parse(T,"SIP_URI"),T!==-1)return T}}]);function h(m,T,S,E){var A=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},R=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{};if(o(this,h),!S)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=m||r.SIP,this._user=T,this._host=S,this._port=E;for(var C in A)Object.prototype.hasOwnProperty.call(A,C)&&this.setParam(C,A[C]);for(var H in R)Object.prototype.hasOwnProperty.call(R,H)&&this.setHeader(H,R[H])}return s(h,[{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[_.headerize(T)]=Array.isArray(S)?S:[S]}},{key:"getHeader",value:function(T){if(T)return this._headers[_.headerize(T)]}},{key:"hasHeader",value:function(T){if(T)return this._headers.hasOwnProperty(_.headerize(T))&&!0||!1}},{key:"deleteHeader",value:function(T){if(T=_.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 h(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(_.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 A in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,A)){var R=c(this._headers[A]),C;try{for(R.s();!(C=R.n()).done;){var H=C.value;T.push("".concat(A,"=").concat(H))}}catch(k){R.e(k)}finally{R.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(_.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}}]),h}(),ta}var Zu;function Rt(){if(Zu)return Ze;Zu=1;function c(m){"@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(m)}function t(m,T){var S;if(typeof Symbol>"u"||m[Symbol.iterator]==null){if(Array.isArray(m)||(S=n(m))||T&&m&&typeof m.length=="number"){S&&(m=S);var E=0,A=function(){};return{s:A,n:function(){return E>=m.length?{done:!0}:{done:!1,value:m[E++]}},e:function(re){throw re},f:A}}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 R=!0,C=!1,H;return{s:function(){S=m[Symbol.iterator]()},n:function(){var re=S.next();return R=re.done,re},e:function(re){C=!0,H=re},f:function(){try{!R&&S.return!=null&&S.return()}finally{if(C)throw H}}}}function n(m,T){if(m){if(typeof m=="string")return o(m,T);var S=Object.prototype.toString.call(m).slice(8,-1);if(S==="Object"&&m.constructor&&(S=m.constructor.name),S==="Map"||S==="Set")return Array.from(m);if(S==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(S))return o(m,T)}}function o(m,T){(T==null||T>m.length)&&(T=m.length);for(var S=0,E=new Array(T);S<T;S++)E[S]=m[S];return E}var a=nt,s=Is(),r=ts();Ze.str_utf8_length=function(m){return unescape(encodeURIComponent(m)).length};var _=Ze.isFunction=function(m){return m!==void 0?Object.prototype.toString.call(m)==="[object Function]":!1};Ze.isString=function(m){return m!==void 0?Object.prototype.toString.call(m)==="[object String]":!1},Ze.isDecimal=function(m){return!isNaN(m)&&parseFloat(m)===parseInt(m,10)},Ze.isEmpty=function(m){return m===null||m===""||m===void 0||Array.isArray(m)&&m.length===0||typeof m=="number"&&isNaN(m)},Ze.hasMethods=function(m){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 A=0,R=S;A<R.length;A++){var C=R[A];if(_(m[C]))return!1}return!0};var d=Ze.createRandomToken=function(m){var T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:32,S,E,A="";for(S=0;S<m;S++)E=Math.random()*T|0,A+=E.toString(T);return A};Ze.newTag=function(){return d(10)},Ze.newUUID=function(){var m="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 m},Ze.hostType=function(m){if(m){if(m=r.parse(m,"host"),m!==-1)return m.host_type}else return};var h=Ze.escapeUser=function(m){return encodeURIComponent(decodeURIComponent(m)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/")};return Ze.normalizeTarget=function(m,T){if(m){if(m instanceof s)return m;if(typeof m=="string"){var S=m.split("@"),E,A;switch(S.length){case 1:if(!T)return;E=m,A=T;break;case 2:E=S[0],A=S[1];break;default:E=S.slice(0,S.length-1).join("@"),A=S[S.length-1]}E=E.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(E)&&(E=E.replace(/[-.()]/g,"")),m="".concat(a.SIP,":").concat(h(E),"@").concat(A);var R;return(R=s.parse(m))?R:void 0}else return}else return},Ze.headerize=function(m){var T={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},S=m.toLowerCase().replace(/_/g,"-").split("-"),E="",A=S.length,R;for(R=0;R<A;R++)R!==0&&(E+="-"),E+=S[R].charAt(0).toUpperCase()+S[R].substring(1);return T[E]&&(E=T[E]),E},Ze.sipErrorCause=function(m){for(var T in a.SIP_ERROR_CAUSES)if(a.SIP_ERROR_CAUSES[T].indexOf(m)!==-1)return a.causes[T];return a.causes.SIP_FAILURE_CODE},Ze.getRandomTestNetIP=function(){function m(T,S){return Math.floor(Math.random()*(S-T+1)+T)}return"192.0.2.".concat(m(1,254))},Ze.calculateMD5=function(m){function T(me,he){return me<<he|me>>>32-he}function S(me,he){var ge=me&2147483648,we=he&2147483648,Ne=me&1073741824,st=he&1073741824,He=(me&1073741823)+(he&1073741823);return Ne&st?He^2147483648^ge^we:Ne|st?He&1073741824?He^3221225472^ge^we:He^1073741824^ge^we:He^ge^we}function E(me,he,ge){return me&he|~me&ge}function A(me,he,ge){return me&ge|he&~ge}function R(me,he,ge){return me^he^ge}function C(me,he,ge){return he^(me|~ge)}function H(me,he,ge,we,Ne,st,He){return me=S(me,S(S(E(he,ge,we),Ne),He)),S(T(me,st),he)}function k(me,he,ge,we,Ne,st,He){return me=S(me,S(S(A(he,ge,we),Ne),He)),S(T(me,st),he)}function re(me,he,ge,we,Ne,st,He){return me=S(me,S(S(R(he,ge,we),Ne),He)),S(T(me,st),he)}function x(me,he,ge,we,Ne,st,He){return me=S(me,S(S(C(he,ge,we),Ne),He)),S(T(me,st),he)}function F(me){for(var he,ge=me.length,we=ge+8,Ne=(we-we%64)/64,st=(Ne+1)*16,He=new Array(st-1),Vt=0,At=0;At<ge;)he=(At-At%4)/4,Vt=At%4*8,He[he]=He[he]|me.charCodeAt(At)<<Vt,At++;return he=(At-At%4)/4,Vt=At%4*8,He[he]=He[he]|128<<Vt,He[st-2]=ge<<3,He[st-1]=ge>>>29,He}function _e(me){var he="",ge="",we,Ne;for(Ne=0;Ne<=3;Ne++)we=me>>>Ne*8&255,ge="0".concat(we.toString(16)),he=he+ge.substr(ge.length-2,2);return he}function pe(me){for(var he="",ge=0;ge<me.length;ge++){var we=me.charCodeAt(ge);we<128?he+=String.fromCharCode(we):we>127&&we<2048?(he+=String.fromCharCode(we>>6|192),he+=String.fromCharCode(we&63|128)):(he+=String.fromCharCode(we>>12|224),he+=String.fromCharCode(we>>6&63|128),he+=String.fromCharCode(we&63|128))}return he}var P=[],N,q,j,K,V,z,D,U,X,je=7,Q=12,W=17,B=22,ie=5,ve=9,Ie=14,Pe=20,Re=4,oe=11,ye=16,lt=23,at=6,Ee=10,Ce=15,be=21;for(m=pe(m),P=F(m),z=1732584193,D=4023233417,U=2562383102,X=271733878,N=0;N<P.length;N+=16)q=z,j=D,K=U,V=X,z=H(z,D,U,X,P[N+0],je,3614090360),X=H(X,z,D,U,P[N+1],Q,3905402710),U=H(U,X,z,D,P[N+2],W,606105819),D=H(D,U,X,z,P[N+3],B,3250441966),z=H(z,D,U,X,P[N+4],je,4118548399),X=H(X,z,D,U,P[N+5],Q,1200080426),U=H(U,X,z,D,P[N+6],W,2821735955),D=H(D,U,X,z,P[N+7],B,4249261313),z=H(z,D,U,X,P[N+8],je,1770035416),X=H(X,z,D,U,P[N+9],Q,2336552879),U=H(U,X,z,D,P[N+10],W,4294925233),D=H(D,U,X,z,P[N+11],B,2304563134),z=H(z,D,U,X,P[N+12],je,1804603682),X=H(X,z,D,U,P[N+13],Q,4254626195),U=H(U,X,z,D,P[N+14],W,2792965006),D=H(D,U,X,z,P[N+15],B,1236535329),z=k(z,D,U,X,P[N+1],ie,4129170786),X=k(X,z,D,U,P[N+6],ve,3225465664),U=k(U,X,z,D,P[N+11],Ie,643717713),D=k(D,U,X,z,P[N+0],Pe,3921069994),z=k(z,D,U,X,P[N+5],ie,3593408605),X=k(X,z,D,U,P[N+10],ve,38016083),U=k(U,X,z,D,P[N+15],Ie,3634488961),D=k(D,U,X,z,P[N+4],Pe,3889429448),z=k(z,D,U,X,P[N+9],ie,568446438),X=k(X,z,D,U,P[N+14],ve,3275163606),U=k(U,X,z,D,P[N+3],Ie,4107603335),D=k(D,U,X,z,P[N+8],Pe,1163531501),z=k(z,D,U,X,P[N+13],ie,2850285829),X=k(X,z,D,U,P[N+2],ve,4243563512),U=k(U,X,z,D,P[N+7],Ie,1735328473),D=k(D,U,X,z,P[N+12],Pe,2368359562),z=re(z,D,U,X,P[N+5],Re,4294588738),X=re(X,z,D,U,P[N+8],oe,2272392833),U=re(U,X,z,D,P[N+11],ye,1839030562),D=re(D,U,X,z,P[N+14],lt,4259657740),z=re(z,D,U,X,P[N+1],Re,2763975236),X=re(X,z,D,U,P[N+4],oe,1272893353),U=re(U,X,z,D,P[N+7],ye,4139469664),D=re(D,U,X,z,P[N+10],lt,3200236656),z=re(z,D,U,X,P[N+13],Re,681279174),X=re(X,z,D,U,P[N+0],oe,3936430074),U=re(U,X,z,D,P[N+3],ye,3572445317),D=re(D,U,X,z,P[N+6],lt,76029189),z=re(z,D,U,X,P[N+9],Re,3654602809),X=re(X,z,D,U,P[N+12],oe,3873151461),U=re(U,X,z,D,P[N+15],ye,530742520),D=re(D,U,X,z,P[N+2],lt,3299628645),z=x(z,D,U,X,P[N+0],at,4096336452),X=x(X,z,D,U,P[N+7],Ee,1126891415),U=x(U,X,z,D,P[N+14],Ce,2878612391),D=x(D,U,X,z,P[N+5],be,4237533241),z=x(z,D,U,X,P[N+12],at,1700485571),X=x(X,z,D,U,P[N+3],Ee,2399980690),U=x(U,X,z,D,P[N+10],Ce,4293915773),D=x(D,U,X,z,P[N+1],be,2240044497),z=x(z,D,U,X,P[N+8],at,1873313359),X=x(X,z,D,U,P[N+15],Ee,4264355552),U=x(U,X,z,D,P[N+6],Ce,2734768916),D=x(D,U,X,z,P[N+13],be,1309151649),z=x(z,D,U,X,P[N+4],at,4149444226),X=x(X,z,D,U,P[N+11],Ee,3174756917),U=x(U,X,z,D,P[N+2],Ce,718787259),D=x(D,U,X,z,P[N+9],be,3951481745),z=S(z,q),D=S(D,j),U=S(U,K),X=S(X,V);var Oe=_e(z)+_e(D)+_e(U)+_e(X);return Oe.toLowerCase()},Ze.closeMediaStream=function(m){if(m)try{var T;if(m.getTracks){T=m.getTracks();var S=t(T),E;try{for(S.s();!(E=S.n()).done;){var A=E.value;A.stop()}}catch(F){S.e(F)}finally{S.f()}}else{T=m.getAudioTracks();var R=t(T),C;try{for(R.s();!(C=R.n()).done;){var H=C.value;H.stop()}}catch(F){R.e(F)}finally{R.f()}T=m.getVideoTracks();var k=t(T),re;try{for(k.s();!(re=k.n()).done;){var x=re.value;x.stop()}}catch(F){k.e(F)}finally{k.f()}}}catch{(typeof m.stop=="function"||c(m.stop)==="object")&&m.stop()}},Ze.cloneArray=function(m){return m&&m.slice()||[]},Ze.cloneObject=function(m){var T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return m&&Object.assign({},m)||T},Ze}var sa={exports:{}},Dn=typeof Reflect=="object"?Reflect:null,ec=Dn&&typeof Dn.apply=="function"?Dn.apply:function(t,n,o){return Function.prototype.apply.call(t,n,o)},Al;Dn&&typeof Dn.ownKeys=="function"?Al=Dn.ownKeys:Object.getOwnPropertySymbols?Al=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Al=function(t){return Object.getOwnPropertyNames(t)};function Kd(c){console&&console.warn&&console.warn(c)}var tc=Number.isNaN||function(t){return t!==t};function Le(){Le.init.call(this)}sa.exports=Le,sa.exports.once=Xd,Le.EventEmitter=Le,Le.prototype._events=void 0,Le.prototype._eventsCount=0,Le.prototype._maxListeners=void 0;var sc=10;function Rl(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 sc},set:function(c){if(typeof c!="number"||c<0||tc(c))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+c+".");sc=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||tc(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 nc(c){return c._maxListeners===void 0?Le.defaultMaxListeners:c._maxListeners}Le.prototype.getMaxListeners=function(){return nc(this)},Le.prototype.emit=function(t){for(var n=[],o=1;o<arguments.length;o++)n.push(arguments[o]);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 _=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw _.context=r,_}var d=s[t];if(d===void 0)return!1;if(typeof d=="function")ec(d,this,n);else for(var h=d.length,m=ac(d,h),o=0;o<h;++o)ec(m[o],this,n);return!0};function rc(c,t,n,o){var a,s,r;if(Rl(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]=o?[n,r]:[r,n]:o?r.unshift(n):r.push(n),a=nc(c),a>0&&r.length>a&&!r.warned){r.warned=!0;var _=new Error("Possible EventEmitter memory leak detected. "+r.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");_.name="MaxListenersExceededWarning",_.emitter=c,_.type=t,_.count=r.length,Kd(_)}return c}Le.prototype.addListener=function(t,n){return rc(this,t,n,!1)},Le.prototype.on=Le.prototype.addListener,Le.prototype.prependListener=function(t,n){return rc(this,t,n,!0)};function Yd(){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 ic(c,t,n){var o={fired:!1,wrapFn:void 0,target:c,type:t,listener:n},a=Yd.bind(o);return a.listener=n,o.wrapFn=a,a}Le.prototype.once=function(t,n){return Rl(n),this.on(t,ic(this,t,n)),this},Le.prototype.prependOnceListener=function(t,n){return Rl(n),this.prependListener(t,ic(this,t,n)),this},Le.prototype.removeListener=function(t,n){var o,a,s,r,_;if(Rl(n),a=this._events,a===void 0)return this;if(o=a[t],o===void 0)return this;if(o===n||o.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete a[t],a.removeListener&&this.emit("removeListener",t,o.listener||n));else if(typeof o!="function"){for(s=-1,r=o.length-1;r>=0;r--)if(o[r]===n||o[r].listener===n){_=o[r].listener,s=r;break}if(s<0)return this;s===0?o.shift():Jd(o,s),o.length===1&&(a[t]=o[0]),a.removeListener!==void 0&&this.emit("removeListener",t,_||n)}return this},Le.prototype.off=Le.prototype.removeListener,Le.prototype.removeAllListeners=function(t){var n,o,a;if(o=this._events,o===void 0)return this;if(o.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):o[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete o[t]),this;if(arguments.length===0){var s=Object.keys(o),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=o[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 lc(c,t,n){var o=c._events;if(o===void 0)return[];var a=o[t];return a===void 0?[]:typeof a=="function"?n?[a.listener||a]:[a]:n?zd(a):ac(a,a.length)}Le.prototype.listeners=function(t){return lc(this,t,!0)},Le.prototype.rawListeners=function(t){return lc(this,t,!1)},Le.listenerCount=function(c,t){return typeof c.listenerCount=="function"?c.listenerCount(t):oc.call(c,t)},Le.prototype.listenerCount=oc;function oc(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}Le.prototype.eventNames=function(){return this._eventsCount>0?Al(this._events):[]};function ac(c,t){for(var n=new Array(t),o=0;o<t;++o)n[o]=c[o];return n}function Jd(c,t){for(;t+1<c.length;t++)c[t]=c[t+1];c.pop()}function zd(c){for(var t=new Array(c.length),n=0;n<t.length;++n)t[n]=c[n].listener||c[n];return t}function Xd(c,t){return new Promise(function(n,o){function a(r){c.removeListener(t,s),o(r)}function s(){typeof c.removeListener=="function"&&c.removeListener("error",a),n([].slice.call(arguments))}uc(c,t,s,{once:!0}),t!=="error"&&Qd(c,a,{once:!0})})}function Qd(c,t,n){typeof c.on=="function"&&uc(c,"error",t,n)}function uc(c,t,n,o){if(typeof c.on=="function")o.once?c.once(t,n):c.on(t,n);else if(typeof c.addEventListener=="function")c.addEventListener(t,function a(s){o.once&&c.removeEventListener(t,a),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof c)}var ct=sa.exports,na={exports:{}},ra,cc;function Zd(){if(cc)return ra;cc=1;var c=1e3,t=c*60,n=t*60,o=n*24,a=o*7,s=o*365.25;ra=function(m,T){T=T||{};var S=typeof m;if(S==="string"&&m.length>0)return r(m);if(S==="number"&&isFinite(m))return T.long?d(m):_(m);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(m))};function r(m){if(m=String(m),!(m.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(m);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*o;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 _(m){var T=Math.abs(m);return T>=o?Math.round(m/o)+"d":T>=n?Math.round(m/n)+"h":T>=t?Math.round(m/t)+"m":T>=c?Math.round(m/c)+"s":m+"ms"}function d(m){var T=Math.abs(m);return T>=o?h(m,T,o,"day"):T>=n?h(m,T,n,"hour"):T>=t?h(m,T,t,"minute"):T>=c?h(m,T,c,"second"):m+" ms"}function h(m,T,S,E){var A=T>=S*1.5;return Math.round(m/S)+" "+E+(A?"s":"")}return ra}function eh(c){n.debug=n,n.default=n,n.coerce=d,n.disable=s,n.enable=a,n.enabled=r,n.humanize=Zd(),n.destroy=h,Object.keys(c).forEach(m=>{n[m]=c[m]}),n.names=[],n.skips=[],n.formatters={};function t(m){let T=0;for(let S=0;S<m.length;S++)T=(T<<5)-T+m.charCodeAt(S),T|=0;return n.colors[Math.abs(T)%n.colors.length]}n.selectColor=t;function n(m){let T,S=null,E,A;function R(...C){if(!R.enabled)return;const H=R,k=Number(new Date),re=k-(T||k);H.diff=re,H.prev=T,H.curr=k,T=k,C[0]=n.coerce(C[0]),typeof C[0]!="string"&&C.unshift("%O");let x=0;C[0]=C[0].replace(/%([a-zA-Z%])/g,(_e,pe)=>{if(_e==="%%")return"%";x++;const P=n.formatters[pe];if(typeof P=="function"){const N=C[x];_e=P.call(H,N),C.splice(x,1),x--}return _e}),n.formatArgs.call(H,C),(H.log||n.log).apply(H,C)}return R.namespace=m,R.useColors=n.useColors(),R.color=n.selectColor(m),R.extend=o,R.destroy=n.destroy,Object.defineProperty(R,"enabled",{enumerable:!0,configurable:!1,get:()=>S!==null?S:(E!==n.namespaces&&(E=n.namespaces,A=n.enabled(m)),A),set:C=>{S=C}}),typeof n.init=="function"&&n.init(R),R}function o(m,T){const S=n(this.namespace+(typeof T>"u"?":":T)+m);return S.log=this.log,S}function a(m){n.save(m),n.namespaces=m,n.names=[],n.skips=[];let T;const S=(typeof m=="string"?m:"").split(/[\s,]+/),E=S.length;for(T=0;T<E;T++)S[T]&&(m=S[T].replace(/\*/g,".*?"),m[0]==="-"?n.skips.push(new RegExp("^"+m.slice(1)+"$")):n.names.push(new RegExp("^"+m+"$")))}function s(){const m=[...n.names.map(_),...n.skips.map(_).map(T=>"-"+T)].join(",");return n.enable(""),m}function r(m){if(m[m.length-1]==="*")return!0;let T,S;for(T=0,S=n.skips.length;T<S;T++)if(n.skips[T].test(m))return!1;for(T=0,S=n.names.length;T<S;T++)if(n.names[T].test(m))return!0;return!1}function _(m){return m.toString().substring(2,m.toString().length-2).replace(/\.\*\?$/,"*")}function d(m){return m instanceof Error?m.stack||m.message:m}function h(){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 th=eh;(function(c,t){t.formatArgs=o,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 o(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 h="color: "+this.color;d.splice(1,0,h,"color: inherit");let m=0,T=0;d[0].replace(/%[a-zA-Z%]/g,S=>{S!=="%%"&&(m++,S==="%c"&&(T=m))}),d.splice(T,0,h)}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=th(t);const{formatters:_}=c.exports;_.j=function(d){try{return JSON.stringify(d)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(na,na.exports);var Nn=na.exports;function sh(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function fc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function nh(c,t,n){return t&&fc(c.prototype,t),n&&fc(c,n),c}var xn=Nn,Un="JsSIP",ft=function(){function c(t){sh(this,c),t?(this._debug=xn.default("".concat(Un,":").concat(t)),this._warn=xn.default("".concat(Un,":WARN:").concat(t)),this._error=xn.default("".concat(Un,":ERROR:").concat(t))):(this._debug=xn.default(Un),this._warn=xn.default("".concat(Un,":WARN")),this._error=xn.default("".concat(Un,":ERROR"))),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}return nh(c,[{key:"debug",get:function(){return this._debug}},{key:"warn",get:function(){return this._warn}},{key:"error",get:function(){return this._error}}]),c}(),Nt={},dc={},hc={exports:{}},_c=hc.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(_c).forEach(function(c){var t=_c[c];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})});var pc=hc.exports;(function(c){var t=function(_){return String(Number(_))===_?Number(_):_},n=function(_,d,h,m){if(m&&!h)d[m]=t(_[1]);else for(var T=0;T<h.length;T+=1)_[T+1]!=null&&(d[h[T]]=t(_[T+1]))},o=function(_,d,h){var m=_.name&&_.names;_.push&&!d[_.push]?d[_.push]=[]:m&&!d[_.name]&&(d[_.name]={});var T=_.push?{}:m?d[_.name]:d;n(h.match(_.reg),T,_.names,_.name),_.push&&d[_.push].push(T)},a=pc,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);c.parse=function(_){var d={},h=[],m=d;return _.split(/(\r\n|\r|\n)/).filter(s).forEach(function(T){var S=T[0],E=T.slice(2);S==="m"&&(h.push({rtp:[],fmtp:[]}),m=h[h.length-1]);for(var A=0;A<(a[S]||[]).length;A+=1){var R=a[S][A];if(R.reg.test(E))return o(R,m,E)}}),d.media=h,d};var r=function(_,d){var h=d.split(/=(.+)/,2);return h.length===2?_[h[0]]=t(h[1]):h.length===1&&d.length>1&&(_[h[0]]=void 0),_};c.parseParams=function(_){return _.split(/;\s?/).reduce(r,{})},c.parseFmtpConfig=c.parseParams,c.parsePayloads=function(_){return _.toString().split(" ").map(Number)},c.parseRemoteCandidates=function(_){for(var d=[],h=_.split(" ").map(t),m=0;m<h.length;m+=3)d.push({component:h[m],ip:h[m+1],port:h[m+2]});return d},c.parseImageAttributes=function(_){return _.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(r,{})})},c.parseSimulcastStreamList=function(_){return _.split(";").map(function(d){return d.split(",").map(function(h){var m,T=!1;return h[0]!=="~"?m=t(h):(m=t(h.substring(1,h.length)),T=!0),{scid:m,paused:T}})})}})(dc);var ia=pc,rh=/%[sdv%]/g,ih=function(c){var t=1,n=arguments,o=n.length;return c.replace(rh,function(a){if(t>=o)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""}})},Cr=function(c,t,n){var o=t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format,a=[c+"="+o];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 ih.apply(null,a)},lh=["v","o","s","i","u","e","p","c","b","t","r","z","a"],oh=["i","c","b","a"],ah=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||lh,o=t.innerOrder||oh,a=[];return n.forEach(function(s){ia[s].forEach(function(r){r.name in c&&c[r.name]!=null?a.push(Cr(s,r,c)):r.push in c&&c[r.push]!=null&&c[r.push].forEach(function(_){a.push(Cr(s,r,_))})})}),c.media.forEach(function(s){a.push(Cr("m",ia.m[0],s)),o.forEach(function(r){ia[r].forEach(function(_){_.name in s&&s[_.name]!=null?a.push(Cr(r,_,s)):_.push in s&&s[_.push]!=null&&s[_.push].forEach(function(d){a.push(Cr(r,_,d))})})})}),a.join(`\r
7
7
  `)+`\r
8
8
  `},zs=dc,uh=ah;Nt.write=uh,Nt.parse=zs.parse,Nt.parseParams=zs.parseParams,Nt.parseFmtpConfig=zs.parseFmtpConfig,Nt.parsePayloads=zs.parsePayloads,Nt.parseRemoteCandidates=zs.parseRemoteCandidates,Nt.parseImageAttributes=zs.parseImageAttributes,Nt.parseSimulcastStreamList=zs.parseSimulcastStreamList;function bl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?bl=function(n){return typeof n}:bl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},bl(c)}function la(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&&oa(c,t)}function oa(c,t){return oa=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},oa(c,t)}function aa(c){var t=dh();return function(){var o=Il(c),a;if(t){var s=Il(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return ch(this,a)}}function ch(c,t){return t&&(bl(t)==="object"||typeof t=="function")?t:fh(c)}function fh(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function dh(){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 Il(c){return Il=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Il(c)}function Lt(c,t){var n;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(n=hh(c))||t&&c&&typeof c.length=="number"){n&&(c=n);var o=0,a=function(){};return{s:a,n:function(){return o>=c.length?{done:!0}:{done:!1,value:c[o++]}},e:function(h){throw h},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 s=!0,r=!1,_;return{s:function(){n=c[Symbol.iterator]()},n:function(){var h=n.next();return s=h.done,h},e:function(h){r=!0,_=h},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw _}}}}function hh(c,t){if(c){if(typeof c=="string")return mc(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 mc(c,t)}}function mc(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=c[n];return o}function Ar(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function wl(c,t,n){return t&&gc(c.prototype,t),n&&gc(c,n),c}var Tc=Nt,_h=ft,ht=nt,rt=Rt(),vc=Zo(),ph=ts(),ua=new _h("SIPMessage"),Sc=function(){function c(t,n,o,a,s,r){if(Ar(this,c),!t||!n||!o)return null;a=a||{},this.ua=o,this.headers={},this.method=t,this.ruri=n,this.body=r,this.extraHeaders=rt.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):o.configuration.use_preloaded_route&&this.setHeader("route","<".concat(o.transport.sip_uri,";lr>")),this.setHeader("via",""),this.setHeader("max-forwards",ht.MAX_FORWARDS);var _=a.to_uri||n,d=a.to_tag?{tag:a.to_tag}:null,h=typeof a.to_display_name<"u"?a.to_display_name:null;this.to=new vc(_,h,d),this.setHeader("to",this.to.toString());var g=a.from_uri||o.configuration.uri,T={tag:a.from_tag||rt.newTag()},S;typeof a.from_display_name<"u"?S=a.from_display_name:o.configuration.display_name?S=o.configuration.display_name:S=null,this.from=new vc(g,S,T),this.setHeader("from",this.from.toString());var E=a.call_id||o.configuration.jssip_id+rt.createRandomToken(15);this.call_id=E,this.setHeader("call-id",E);var A=a.cseq||Math.floor(Math.random()*1e4);this.cseq=A,this.setHeader("cseq","".concat(A," ").concat(t))}return wl(c,[{key:"setHeader",value:function(n,o){for(var a=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),s=0;s<this.extraHeaders.length;s++)a.test(this.extraHeaders[s])&&this.extraHeaders.splice(s,1);this.headers[rt.headerize(n)]=Array.isArray(o)?o:[o]}},{key:"getHeader",value:function(n){var o=this.headers[rt.headerize(n)];if(o){if(o[0])return o[0]}else{var a=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),s=Lt(this.extraHeaders),r;try{for(s.s();!(r=s.n()).done;){var _=r.value;if(a.test(_))return _.substring(_.indexOf(":")+1).trim()}}catch(d){s.e(d)}finally{s.f()}}}},{key:"getHeaders",value:function(n){var o=this.headers[rt.headerize(n)],a=[];if(o){var s=Lt(o),r;try{for(s.s();!(r=s.n()).done;){var _=r.value;a.push(_)}}catch(S){s.e(S)}finally{s.f()}return a}else{var d=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),h=Lt(this.extraHeaders),g;try{for(h.s();!(g=h.n()).done;){var T=g.value;d.test(T)&&a.push(T.substring(T.indexOf(":")+1).trim())}}catch(S){h.e(S)}finally{h.f()}return a}}},{key:"hasHeader",value:function(n){if(this.headers[rt.headerize(n)])return!0;var o=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),a=Lt(this.extraHeaders),s;try{for(a.s();!(s=a.n()).done;){var r=s.value;if(o.test(r))return!0}}catch(_){a.e(_)}finally{a.f()}return!1}},{key:"parseSDP",value:function(n){return!n&&this.sdp?this.sdp:(this.sdp=Tc.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){var n="".concat(this.method," ").concat(this.ruri,` SIP/2.0\r
9
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,_;return{s:function(){n=c[Symbol.iterator]()},n:function(){var h=n.next();return s=h.done,h},e:function(h){r=!0,_=h},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw _}}}}function hh(c,t){if(c){if(typeof c=="string")return gc(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 gc(c,t)}}function gc(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=c[n];return o}function Ar(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function mc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function wl(c,t,n){return t&&mc(c.prototype,t),n&&mc(c,n),c}var Tc=Nt,_h=ft,ht=nt,rt=Rt(),vc=Zo(),ph=ts(),ua=new _h("SIPMessage"),Sc=function(){function c(t,n,o,a,s,r){if(Ar(this,c),!t||!n||!o)return null;a=a||{},this.ua=o,this.headers={},this.method=t,this.ruri=n,this.body=r,this.extraHeaders=rt.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):o.configuration.use_preloaded_route&&this.setHeader("route","<".concat(o.transport.sip_uri,";lr>")),this.setHeader("via",""),this.setHeader("max-forwards",ht.MAX_FORWARDS);var _=a.to_uri||n,d=a.to_tag?{tag:a.to_tag}:null,h=typeof a.to_display_name<"u"?a.to_display_name:null;this.to=new vc(_,h,d),this.setHeader("to",this.to.toString());var m=a.from_uri||o.configuration.uri,T={tag:a.from_tag||rt.newTag()},S;typeof a.from_display_name<"u"?S=a.from_display_name:o.configuration.display_name?S=o.configuration.display_name:S=null,this.from=new vc(m,S,T),this.setHeader("from",this.from.toString());var E=a.call_id||o.configuration.jssip_id+rt.createRandomToken(15);this.call_id=E,this.setHeader("call-id",E);var A=a.cseq||Math.floor(Math.random()*1e4);this.cseq=A,this.setHeader("cseq","".concat(A," ").concat(t))}return wl(c,[{key:"setHeader",value:function(n,o){for(var a=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),s=0;s<this.extraHeaders.length;s++)a.test(this.extraHeaders[s])&&this.extraHeaders.splice(s,1);this.headers[rt.headerize(n)]=Array.isArray(o)?o:[o]}},{key:"getHeader",value:function(n){var o=this.headers[rt.headerize(n)];if(o){if(o[0])return o[0]}else{var a=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),s=Lt(this.extraHeaders),r;try{for(s.s();!(r=s.n()).done;){var _=r.value;if(a.test(_))return _.substring(_.indexOf(":")+1).trim()}}catch(d){s.e(d)}finally{s.f()}}}},{key:"getHeaders",value:function(n){var o=this.headers[rt.headerize(n)],a=[];if(o){var s=Lt(o),r;try{for(s.s();!(r=s.n()).done;){var _=r.value;a.push(_)}}catch(S){s.e(S)}finally{s.f()}return a}else{var d=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),h=Lt(this.extraHeaders),m;try{for(h.s();!(m=h.n()).done;){var T=m.value;d.test(T)&&a.push(T.substring(T.indexOf(":")+1).trim())}}catch(S){h.e(S)}finally{h.f()}return a}}},{key:"hasHeader",value:function(n){if(this.headers[rt.headerize(n)])return!0;var o=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),a=Lt(this.extraHeaders),s;try{for(a.s();!(s=a.n()).done;){var r=s.value;if(o.test(r))return!0}}catch(_){a.e(_)}finally{a.f()}return!1}},{key:"parseSDP",value:function(n){return!n&&this.sdp?this.sdp:(this.sdp=Tc.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){var n="".concat(this.method," ").concat(this.ruri,` SIP/2.0\r
10
10
  `);for(var o in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,o)){var a=Lt(this.headers[o]),s;try{for(a.s();!(s=a.n()).done;){var r=s.value;n+="".concat(o,": ").concat(r,`\r
11
11
  `)}}catch(E){a.e(E)}finally{a.f()}}var _=Lt(this.extraHeaders),d;try{for(_.s();!(d=_.n()).done;){var h=d.value;n+="".concat(h.trim(),`\r
12
- `)}}catch(E){_.e(E)}finally{_.f()}var g=[];switch(this.method){case ht.REGISTER:g.push("path","gruu");break;case ht.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 ht.UPDATE:this.ua.configuration.session_timers&&g.push("timer"),g.push("ice");break}g.push("outbound");var T=this.ua.configuration.user_agent||ht.USER_AGENT;if(n+="Allow: ".concat(ht.ALLOWED_METHODS,`\r
13
- `),n+="Supported: ".concat(g,`\r
12
+ `)}}catch(E){_.e(E)}finally{_.f()}var m=[];switch(this.method){case ht.REGISTER:m.push("path","gruu");break;case ht.INVITE:this.ua.configuration.session_timers&&m.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&m.push("gruu"),m.push("ice","replaces");break;case ht.UPDATE:this.ua.configuration.session_timers&&m.push("timer"),m.push("ice");break}m.push("outbound");var T=this.ua.configuration.user_agent||ht.USER_AGENT;if(n+="Allow: ".concat(ht.ALLOWED_METHODS,`\r
13
+ `),n+="Supported: ".concat(m,`\r
14
14
  `),n+="User-Agent: ".concat(T,`\r
15
15
  `),this.body){var S=rt.str_utf8_length(this.body);n+="Content-Length: ".concat(S,`\r
16
16
  \r
17
17
  `),n+=this.body}else n+=`Content-Length: 0\r
18
18
  \r
19
- `;return n}},{key:"clone",value:function(){var n=new c(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(o){n.headers[o]=this.headers[o].slice()},this),n.body=this.body,n.extraHeaders=rt.cloneArray(this.extraHeaders),n.to=this.to,n.from=this.from,n.call_id=this.call_id,n.cseq=this.cseq,n}}]),c}(),mh=function(c){la(n,c);var t=aa(n);function n(o,a,s,r,_){var d;return Ar(this,n),d=t.call(this,ht.INVITE,o,a,s,r,_),d.transaction=null,d}return wl(n,[{key:"cancel",value:function(a){this.transaction.cancel(a)}},{key:"clone",value:function(){var a=new n(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(s){a.headers[s]=this.headers[s].slice()},this),a.body=this.body,a.extraHeaders=rt.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}}]),n}(Sc),Ec=function(){function c(){Ar(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 wl(c,[{key:"addHeader",value:function(n,o){var a={raw:o};n=rt.headerize(n),this.headers[n]?this.headers[n].push(a):this.headers[n]=[a]}},{key:"getHeader",value:function(n){var o=this.headers[rt.headerize(n)];if(o){if(o[0])return o[0].raw}else return}},{key:"getHeaders",value:function(n){var o=this.headers[rt.headerize(n)],a=[];if(!o)return[];var s=Lt(o),r;try{for(s.s();!(r=s.n()).done;){var _=r.value;a.push(_.raw)}}catch(d){s.e(d)}finally{s.f()}return a}},{key:"hasHeader",value:function(n){return!!this.headers[rt.headerize(n)]}},{key:"parseHeader",value:function(n){var o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(n=rt.headerize(n),this.headers[n]){if(o>=this.headers[n].length){ua.debug('not so many "'.concat(n,'" headers present'));return}}else{ua.debug('header "'.concat(n,'" not present'));return}var a=this.headers[n][o],s=a.raw;if(a.parsed)return a.parsed;var r=ph.parse(s,n.replace(/-/g,"_"));if(r===-1){this.headers[n].splice(o,1),ua.debug('error parsing "'.concat(n,'" header field with value "').concat(s,'"'));return}else return a.parsed=r,r}},{key:"s",value:function(n,o){return this.parseHeader(n,o)}},{key:"setHeader",value:function(n,o){var a={raw:o};this.headers[rt.headerize(n)]=[a]}},{key:"parseSDP",value:function(n){return!n&&this.sdp?this.sdp:(this.sdp=Tc.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){return this.data}}]),c}(),gh=function(c){la(n,c);var t=aa(n);function n(o){var a;return Ar(this,n),a=t.call(this),a.ua=o,a.headers={},a.ruri=null,a.transport=null,a.server_transaction=null,a}return wl(n,[{key:"reply",value:function(a,s,r,_,d,h){var g=[],T=this.getHeader("To");if(a=a||null,s=s||null,!a||a<100||a>699)throw new TypeError("Invalid status_code: ".concat(a));if(s&&typeof s!="string"&&!(s instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(s));s=s||ht.REASON_PHRASE[a]||"",r=rt.cloneArray(r),this.ua.configuration.extra_headers&&(r=r.concat(this.ua.configuration.extra_headers));var S="SIP/2.0 ".concat(a," ").concat(s,`\r
19
+ `;return n}},{key:"clone",value:function(){var n=new c(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(o){n.headers[o]=this.headers[o].slice()},this),n.body=this.body,n.extraHeaders=rt.cloneArray(this.extraHeaders),n.to=this.to,n.from=this.from,n.call_id=this.call_id,n.cseq=this.cseq,n}}]),c}(),gh=function(c){la(n,c);var t=aa(n);function n(o,a,s,r,_){var d;return Ar(this,n),d=t.call(this,ht.INVITE,o,a,s,r,_),d.transaction=null,d}return wl(n,[{key:"cancel",value:function(a){this.transaction.cancel(a)}},{key:"clone",value:function(){var a=new n(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(s){a.headers[s]=this.headers[s].slice()},this),a.body=this.body,a.extraHeaders=rt.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}}]),n}(Sc),Ec=function(){function c(){Ar(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 wl(c,[{key:"addHeader",value:function(n,o){var a={raw:o};n=rt.headerize(n),this.headers[n]?this.headers[n].push(a):this.headers[n]=[a]}},{key:"getHeader",value:function(n){var o=this.headers[rt.headerize(n)];if(o){if(o[0])return o[0].raw}else return}},{key:"getHeaders",value:function(n){var o=this.headers[rt.headerize(n)],a=[];if(!o)return[];var s=Lt(o),r;try{for(s.s();!(r=s.n()).done;){var _=r.value;a.push(_.raw)}}catch(d){s.e(d)}finally{s.f()}return a}},{key:"hasHeader",value:function(n){return!!this.headers[rt.headerize(n)]}},{key:"parseHeader",value:function(n){var o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(n=rt.headerize(n),this.headers[n]){if(o>=this.headers[n].length){ua.debug('not so many "'.concat(n,'" headers present'));return}}else{ua.debug('header "'.concat(n,'" not present'));return}var a=this.headers[n][o],s=a.raw;if(a.parsed)return a.parsed;var r=ph.parse(s,n.replace(/-/g,"_"));if(r===-1){this.headers[n].splice(o,1),ua.debug('error parsing "'.concat(n,'" header field with value "').concat(s,'"'));return}else return a.parsed=r,r}},{key:"s",value:function(n,o){return this.parseHeader(n,o)}},{key:"setHeader",value:function(n,o){var a={raw:o};this.headers[rt.headerize(n)]=[a]}},{key:"parseSDP",value:function(n){return!n&&this.sdp?this.sdp:(this.sdp=Tc.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){return this.data}}]),c}(),mh=function(c){la(n,c);var t=aa(n);function n(o){var a;return Ar(this,n),a=t.call(this),a.ua=o,a.headers={},a.ruri=null,a.transport=null,a.server_transaction=null,a}return wl(n,[{key:"reply",value:function(a,s,r,_,d,h){var m=[],T=this.getHeader("To");if(a=a||null,s=s||null,!a||a<100||a>699)throw new TypeError("Invalid status_code: ".concat(a));if(s&&typeof s!="string"&&!(s instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(s));s=s||ht.REASON_PHRASE[a]||"",r=rt.cloneArray(r),this.ua.configuration.extra_headers&&(r=r.concat(this.ua.configuration.extra_headers));var S="SIP/2.0 ".concat(a," ").concat(s,`\r
20
20
  `);if(this.method===ht.INVITE&&a>100&&a<=200){var E=this.getHeaders("record-route"),A=Lt(E),R;try{for(A.s();!(R=A.n()).done;){var C=R.value;S+="Record-Route: ".concat(C,`\r
21
21
  `)}}catch(N){A.e(N)}finally{A.f()}}var H=this.getHeaders("via"),k=Lt(H),re;try{for(k.s();!(re=k.n()).done;){var x=re.value;S+="Via: ".concat(x,`\r
22
22
  `)}}catch(N){k.e(N)}finally{k.f()}!this.to_tag&&a>100?T+=";tag=".concat(rt.newTag()):this.to_tag&&!this.s("to").hasParam("tag")&&(T+=";tag=".concat(this.to_tag)),S+="To: ".concat(T,`\r
@@ -24,18 +24,18 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
24
24
  `),S+="Call-ID: ".concat(this.call_id,`\r
25
25
  `),S+="CSeq: ".concat(this.cseq," ").concat(this.method,`\r
26
26
  `);var F=Lt(r),_e;try{for(F.s();!(_e=F.n()).done;){var pe=_e.value;S+="".concat(pe.trim(),`\r
27
- `)}}catch(N){F.e(N)}finally{F.f()}switch(this.method){case ht.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 ht.UPDATE:this.ua.configuration.session_timers&&g.push("timer"),_&&g.push("ice"),g.push("replaces")}if(g.push("outbound"),this.method===ht.OPTIONS?(S+="Allow: ".concat(ht.ALLOWED_METHODS,`\r
27
+ `)}}catch(N){F.e(N)}finally{F.f()}switch(this.method){case ht.INVITE:this.ua.configuration.session_timers&&m.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&m.push("gruu"),m.push("ice","replaces");break;case ht.UPDATE:this.ua.configuration.session_timers&&m.push("timer"),_&&m.push("ice"),m.push("replaces")}if(m.push("outbound"),this.method===ht.OPTIONS?(S+="Allow: ".concat(ht.ALLOWED_METHODS,`\r
28
28
  `),S+="Accept: ".concat(ht.ACCEPTED_BODY_TYPES,`\r
29
29
  `)):a===405?S+="Allow: ".concat(ht.ALLOWED_METHODS,`\r
30
30
  `):a===415&&(S+="Accept: ".concat(ht.ACCEPTED_BODY_TYPES,`\r
31
- `)),S+="Supported: ".concat(g,`\r
31
+ `)),S+="Supported: ".concat(m,`\r
32
32
  `),_){var P=rt.str_utf8_length(_);S+=`Content-Type: application/sdp\r
33
33
  `,S+="Content-Length: ".concat(P,`\r
34
34
  \r
35
35
  `),S+=_}else S+="Content-Length: ".concat(0,`\r
36
36
  \r
37
37
  `);this.server_transaction.receiveResponse(a,S,d,h)}},{key:"reply_sl",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,s=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(s&&typeof s!="string"&&!(s instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(s));s=s||ht.REASON_PHRASE[a]||"";var _="SIP/2.0 ".concat(a," ").concat(s,`\r
38
- `),d=Lt(r),h;try{for(d.s();!(h=d.n()).done;){var g=h.value;_+="Via: ".concat(g,`\r
38
+ `),d=Lt(r),h;try{for(d.s();!(h=d.n()).done;){var m=h.value;_+="Via: ".concat(m,`\r
39
39
  `)}}catch(R){d.e(R)}finally{d.f()}var T=this.getHeader("To");if(!this.to_tag&&a>100?T+=";tag=".concat(rt.newTag()):this.to_tag&&!this.s("to").hasParam("tag")&&(T+=";tag=".concat(this.to_tag)),_+="To: ".concat(T,`\r
40
40
  `),_+="From: ".concat(this.getHeader("From"),`\r
41
41
  `),_+="Call-ID: ".concat(this.call_id,`\r
@@ -43,11 +43,11 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
43
43
  `),this.ua.configuration.extra_headers){var S=Lt(this.ua.configuration.extra_headers),E;try{for(S.s();!(E=S.n()).done;){var A=E.value;_+="".concat(A.trim(),`\r
44
44
  `)}}catch(R){S.e(R)}finally{S.f()}}_+="Content-Length: ".concat(0,`\r
45
45
  \r
46
- `),this.transport.send(_)}}]),n}(Ec),Th=function(c){la(n,c);var t=aa(n);function n(){var o;return Ar(this,n),o=t.call(this),o.headers={},o.status_code=null,o.reason_phrase=null,o}return n}(Ec),fs={OutgoingRequest:Sc,InitialOutgoingInviteRequest:mh,IncomingRequest:gh,IncomingResponse:Th};function vh(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Sh(c,t,n){return t&&yc(c.prototype,t),n&&yc(c,n),c}var Eh=ft,ds=Rt(),Kt=new Eh("DigestAuthentication"),yh=function(){function c(t){vh(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 Sh(c,[{key:"get",value:function(n){switch(n){case"realm":return this._realm;case"ha1":return this._ha1;default:Kt.warn('get() | cannot get "%s" parameter',n);return}}},{key:"authenticate",value:function(n,o){var a=n.method,s=n.ruri,r=n.body,_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this._algorithm=o.algorithm,this._realm=o.realm,this._nonce=o.nonce,this._opaque=o.opaque,this._stale=o.stale,this._algorithm){if(this._algorithm!=="MD5")return Kt.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return Kt.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return Kt.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return Kt.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return Kt.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(o.qop)if(o.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(o.qop.indexOf("auth")>-1)this._qop="auth";else return Kt.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=_||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 h,g;return this._qop==="auth"?(h="".concat(this._method,":").concat(this._uri),g=ds.calculateMD5(h),Kt.debug('authenticate() | using qop=auth [a2:"%s"]',h),this._response=ds.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth:").concat(g))):this._qop==="auth-int"?(h="".concat(this._method,":").concat(this._uri,":").concat(ds.calculateMD5(r||"")),g=ds.calculateMD5(h),Kt.debug('authenticate() | using qop=auth-int [a2:"%s"]',h),this._response=ds.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth-int:").concat(g))):this._qop===null&&(h="".concat(this._method,":").concat(this._uri),g=ds.calculateMD5(h),Kt.debug('authenticate() | using qop=null [a2:"%s"]',h),this._response=ds.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(g))),Kt.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,Ch=4e3,Cc=5e3,Ac={T1:hs,T2:Ch,T4:Cc,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*Cc,TIMER_L:64*hs,TIMER_M:64*hs,PROVISIONAL_RESPONSE_INTERVAL:6e4};function Ol(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ol=function(n){return typeof n}:Ol=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Ol(c)}function Rr(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Rc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function br(c,t,n){return t&&Rc(c.prototype,t),n&&Rc(c,n),c}function Ir(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&&ca(c,t)}function ca(c,t){return ca=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},ca(c,t)}function wr(c){var t=Rh();return function(){var o=Dl(c),a;if(t){var s=Dl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return Ah(this,a)}}function Ah(c,t){return t&&(Ol(t)==="object"||typeof t=="function")?t:ws(c)}function ws(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Rh(){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 Dl(c){return Dl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Dl(c)}var Or=ct.EventEmitter,Dr=ft,Nr=nt,bc=fs,ss=Ac,Ic=new Dr("NonInviteClientTransaction"),Nl=new Dr("InviteClientTransaction"),bh=new Dr("AckClientTransaction"),wc=new Dr("NonInviteServerTransaction"),xl=new Dr("InviteServerTransaction"),ue={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"},Ih=function(c){Ir(n,c);var t=wr(n);function n(o,a,s,r){var _;Rr(this,n),_=t.call(this),_.type=ue.NON_INVITE_CLIENT,_.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),_.ua=o,_.transport=a,_.request=s,_.eventHandlers=r;var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(o.configuration.via_host,";branch=").concat(_.id),_.request.setHeader("via",d),_.ua.newTransaction(ws(_)),_}return br(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(ue.STATUS_TRYING),this.F=setTimeout(function(){a.timer_F()},ss.TIMER_F),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){Ic.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}},{key:"timer_F",value:function(){Ic.debug("Timer F expired for transaction ".concat(this.id)),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}},{key:"timer_K",value:function(){this.stateChanged(ue.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 ue.STATUS_TRYING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break}else switch(this.state){case ue.STATUS_TRYING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_COMPLETED),clearTimeout(this.F),r===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(a),this.K=setTimeout(function(){s.timer_K()},ss.TIMER_K);break;case ue.STATUS_COMPLETED:break}}},{key:"C",get:function(){return ue}}]),n}(Or),wh=function(c){Ir(n,c);var t=wr(n);function n(o,a,s,r){var _;Rr(this,n),_=t.call(this),_.type=ue.INVITE_CLIENT,_.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),_.ua=o,_.transport=a,_.request=s,_.eventHandlers=r,s.transaction=ws(_);var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(o.configuration.via_host,";branch=").concat(_.id),_.request.setHeader("via",d),_.ua.newTransaction(ws(_)),_}return br(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(ue.STATUS_CALLING),this.B=setTimeout(function(){a.timer_B()},ss.TIMER_B),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==ue.STATUS_ACCEPTED&&(Nl.debug("transport error occurred, deleting transaction ".concat(this.id)),this.eventHandlers.onTransportError()),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_M",value:function(){Nl.debug("Timer M expired for transaction ".concat(this.id)),this.state===ue.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"timer_B",value:function(){Nl.debug("Timer B expired for transaction ".concat(this.id)),this.state===ue.STATUS_CALLING&&(this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}},{key:"timer_D",value:function(){Nl.debug("Timer D expired for transaction ".concat(this.id)),clearTimeout(this.B),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"sendACK",value:function(a){var s=this,r=new bc.OutgoingRequest(Nr.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()},ss.TIMER_D),this.transport.send(r)}},{key:"cancel",value:function(a){if(this.state===ue.STATUS_PROCEEDING){var s=new bc.OutgoingRequest(Nr.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 ue.STATUS_CALLING:this.stateChanged(ue.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break;case ue.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(a);break}else if(r>=200&&r<=299)switch(this.state){case ue.STATUS_CALLING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_ACCEPTED),this.M=setTimeout(function(){s.timer_M()},ss.TIMER_M),this.eventHandlers.onReceiveResponse(a);break;case ue.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(a);break}else if(r>=300&&r<=699)switch(this.state){case ue.STATUS_CALLING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_COMPLETED),this.sendACK(a),this.eventHandlers.onReceiveResponse(a);break;case ue.STATUS_COMPLETED:this.sendACK(a);break}}},{key:"C",get:function(){return ue}}]),n}(Or),Oh=function(c){Ir(n,c);var t=wr(n);function n(o,a,s,r){var _;Rr(this,n),_=t.call(this),_.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),_.transport=a,_.request=s,_.eventHandlers=r;var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(o.configuration.via_host,";branch=").concat(_.id),_.request.setHeader("via",d),_}return br(n,[{key:"send",value:function(){this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){bh.debug("transport error occurred for transaction ".concat(this.id)),this.eventHandlers.onTransportError()}},{key:"C",get:function(){return ue}}]),n}(Or),Dh=function(c){Ir(n,c);var t=wr(n);function n(o,a,s){var r;return Rr(this,n),r=t.call(this),r.type=ue.NON_INVITE_SERVER,r.id=s.via_branch,r.ua=o,r.transport=a,r.request=s,r.last_response="",s.server_transaction=ws(r),r.state=ue.STATUS_TRYING,o.newTransaction(ws(r)),r}return br(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_J",value:function(){wc.debug("Timer J expired for transaction ".concat(this.id)),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,wc.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.J),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"receiveResponse",value:function(a,s,r,_){var d=this;if(a===100)switch(this.state){case ue.STATUS_TRYING:this.stateChanged(ue.STATUS_PROCEEDING),this.transport.send(s)||this.onTransportError();break;case ue.STATUS_PROCEEDING:this.last_response=s,this.transport.send(s)?r&&r():(this.onTransportError(),_&&_());break}else if(a>=200&&a<=699)switch(this.state){case ue.STATUS_TRYING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_COMPLETED),this.last_response=s,this.J=setTimeout(function(){d.timer_J()},ss.TIMER_J),this.transport.send(s)?r&&r():(this.onTransportError(),_&&_());break;case ue.STATUS_COMPLETED:break}}},{key:"C",get:function(){return ue}}]),n}(Or),Nh=function(c){Ir(n,c);var t=wr(n);function n(o,a,s){var r;return Rr(this,n),r=t.call(this),r.type=ue.INVITE_SERVER,r.id=s.via_branch,r.ua=o,r.transport=a,r.request=s,r.last_response="",s.server_transaction=ws(r),r.state=ue.STATUS_PROCEEDING,o.newTransaction(ws(r)),r.resendProvisionalTimer=null,s.reply(100),r}return br(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_H",value:function(){xl.debug("Timer H expired for transaction ".concat(this.id)),this.state===ue.STATUS_COMPLETED&&xl.debug("ACK not received, dialog will be terminated"),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_I",value:function(){this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_L",value:function(){xl.debug("Timer L expired for transaction ".concat(this.id)),this.state===ue.STATUS_ACCEPTED&&(this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,xl.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(ue.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,_){var d=this;if(a>=100&&a<=199)switch(this.state){case ue.STATUS_PROCEEDING:this.transport.send(s)||this.onTransportError(),this.last_response=s;break}if(a>100&&a<=199&&this.state===ue.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(function(){d.resend_provisional()},ss.PROVISIONAL_RESPONSE_INTERVAL));else if(a>=200&&a<=299)switch(this.state){case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_ACCEPTED),this.last_response=s,this.L=setTimeout(function(){d.timer_L()},ss.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case ue.STATUS_ACCEPTED:this.transport.send(s)?r&&r():(this.onTransportError(),_&&_());break}else if(a>=300&&a<=699)switch(this.state){case ue.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(s)?(this.stateChanged(ue.STATUS_COMPLETED),this.H=setTimeout(function(){d.timer_H()},ss.TIMER_H),r&&r()):(this.onTransportError(),_&&_());break}}},{key:"C",get:function(){return ue}}]),n}(Or);function xh(c,t){var n=c._transactions,o;switch(t.method){case Nr.INVITE:if(o=n.ist[t.via_branch],o){switch(o.state){case ue.STATUS_PROCEEDING:o.transport.send(o.last_response);break;case ue.STATUS_ACCEPTED:break}return!0}break;case Nr.ACK:if(o=n.ist[t.via_branch],o){if(o.state===ue.STATUS_ACCEPTED)return!1;if(o.state===ue.STATUS_COMPLETED)return o.state=ue.STATUS_CONFIRMED,o.I=setTimeout(function(){o.timer_I()},ss.TIMER_I),!0}else return!1;break;case Nr.CANCEL:return o=n.ist[t.via_branch],o?(t.reply_sl(200),o.state!==ue.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(o=n.nist[t.via_branch],o){switch(o.state){case ue.STATUS_TRYING:break;case ue.STATUS_PROCEEDING:case ue.STATUS_COMPLETED:o.transport.send(o.last_response);break}return!0}break}}var xr={C:ue,NonInviteClientTransaction:Ih,InviteClientTransaction:wh,AckClientTransaction:Oh,NonInviteServerTransaction:Dh,InviteServerTransaction:Nh,checkTransaction:xh};function Uh(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function kh(c,t,n){return t&&Oc(c.prototype,t),n&&Oc(c,n),c}var Ph=ft,Dc=nt,Mh=yh,fa=xr,Lh=new Ph("RequestSender"),da={onRequestTimeout:function(){},onTransportError:function(){},onReceiveResponse:function(){},onAuthenticated:function(){}},Ur=function(){function c(t,n,o){Uh(this,c),this._ua=t,this._eventHandlers=o,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(var a in da)Object.prototype.hasOwnProperty.call(da,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=da[a]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==Dc.BYE||this._method!==Dc.ACK)&&this._eventHandlers.onTransportError()}return kh(c,[{key:"send",value:function(){var n=this,o={onRequestTimeout:function(){n._eventHandlers.onRequestTimeout()},onTransportError:function(){n._eventHandlers.onTransportError()},onReceiveResponse:function(s){n._receiveResponse(s)}};switch(this._method){case"INVITE":this.clientTransaction=new fa.InviteClientTransaction(this._ua,this._ua.transport,this._request,o);break;case"ACK":this.clientTransaction=new fa.AckClientTransaction(this._ua,this._ua.transport,this._request,o);break;default:this.clientTransaction=new fa.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,o)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}},{key:"_receiveResponse",value:function(n){var o,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?(o=n.parseHeader("www-authenticate"),a="authorization"):(o=n.parseHeader("proxy-authenticate"),a="proxy-authorization"),!o){Lh.debug("".concat(n.status_code," with wrong or missing challenge, cannot authenticate")),this._eventHandlers.onReceiveResponse(n);return}if(!this._challenged||!this._staled&&o.stale===!0){if(this._auth||(this._auth=new Mh({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,o)){this._eventHandlers.onReceiveResponse(n);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),o.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 $h(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Nc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Hh(c,t,n){return t&&Nc(c.prototype,t),n&&Nc(c,n),c}var Fh=ft,ha=Rt(),Xs=nt,xc=fs,Uc=Ur,kr=new Fh("Registrator"),Ul=10,Vh=function(){function c(t,n){$h(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=ha.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 Hh(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 o in n)if(Object.prototype.hasOwnProperty.call(n,o)){var a=n[o];this._extraContactParams+=";".concat(o),a&&(this._extraContactParams+="=".concat(a))}}},{key:"register",value:function(){var n=this;if(this._registering){kr.debug("Register request in progress...");return}var o=this._extraHeaders.slice();o.push("Contact: ".concat(this._contact,";expires=").concat(this._expires).concat(this._extraContactParams)),o.push("Expires: ".concat(this._expires));var a=new xc.OutgoingRequest(Xs.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},o),s=new Uc(this._ua,a,{onRequestTimeout:function(){n._registrationFailure(null,Xs.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._registrationFailure(null,Xs.causes.CONNECTION_ERROR)},onAuthenticated:function(){n._cseq+=1},onReceiveResponse:function(_){if(_.cseq===n._cseq)switch(n._registrationTimer!==null&&(clearTimeout(n._registrationTimer),n._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(_.status_code):break;case/^2[0-9]{2}$/.test(_.status_code):{if(n._registering=!1,!_.hasHeader("Contact")){kr.debug("no Contact header in response to REGISTER, response ignored");break}var d=_.headers.Contact.reduce(function(E,A){return E.concat(A.parsed)},[]),h=d.find(function(E){return n._sipInstance===E.getParam("+sip.instance")&&n._reg_id===parseInt(E.getParam("reg-id"))});if(h||(h=d.find(function(E){return E.uri.user===n._ua.contact.uri.user})),!h){kr.debug("no Contact header pointing to us, response ignored");break}var g=h.getParam("expires");!g&&_.hasHeader("expires")&&(g=_.getHeader("expires")),g||(g=n._expires),g=Number(g),g<Ul&&(g=Ul);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),h.hasParam("temp-gruu")&&(n._ua.contact.temp_gruu=h.getParam("temp-gruu").replace(/"/g,"")),h.hasParam("pub-gruu")&&(n._ua.contact.pub_gruu=h.getParam("pub-gruu").replace(/"/g,"")),n._registered||(n._registered=!0,n._ua.registered({response:_}));break}case/^423$/.test(_.status_code):{_.hasHeader("min-expires")?(n._expires=Number(_.getHeader("min-expires")),n._expires<Ul&&(n._expires=Ul),n.register()):(kr.debug("423 response received for REGISTER without Min-Expires"),n._registrationFailure(_,Xs.causes.SIP_FAILURE_CODE));break}default:{var S=ha.sipErrorCause(_.status_code);n._registrationFailure(_,S)}}}});this._registering=!0,s.send()}},{key:"unregister",value:function(){var n=this,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._registered){kr.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);var a=this._extraHeaders.slice();o.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 xc.OutgoingRequest(Xs.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},a),r=new Uc(this._ua,s,{onRequestTimeout:function(){n._unregistered(null,Xs.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._unregistered(null,Xs.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 h=ha.sipErrorCause(d.status_code);n._unregistered(d,h)}}}});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,o){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:o}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:o}))}},{key:"_unregistered",value:function(n,o){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:o||null})}},{key:"registered",get:function(){return this._registered}}]),c}();function jh(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function kc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function qh(c,t,n){return t&&kc(c.prototype,t),n&&kc(c,n),c}var _a=nt,kl=xr,Bh=Ur,pa={onRequestTimeout:function(){},onTransportError:function(){},onSuccessResponse:function(){},onErrorResponse:function(){},onAuthenticated:function(){},onDialogError:function(){}},Gh=function(){function c(t,n,o){jh(this,c),this._dialog=t,this._ua=t._ua,this._request=n,this._eventHandlers=o,this._reattempt=!1,this._reattemptTimer=null;for(var a in pa)Object.prototype.hasOwnProperty.call(pa,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=pa[a]))}return qh(c,[{key:"send",value:function(){var n=this,o=new Bh(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(o.send(),(this._request.method===_a.INVITE||this._request.method===_a.UPDATE&&this._request.body)&&o.clientTransaction.state!==kl.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;var a=function s(){(o.clientTransaction.state===kl.C.STATUS_ACCEPTED||o.clientTransaction.state===kl.C.STATUS_COMPLETED||o.clientTransaction.state===kl.C.STATUS_TERMINATED)&&(o.clientTransaction.removeListener("stateChanged",s),n._dialog.uac_pending_reply=!1)};o.clientTransaction.on("stateChanged",a)}}},{key:"_receiveResponse",value:function(n){var o=this;n.status_code===408||n.status_code===481?this._eventHandlers.onDialogError(n):n.method===_a.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(){o._dialog.isTerminated()||(o._reattempt=!0,o.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 Wh(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Mc(c,t,n){return t&&Pc(c.prototype,t),n&&Pc(c,n),c}var Kh=ft,Lc=fs,Os=nt,Pr=xr,Yh=Gh,ma=Rt(),ga=new Kh("Dialog"),Ds={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3},Jh=function(){Mc(c,null,[{key:"C",get:function(){return Ds}}]);function c(t,n,o){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:Ds.STATUS_CONFIRMED;if(Wh(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 Lc.IncomingResponse&&(a=n.status_code<200?Ds.STATUS_EARLY:Ds.STATUS_CONFIRMED);var s=n.parseHeader("contact");o==="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):o==="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),ga.debug("new ".concat(o," dialog created with status ").concat(this._state===Ds.STATUS_EARLY?"EARLY":"CONFIRMED"))}return Mc(c,[{key:"isTerminated",value:function(){return this._status===Ds.STATUS_TERMINATED}},{key:"update",value:function(n,o){this._state=Ds.STATUS_CONFIRMED,ga.debug("dialog ".concat(this._id.toString()," changed to CONFIRMED state")),o==="UAC"&&(this._route_set=n.getHeaders("record-route").reverse())}},{key:"terminate",value:function(){ga.debug("dialog ".concat(this._id.toString()," deleted")),this._ua.destroyDialog(this),this._state=Ds.STATUS_TERMINATED}},{key:"sendRequest",value:function(n){var o=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=ma.cloneArray(a.extraHeaders),r=ma.cloneObject(a.eventHandlers),_=a.body||null,d=this._createRequest(n,s,_);r.onAuthenticated=function(){o._local_seqnum+=1};var h=new Yh(this,d,r);return h.send(),d}},{key:"receiveRequest",value:function(n){this._checkInDialogRequest(n)&&(n.method===Os.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:n.method===Os.INVITE&&(this._ack_seqnum=n.cseq),this._owner.receiveRequest(n))}},{key:"_createRequest",value:function(n,o,a){o=ma.cloneArray(o),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));var s=n===Os.CANCEL||n===Os.ACK?this._local_seqnum:this._local_seqnum+=1,r=new Lc.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},o,a);return r}},{key:"_checkInDialogRequest",value:function(n){var o=this;if(!this._remote_seqnum)this._remote_seqnum=n.cseq;else if(n.cseq<this._remote_seqnum)if(n.method===Os.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===Os.INVITE||n.method===Os.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===Pr.C.STATUS_ACCEPTED||n.server_transaction.state===Pr.C.STATUS_COMPLETED||n.server_transaction.state===Pr.C.STATUS_TERMINATED)&&(n.server_transaction.removeListener("stateChanged",r),o._uas_pending_reply=!1)};n.server_transaction.on("stateChanged",s)}n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Pr.C.STATUS_ACCEPTED&&(o._remote_target=n.parseHeader("contact").uri)})}else n.method===Os.NOTIFY&&n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Pr.C.STATUS_COMPLETED&&(o._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}(),Ta={exports:{}};function Pl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Pl=function(n){return typeof n}:Pl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Pl(c)}function zh(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Xh(c,t,n){return t&&$c(c.prototype,t),n&&$c(c,n),c}function Qh(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&&va(c,t)}function va(c,t){return va=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},va(c,t)}function Zh(c){var t=s_();return function(){var o=Ml(c),a;if(t){var s=Ml(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return e_(this,a)}}function e_(c,t){return t&&(Pl(t)==="object"||typeof t=="function")?t:t_(c)}function t_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function s_(){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 Ml(c){return Ml=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Ml(c)}var n_=ct.EventEmitter,r_=ft,i_=nt,l_=bs,Hc=Rt(),o_=new r_("RTCSession:DTMF"),Fc={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};Ta.exports=function(c){Qh(n,c);var t=Zh(n);function n(o){var a;return zh(this,n),a=t.call(this),a._session=o,a._direction=null,a._tone=null,a._duration=null,a._request=null,a}return Xh(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 l_.InvalidStateError(this._session.status);var _=Hc.cloneArray(r.extraHeaders);if(this.eventHandlers=Hc.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,_.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(i_.INFO,{extraHeaders:_,eventHandlers:{onSuccessResponse:function(g){s.emit("succeeded",{originator:"remote",response:g})},onErrorResponse:function(g){s.eventHandlers.onFailed&&s.eventHandlers.onFailed(),s.emit("failed",{originator:"remote",response:g})},onRequestTimeout:function(){s._session.onRequestTimeout()},onTransportError:function(){s._session.onTransportError()},onDialogError:function(){s._session.onDialogError()}},body:d})}},{key:"init_incoming",value:function(a){var s=/^(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 _=a.body.split(`
48
- `);_.length>=1&&s.test(_[0])&&(this._tone=_[0].replace(s,"$2")),_.length>=2&&r.test(_[1])&&(this._duration=parseInt(_[1].replace(r,"$2"),10))}this._duration||(this._duration=Fc.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:a}):o_.debug("invalid INFO DTMF received, discarded")}},{key:"tone",get:function(){return this._tone}},{key:"duration",get:function(){return this._duration}}]),n}(n_),Ta.exports.C=Fc;var a_=Ta.exports;function Ll(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ll=function(n){return typeof n}:Ll=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Ll(c)}function u_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Vc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function c_(c,t,n){return t&&Vc(c.prototype,t),n&&Vc(c,n),c}function f_(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&&Sa(c,t)}function Sa(c,t){return Sa=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Sa(c,t)}function d_(c){var t=p_();return function(){var o=$l(c),a;if(t){var s=$l(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return h_(this,a)}}function h_(c,t){return t&&(Ll(t)==="object"||typeof t=="function")?t:__(c)}function __(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function p_(){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 $l(c){return $l=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},$l(c)}var m_=ct.EventEmitter,g_=nt,T_=bs,v_=Rt(),S_=function(c){f_(n,c);var t=d_(n);function n(o){var a;return u_(this,n),a=t.call(this),a._session=o,a._direction=null,a._contentType=null,a._body=null,a}return c_(n,[{key:"send",value:function(a,s){var r=this,_=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 T_.InvalidStateError(this._session.status);this._contentType=a,this._body=s;var d=v_.cloneArray(_.extraHeaders);d.push("Content-Type: ".concat(a)),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(g_.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:s})}},{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}}]),n}(m_);function E_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function jc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function y_(c,t,n){return t&&jc(c.prototype,t),n&&jc(c,n),c}var C_=ft,qc=nt,A_=new C_("RTCSession:ReferNotifier"),Ea={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300},R_=function(){function c(t,n,o){E_(this,c),this._session=t,this._id=n,this._expires=o||Ea.expires,this._active=!0,this.notify(100)}return y_(c,[{key:"notify",value:function(n,o){if(A_.debug("notify()"),this._active!==!1){o=o||qc.REASON_PHRASE[n]||"";var a;n>=200?a="terminated;reason=noresource":a="active;expires=".concat(this._expires),this._session.sendRequest(qc.NOTIFY,{extraHeaders:["Event: ".concat(Ea.event_type,";id=").concat(this._id),"Subscription-State: ".concat(a),"Content-Type: ".concat(Ea.body_type)],body:"SIP/2.0 ".concat(n," ").concat(o),eventHandlers:{onErrorResponse:function(){this._active=!1}}})}}}]),c}();function Hl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Hl=function(n){return typeof n}:Hl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Hl(c)}function b_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Bc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function I_(c,t,n){return t&&Bc(c.prototype,t),n&&Bc(c,n),c}function w_(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&&ya(c,t)}function ya(c,t){return ya=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},ya(c,t)}function O_(c){var t=x_();return function(){var o=Fl(c),a;if(t){var s=Fl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return D_(this,a)}}function D_(c,t){return t&&(Hl(t)==="object"||typeof t=="function")?t:N_(c)}function N_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function x_(){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 Fl(c){return Fl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Fl(c)}var U_=ct.EventEmitter,k_=ft,Mr=nt,P_=ts(),Gc=Rt(),Qs=new k_("RTCSession:ReferSubscriber"),M_=function(c){w_(n,c);var t=O_(n);function n(o){var a;return b_(this,n),a=t.call(this),a._id=null,a._session=o,a}return I_(n,[{key:"sendRefer",value:function(a){var s=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Qs.debug("sendRefer()");var _=Gc.cloneArray(r.extraHeaders),d=Gc.cloneObject(r.eventHandlers);for(var h in d)Object.prototype.hasOwnProperty.call(d,h)&&this.on(h,d[h]);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(_.push(T),!_.some(function(A){return A.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,">");_.push(S)}_.push("Contact: ".concat(this._session.contact));var E=this._session.sendRequest(Mr.REFER,{extraHeaders:_,eventHandlers:{onSuccessResponse:function(R){s._requestSucceeded(R)},onErrorResponse:function(R){s._requestFailed(R,Mr.causes.REJECTED)},onTransportError:function(){s._requestFailed(null,Mr.causes.CONNECTION_ERROR)},onRequestTimeout:function(){s._requestFailed(null,Mr.causes.REQUEST_TIMEOUT)},onDialogError:function(){s._requestFailed(null,Mr.causes.DIALOG_ERROR)}}});this._id=E.cseq}},{key:"receiveNotify",value:function(a){if(Qs.debug("receiveNotify()"),!!a.body){var s=P_.parse(a.body.trim().split(`\r
46
+ `),this.transport.send(_)}}]),n}(Ec),Th=function(c){la(n,c);var t=aa(n);function n(){var o;return Ar(this,n),o=t.call(this),o.headers={},o.status_code=null,o.reason_phrase=null,o}return n}(Ec),fs={OutgoingRequest:Sc,InitialOutgoingInviteRequest:gh,IncomingRequest:mh,IncomingResponse:Th};function vh(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Sh(c,t,n){return t&&yc(c.prototype,t),n&&yc(c,n),c}var Eh=ft,ds=Rt(),Kt=new Eh("DigestAuthentication"),yh=function(){function c(t){vh(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 Sh(c,[{key:"get",value:function(n){switch(n){case"realm":return this._realm;case"ha1":return this._ha1;default:Kt.warn('get() | cannot get "%s" parameter',n);return}}},{key:"authenticate",value:function(n,o){var a=n.method,s=n.ruri,r=n.body,_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this._algorithm=o.algorithm,this._realm=o.realm,this._nonce=o.nonce,this._opaque=o.opaque,this._stale=o.stale,this._algorithm){if(this._algorithm!=="MD5")return Kt.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return Kt.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return Kt.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return Kt.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return Kt.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(o.qop)if(o.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(o.qop.indexOf("auth")>-1)this._qop="auth";else return Kt.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=_||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 h,m;return this._qop==="auth"?(h="".concat(this._method,":").concat(this._uri),m=ds.calculateMD5(h),Kt.debug('authenticate() | using qop=auth [a2:"%s"]',h),this._response=ds.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth:").concat(m))):this._qop==="auth-int"?(h="".concat(this._method,":").concat(this._uri,":").concat(ds.calculateMD5(r||"")),m=ds.calculateMD5(h),Kt.debug('authenticate() | using qop=auth-int [a2:"%s"]',h),this._response=ds.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth-int:").concat(m))):this._qop===null&&(h="".concat(this._method,":").concat(this._uri),m=ds.calculateMD5(h),Kt.debug('authenticate() | using qop=null [a2:"%s"]',h),this._response=ds.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(m))),Kt.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,Ch=4e3,Cc=5e3,Ac={T1:hs,T2:Ch,T4:Cc,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*Cc,TIMER_L:64*hs,TIMER_M:64*hs,PROVISIONAL_RESPONSE_INTERVAL:6e4};function Ol(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ol=function(n){return typeof n}:Ol=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Ol(c)}function Rr(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Rc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function br(c,t,n){return t&&Rc(c.prototype,t),n&&Rc(c,n),c}function Ir(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&&ca(c,t)}function ca(c,t){return ca=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},ca(c,t)}function wr(c){var t=Rh();return function(){var o=Dl(c),a;if(t){var s=Dl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return Ah(this,a)}}function Ah(c,t){return t&&(Ol(t)==="object"||typeof t=="function")?t:ws(c)}function ws(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Rh(){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 Dl(c){return Dl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Dl(c)}var Or=ct.EventEmitter,Dr=ft,Nr=nt,bc=fs,ss=Ac,Ic=new Dr("NonInviteClientTransaction"),Nl=new Dr("InviteClientTransaction"),bh=new Dr("AckClientTransaction"),wc=new Dr("NonInviteServerTransaction"),xl=new Dr("InviteServerTransaction"),ue={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"},Ih=function(c){Ir(n,c);var t=wr(n);function n(o,a,s,r){var _;Rr(this,n),_=t.call(this),_.type=ue.NON_INVITE_CLIENT,_.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),_.ua=o,_.transport=a,_.request=s,_.eventHandlers=r;var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(o.configuration.via_host,";branch=").concat(_.id),_.request.setHeader("via",d),_.ua.newTransaction(ws(_)),_}return br(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(ue.STATUS_TRYING),this.F=setTimeout(function(){a.timer_F()},ss.TIMER_F),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){Ic.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}},{key:"timer_F",value:function(){Ic.debug("Timer F expired for transaction ".concat(this.id)),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}},{key:"timer_K",value:function(){this.stateChanged(ue.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 ue.STATUS_TRYING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break}else switch(this.state){case ue.STATUS_TRYING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_COMPLETED),clearTimeout(this.F),r===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(a),this.K=setTimeout(function(){s.timer_K()},ss.TIMER_K);break;case ue.STATUS_COMPLETED:break}}},{key:"C",get:function(){return ue}}]),n}(Or),wh=function(c){Ir(n,c);var t=wr(n);function n(o,a,s,r){var _;Rr(this,n),_=t.call(this),_.type=ue.INVITE_CLIENT,_.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),_.ua=o,_.transport=a,_.request=s,_.eventHandlers=r,s.transaction=ws(_);var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(o.configuration.via_host,";branch=").concat(_.id),_.request.setHeader("via",d),_.ua.newTransaction(ws(_)),_}return br(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(ue.STATUS_CALLING),this.B=setTimeout(function(){a.timer_B()},ss.TIMER_B),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==ue.STATUS_ACCEPTED&&(Nl.debug("transport error occurred, deleting transaction ".concat(this.id)),this.eventHandlers.onTransportError()),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_M",value:function(){Nl.debug("Timer M expired for transaction ".concat(this.id)),this.state===ue.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"timer_B",value:function(){Nl.debug("Timer B expired for transaction ".concat(this.id)),this.state===ue.STATUS_CALLING&&(this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}},{key:"timer_D",value:function(){Nl.debug("Timer D expired for transaction ".concat(this.id)),clearTimeout(this.B),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"sendACK",value:function(a){var s=this,r=new bc.OutgoingRequest(Nr.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()},ss.TIMER_D),this.transport.send(r)}},{key:"cancel",value:function(a){if(this.state===ue.STATUS_PROCEEDING){var s=new bc.OutgoingRequest(Nr.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 ue.STATUS_CALLING:this.stateChanged(ue.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break;case ue.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(a);break}else if(r>=200&&r<=299)switch(this.state){case ue.STATUS_CALLING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_ACCEPTED),this.M=setTimeout(function(){s.timer_M()},ss.TIMER_M),this.eventHandlers.onReceiveResponse(a);break;case ue.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(a);break}else if(r>=300&&r<=699)switch(this.state){case ue.STATUS_CALLING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_COMPLETED),this.sendACK(a),this.eventHandlers.onReceiveResponse(a);break;case ue.STATUS_COMPLETED:this.sendACK(a);break}}},{key:"C",get:function(){return ue}}]),n}(Or),Oh=function(c){Ir(n,c);var t=wr(n);function n(o,a,s,r){var _;Rr(this,n),_=t.call(this),_.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),_.transport=a,_.request=s,_.eventHandlers=r;var d="SIP/2.0/".concat(a.via_transport);return d+=" ".concat(o.configuration.via_host,";branch=").concat(_.id),_.request.setHeader("via",d),_}return br(n,[{key:"send",value:function(){this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){bh.debug("transport error occurred for transaction ".concat(this.id)),this.eventHandlers.onTransportError()}},{key:"C",get:function(){return ue}}]),n}(Or),Dh=function(c){Ir(n,c);var t=wr(n);function n(o,a,s){var r;return Rr(this,n),r=t.call(this),r.type=ue.NON_INVITE_SERVER,r.id=s.via_branch,r.ua=o,r.transport=a,r.request=s,r.last_response="",s.server_transaction=ws(r),r.state=ue.STATUS_TRYING,o.newTransaction(ws(r)),r}return br(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_J",value:function(){wc.debug("Timer J expired for transaction ".concat(this.id)),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,wc.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.J),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"receiveResponse",value:function(a,s,r,_){var d=this;if(a===100)switch(this.state){case ue.STATUS_TRYING:this.stateChanged(ue.STATUS_PROCEEDING),this.transport.send(s)||this.onTransportError();break;case ue.STATUS_PROCEEDING:this.last_response=s,this.transport.send(s)?r&&r():(this.onTransportError(),_&&_());break}else if(a>=200&&a<=699)switch(this.state){case ue.STATUS_TRYING:case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_COMPLETED),this.last_response=s,this.J=setTimeout(function(){d.timer_J()},ss.TIMER_J),this.transport.send(s)?r&&r():(this.onTransportError(),_&&_());break;case ue.STATUS_COMPLETED:break}}},{key:"C",get:function(){return ue}}]),n}(Or),Nh=function(c){Ir(n,c);var t=wr(n);function n(o,a,s){var r;return Rr(this,n),r=t.call(this),r.type=ue.INVITE_SERVER,r.id=s.via_branch,r.ua=o,r.transport=a,r.request=s,r.last_response="",s.server_transaction=ws(r),r.state=ue.STATUS_PROCEEDING,o.newTransaction(ws(r)),r.resendProvisionalTimer=null,s.reply(100),r}return br(n,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_H",value:function(){xl.debug("Timer H expired for transaction ".concat(this.id)),this.state===ue.STATUS_COMPLETED&&xl.debug("ACK not received, dialog will be terminated"),this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_I",value:function(){this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_L",value:function(){xl.debug("Timer L expired for transaction ".concat(this.id)),this.state===ue.STATUS_ACCEPTED&&(this.stateChanged(ue.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,xl.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(ue.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,_){var d=this;if(a>=100&&a<=199)switch(this.state){case ue.STATUS_PROCEEDING:this.transport.send(s)||this.onTransportError(),this.last_response=s;break}if(a>100&&a<=199&&this.state===ue.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(function(){d.resend_provisional()},ss.PROVISIONAL_RESPONSE_INTERVAL));else if(a>=200&&a<=299)switch(this.state){case ue.STATUS_PROCEEDING:this.stateChanged(ue.STATUS_ACCEPTED),this.last_response=s,this.L=setTimeout(function(){d.timer_L()},ss.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case ue.STATUS_ACCEPTED:this.transport.send(s)?r&&r():(this.onTransportError(),_&&_());break}else if(a>=300&&a<=699)switch(this.state){case ue.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(s)?(this.stateChanged(ue.STATUS_COMPLETED),this.H=setTimeout(function(){d.timer_H()},ss.TIMER_H),r&&r()):(this.onTransportError(),_&&_());break}}},{key:"C",get:function(){return ue}}]),n}(Or);function xh(c,t){var n=c._transactions,o;switch(t.method){case Nr.INVITE:if(o=n.ist[t.via_branch],o){switch(o.state){case ue.STATUS_PROCEEDING:o.transport.send(o.last_response);break;case ue.STATUS_ACCEPTED:break}return!0}break;case Nr.ACK:if(o=n.ist[t.via_branch],o){if(o.state===ue.STATUS_ACCEPTED)return!1;if(o.state===ue.STATUS_COMPLETED)return o.state=ue.STATUS_CONFIRMED,o.I=setTimeout(function(){o.timer_I()},ss.TIMER_I),!0}else return!1;break;case Nr.CANCEL:return o=n.ist[t.via_branch],o?(t.reply_sl(200),o.state!==ue.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(o=n.nist[t.via_branch],o){switch(o.state){case ue.STATUS_TRYING:break;case ue.STATUS_PROCEEDING:case ue.STATUS_COMPLETED:o.transport.send(o.last_response);break}return!0}break}}var xr={C:ue,NonInviteClientTransaction:Ih,InviteClientTransaction:wh,AckClientTransaction:Oh,NonInviteServerTransaction:Dh,InviteServerTransaction:Nh,checkTransaction:xh};function Uh(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function kh(c,t,n){return t&&Oc(c.prototype,t),n&&Oc(c,n),c}var Ph=ft,Dc=nt,Mh=yh,fa=xr,Lh=new Ph("RequestSender"),da={onRequestTimeout:function(){},onTransportError:function(){},onReceiveResponse:function(){},onAuthenticated:function(){}},Ur=function(){function c(t,n,o){Uh(this,c),this._ua=t,this._eventHandlers=o,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(var a in da)Object.prototype.hasOwnProperty.call(da,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=da[a]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==Dc.BYE||this._method!==Dc.ACK)&&this._eventHandlers.onTransportError()}return kh(c,[{key:"send",value:function(){var n=this,o={onRequestTimeout:function(){n._eventHandlers.onRequestTimeout()},onTransportError:function(){n._eventHandlers.onTransportError()},onReceiveResponse:function(s){n._receiveResponse(s)}};switch(this._method){case"INVITE":this.clientTransaction=new fa.InviteClientTransaction(this._ua,this._ua.transport,this._request,o);break;case"ACK":this.clientTransaction=new fa.AckClientTransaction(this._ua,this._ua.transport,this._request,o);break;default:this.clientTransaction=new fa.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,o)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}},{key:"_receiveResponse",value:function(n){var o,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?(o=n.parseHeader("www-authenticate"),a="authorization"):(o=n.parseHeader("proxy-authenticate"),a="proxy-authorization"),!o){Lh.debug("".concat(n.status_code," with wrong or missing challenge, cannot authenticate")),this._eventHandlers.onReceiveResponse(n);return}if(!this._challenged||!this._staled&&o.stale===!0){if(this._auth||(this._auth=new Mh({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,o)){this._eventHandlers.onReceiveResponse(n);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),o.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 $h(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Nc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Hh(c,t,n){return t&&Nc(c.prototype,t),n&&Nc(c,n),c}var Fh=ft,ha=Rt(),Xs=nt,xc=fs,Uc=Ur,kr=new Fh("Registrator"),Ul=10,Vh=function(){function c(t,n){$h(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=ha.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 Hh(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 o in n)if(Object.prototype.hasOwnProperty.call(n,o)){var a=n[o];this._extraContactParams+=";".concat(o),a&&(this._extraContactParams+="=".concat(a))}}},{key:"register",value:function(){var n=this;if(this._registering){kr.debug("Register request in progress...");return}var o=this._extraHeaders.slice();o.push("Contact: ".concat(this._contact,";expires=").concat(this._expires).concat(this._extraContactParams)),o.push("Expires: ".concat(this._expires));var a=new xc.OutgoingRequest(Xs.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},o),s=new Uc(this._ua,a,{onRequestTimeout:function(){n._registrationFailure(null,Xs.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._registrationFailure(null,Xs.causes.CONNECTION_ERROR)},onAuthenticated:function(){n._cseq+=1},onReceiveResponse:function(_){if(_.cseq===n._cseq)switch(n._registrationTimer!==null&&(clearTimeout(n._registrationTimer),n._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(_.status_code):break;case/^2[0-9]{2}$/.test(_.status_code):{if(n._registering=!1,!_.hasHeader("Contact")){kr.debug("no Contact header in response to REGISTER, response ignored");break}var d=_.headers.Contact.reduce(function(E,A){return E.concat(A.parsed)},[]),h=d.find(function(E){return n._sipInstance===E.getParam("+sip.instance")&&n._reg_id===parseInt(E.getParam("reg-id"))});if(h||(h=d.find(function(E){return E.uri.user===n._ua.contact.uri.user})),!h){kr.debug("no Contact header pointing to us, response ignored");break}var m=h.getParam("expires");!m&&_.hasHeader("expires")&&(m=_.getHeader("expires")),m||(m=n._expires),m=Number(m),m<Ul&&(m=Ul);var T=m>64?m*1e3/2+Math.floor((m/2-32)*1e3*Math.random()):m*1e3-5e3;n._registrationTimer=setTimeout(function(){n._registrationTimer=null,n._ua.listeners("registrationExpiring").length===0?n.register():n._ua.emit("registrationExpiring")},T),h.hasParam("temp-gruu")&&(n._ua.contact.temp_gruu=h.getParam("temp-gruu").replace(/"/g,"")),h.hasParam("pub-gruu")&&(n._ua.contact.pub_gruu=h.getParam("pub-gruu").replace(/"/g,"")),n._registered||(n._registered=!0,n._ua.registered({response:_}));break}case/^423$/.test(_.status_code):{_.hasHeader("min-expires")?(n._expires=Number(_.getHeader("min-expires")),n._expires<Ul&&(n._expires=Ul),n.register()):(kr.debug("423 response received for REGISTER without Min-Expires"),n._registrationFailure(_,Xs.causes.SIP_FAILURE_CODE));break}default:{var S=ha.sipErrorCause(_.status_code);n._registrationFailure(_,S)}}}});this._registering=!0,s.send()}},{key:"unregister",value:function(){var n=this,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._registered){kr.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);var a=this._extraHeaders.slice();o.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 xc.OutgoingRequest(Xs.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},a),r=new Uc(this._ua,s,{onRequestTimeout:function(){n._unregistered(null,Xs.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._unregistered(null,Xs.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 h=ha.sipErrorCause(d.status_code);n._unregistered(d,h)}}}});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,o){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:o}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:o}))}},{key:"_unregistered",value:function(n,o){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:o||null})}},{key:"registered",get:function(){return this._registered}}]),c}();function jh(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function kc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function qh(c,t,n){return t&&kc(c.prototype,t),n&&kc(c,n),c}var _a=nt,kl=xr,Bh=Ur,pa={onRequestTimeout:function(){},onTransportError:function(){},onSuccessResponse:function(){},onErrorResponse:function(){},onAuthenticated:function(){},onDialogError:function(){}},Gh=function(){function c(t,n,o){jh(this,c),this._dialog=t,this._ua=t._ua,this._request=n,this._eventHandlers=o,this._reattempt=!1,this._reattemptTimer=null;for(var a in pa)Object.prototype.hasOwnProperty.call(pa,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=pa[a]))}return qh(c,[{key:"send",value:function(){var n=this,o=new Bh(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(o.send(),(this._request.method===_a.INVITE||this._request.method===_a.UPDATE&&this._request.body)&&o.clientTransaction.state!==kl.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;var a=function s(){(o.clientTransaction.state===kl.C.STATUS_ACCEPTED||o.clientTransaction.state===kl.C.STATUS_COMPLETED||o.clientTransaction.state===kl.C.STATUS_TERMINATED)&&(o.clientTransaction.removeListener("stateChanged",s),n._dialog.uac_pending_reply=!1)};o.clientTransaction.on("stateChanged",a)}}},{key:"_receiveResponse",value:function(n){var o=this;n.status_code===408||n.status_code===481?this._eventHandlers.onDialogError(n):n.method===_a.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(){o._dialog.isTerminated()||(o._reattempt=!0,o.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 Wh(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Mc(c,t,n){return t&&Pc(c.prototype,t),n&&Pc(c,n),c}var Kh=ft,Lc=fs,Os=nt,Pr=xr,Yh=Gh,ga=Rt(),ma=new Kh("Dialog"),Ds={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3},Jh=function(){Mc(c,null,[{key:"C",get:function(){return Ds}}]);function c(t,n,o){var a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:Ds.STATUS_CONFIRMED;if(Wh(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 Lc.IncomingResponse&&(a=n.status_code<200?Ds.STATUS_EARLY:Ds.STATUS_CONFIRMED);var s=n.parseHeader("contact");o==="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):o==="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),ma.debug("new ".concat(o," dialog created with status ").concat(this._state===Ds.STATUS_EARLY?"EARLY":"CONFIRMED"))}return Mc(c,[{key:"isTerminated",value:function(){return this._status===Ds.STATUS_TERMINATED}},{key:"update",value:function(n,o){this._state=Ds.STATUS_CONFIRMED,ma.debug("dialog ".concat(this._id.toString()," changed to CONFIRMED state")),o==="UAC"&&(this._route_set=n.getHeaders("record-route").reverse())}},{key:"terminate",value:function(){ma.debug("dialog ".concat(this._id.toString()," deleted")),this._ua.destroyDialog(this),this._state=Ds.STATUS_TERMINATED}},{key:"sendRequest",value:function(n){var o=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=ga.cloneArray(a.extraHeaders),r=ga.cloneObject(a.eventHandlers),_=a.body||null,d=this._createRequest(n,s,_);r.onAuthenticated=function(){o._local_seqnum+=1};var h=new Yh(this,d,r);return h.send(),d}},{key:"receiveRequest",value:function(n){this._checkInDialogRequest(n)&&(n.method===Os.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:n.method===Os.INVITE&&(this._ack_seqnum=n.cseq),this._owner.receiveRequest(n))}},{key:"_createRequest",value:function(n,o,a){o=ga.cloneArray(o),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));var s=n===Os.CANCEL||n===Os.ACK?this._local_seqnum:this._local_seqnum+=1,r=new Lc.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},o,a);return r}},{key:"_checkInDialogRequest",value:function(n){var o=this;if(!this._remote_seqnum)this._remote_seqnum=n.cseq;else if(n.cseq<this._remote_seqnum)if(n.method===Os.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===Os.INVITE||n.method===Os.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===Pr.C.STATUS_ACCEPTED||n.server_transaction.state===Pr.C.STATUS_COMPLETED||n.server_transaction.state===Pr.C.STATUS_TERMINATED)&&(n.server_transaction.removeListener("stateChanged",r),o._uas_pending_reply=!1)};n.server_transaction.on("stateChanged",s)}n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Pr.C.STATUS_ACCEPTED&&(o._remote_target=n.parseHeader("contact").uri)})}else n.method===Os.NOTIFY&&n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Pr.C.STATUS_COMPLETED&&(o._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}(),Ta={exports:{}};function Pl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Pl=function(n){return typeof n}:Pl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Pl(c)}function zh(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Xh(c,t,n){return t&&$c(c.prototype,t),n&&$c(c,n),c}function Qh(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&&va(c,t)}function va(c,t){return va=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},va(c,t)}function Zh(c){var t=s_();return function(){var o=Ml(c),a;if(t){var s=Ml(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return e_(this,a)}}function e_(c,t){return t&&(Pl(t)==="object"||typeof t=="function")?t:t_(c)}function t_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function s_(){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 Ml(c){return Ml=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Ml(c)}var n_=ct.EventEmitter,r_=ft,i_=nt,l_=bs,Hc=Rt(),o_=new r_("RTCSession:DTMF"),Fc={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};Ta.exports=function(c){Qh(n,c);var t=Zh(n);function n(o){var a;return zh(this,n),a=t.call(this),a._session=o,a._direction=null,a._tone=null,a._duration=null,a._request=null,a}return Xh(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 l_.InvalidStateError(this._session.status);var _=Hc.cloneArray(r.extraHeaders);if(this.eventHandlers=Hc.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,_.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(i_.INFO,{extraHeaders:_,eventHandlers:{onSuccessResponse:function(m){s.emit("succeeded",{originator:"remote",response:m})},onErrorResponse:function(m){s.eventHandlers.onFailed&&s.eventHandlers.onFailed(),s.emit("failed",{originator:"remote",response:m})},onRequestTimeout:function(){s._session.onRequestTimeout()},onTransportError:function(){s._session.onTransportError()},onDialogError:function(){s._session.onDialogError()}},body:d})}},{key:"init_incoming",value:function(a){var s=/^(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 _=a.body.split(`
48
+ `);_.length>=1&&s.test(_[0])&&(this._tone=_[0].replace(s,"$2")),_.length>=2&&r.test(_[1])&&(this._duration=parseInt(_[1].replace(r,"$2"),10))}this._duration||(this._duration=Fc.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:a}):o_.debug("invalid INFO DTMF received, discarded")}},{key:"tone",get:function(){return this._tone}},{key:"duration",get:function(){return this._duration}}]),n}(n_),Ta.exports.C=Fc;var a_=Ta.exports;function Ll(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Ll=function(n){return typeof n}:Ll=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Ll(c)}function u_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Vc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function c_(c,t,n){return t&&Vc(c.prototype,t),n&&Vc(c,n),c}function f_(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&&Sa(c,t)}function Sa(c,t){return Sa=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Sa(c,t)}function d_(c){var t=p_();return function(){var o=$l(c),a;if(t){var s=$l(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return h_(this,a)}}function h_(c,t){return t&&(Ll(t)==="object"||typeof t=="function")?t:__(c)}function __(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function p_(){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 $l(c){return $l=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},$l(c)}var g_=ct.EventEmitter,m_=nt,T_=bs,v_=Rt(),S_=function(c){f_(n,c);var t=d_(n);function n(o){var a;return u_(this,n),a=t.call(this),a._session=o,a._direction=null,a._contentType=null,a._body=null,a}return c_(n,[{key:"send",value:function(a,s){var r=this,_=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 T_.InvalidStateError(this._session.status);this._contentType=a,this._body=s;var d=v_.cloneArray(_.extraHeaders);d.push("Content-Type: ".concat(a)),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(m_.INFO,{extraHeaders:d,eventHandlers:{onSuccessResponse:function(m){r.emit("succeeded",{originator:"remote",response:m})},onErrorResponse:function(m){r.emit("failed",{originator:"remote",response:m})},onTransportError:function(){r._session.onTransportError()},onRequestTimeout:function(){r._session.onRequestTimeout()},onDialogError:function(){r._session.onDialogError()}},body:s})}},{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}}]),n}(g_);function E_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function jc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function y_(c,t,n){return t&&jc(c.prototype,t),n&&jc(c,n),c}var C_=ft,qc=nt,A_=new C_("RTCSession:ReferNotifier"),Ea={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300},R_=function(){function c(t,n,o){E_(this,c),this._session=t,this._id=n,this._expires=o||Ea.expires,this._active=!0,this.notify(100)}return y_(c,[{key:"notify",value:function(n,o){if(A_.debug("notify()"),this._active!==!1){o=o||qc.REASON_PHRASE[n]||"";var a;n>=200?a="terminated;reason=noresource":a="active;expires=".concat(this._expires),this._session.sendRequest(qc.NOTIFY,{extraHeaders:["Event: ".concat(Ea.event_type,";id=").concat(this._id),"Subscription-State: ".concat(a),"Content-Type: ".concat(Ea.body_type)],body:"SIP/2.0 ".concat(n," ").concat(o),eventHandlers:{onErrorResponse:function(){this._active=!1}}})}}}]),c}();function Hl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Hl=function(n){return typeof n}:Hl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Hl(c)}function b_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Bc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function I_(c,t,n){return t&&Bc(c.prototype,t),n&&Bc(c,n),c}function w_(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&&ya(c,t)}function ya(c,t){return ya=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},ya(c,t)}function O_(c){var t=x_();return function(){var o=Fl(c),a;if(t){var s=Fl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return D_(this,a)}}function D_(c,t){return t&&(Hl(t)==="object"||typeof t=="function")?t:N_(c)}function N_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function x_(){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 Fl(c){return Fl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Fl(c)}var U_=ct.EventEmitter,k_=ft,Mr=nt,P_=ts(),Gc=Rt(),Qs=new k_("RTCSession:ReferSubscriber"),M_=function(c){w_(n,c);var t=O_(n);function n(o){var a;return b_(this,n),a=t.call(this),a._id=null,a._session=o,a}return I_(n,[{key:"sendRefer",value:function(a){var s=this,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Qs.debug("sendRefer()");var _=Gc.cloneArray(r.extraHeaders),d=Gc.cloneObject(r.eventHandlers);for(var h in d)Object.prototype.hasOwnProperty.call(d,h)&&this.on(h,d[h]);var m=null;r.replaces&&(m=r.replaces._request.call_id,m+=";to-tag=".concat(r.replaces._to_tag),m+=";from-tag=".concat(r.replaces._from_tag),m=encodeURIComponent(m));var T="Refer-To: <".concat(a).concat(m?"?Replaces=".concat(m):"",">");if(_.push(T),!_.some(function(A){return A.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,">");_.push(S)}_.push("Contact: ".concat(this._session.contact));var E=this._session.sendRequest(Mr.REFER,{extraHeaders:_,eventHandlers:{onSuccessResponse:function(R){s._requestSucceeded(R)},onErrorResponse:function(R){s._requestFailed(R,Mr.causes.REJECTED)},onTransportError:function(){s._requestFailed(null,Mr.causes.CONNECTION_ERROR)},onRequestTimeout:function(){s._requestFailed(null,Mr.causes.REQUEST_TIMEOUT)},onDialogError:function(){s._requestFailed(null,Mr.causes.DIALOG_ERROR)}}});this._id=E.cseq}},{key:"receiveNotify",value:function(a){if(Qs.debug("receiveNotify()"),!!a.body){var s=P_.parse(a.body.trim().split(`\r
49
49
  `,1)[0],"Status_Line");if(s===-1){Qs.debug('receiveNotify() | error parsing NOTIFY body: "'.concat(a.body,'"'));return}switch(!0){case/^100$/.test(s.status_code):this.emit("trying",{request:a,status_line:s});break;case/^1[0-9]{2}$/.test(s.status_code):this.emit("progress",{request:a,status_line:s});break;case/^2[0-9]{2}$/.test(s.status_code):this.emit("accepted",{request:a,status_line:s});break;default:this.emit("failed",{request:a,status_line:s});break}}}},{key:"_requestSucceeded",value:function(a){Qs.debug("REFER succeeded"),Qs.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:a})}},{key:"_requestFailed",value:function(a,s){Qs.debug("REFER failed"),Qs.debug('emit "requestFailed"'),this.emit("requestFailed",{response:a||null,cause:s})}},{key:"id",get:function(){return this._id}}]),n}(U_);function Vl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Vl=function(n){return typeof n}:Vl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Vl(c)}function _s(c,t){var n;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(n=L_(c))||t&&c&&typeof c.length=="number"){n&&(c=n);var o=0,a=function(){};return{s:a,n:function(){return o>=c.length?{done:!0}:{done:!1,value:c[o++]}},e:function(h){throw h},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 s=!0,r=!1,_;return{s:function(){n=c[Symbol.iterator]()},n:function(){var h=n.next();return s=h.done,h},e:function(h){r=!0,_=h},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw _}}}}function L_(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,o=new Array(t);n<t;n++)o[n]=c[n];return o}function $_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Kc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Yc(c,t,n){return t&&Kc(c.prototype,t),n&&Kc(c,n),c}function H_(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&&Ca(c,t)}function Ca(c,t){return Ca=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Ca(c,t)}function F_(c){var t=q_();return function(){var o=jl(c),a;if(t){var s=jl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return V_(this,a)}}function V_(c,t){return t&&(Vl(t)==="object"||typeof t=="function")?t:j_(c)}function j_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function q_(){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 jl(c){return jl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},jl(c)}var B_=ct.EventEmitter,Jc=Nt,G_=ft,ce=nt,Zs=bs,zc=xr,Ge=Rt(),Lr=Ac,W_=fs,ql=Jh,K_=Ur,Pt=a_,Xc=S_,Y_=R_,J_=M_,Qc=Is(),Y=new G_("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"],z_=function(c){H_(n,c);var t=F_(n);Yc(n,null,[{key:"C",get:function(){return ee}}]);function n(o){var a;return $_(this,n),Y.debug("new"),a=t.call(this),a._id=null,a._ua=o,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 Yc(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;Y.debug("connect()");var _=a,d=Ge.cloneObject(s.eventHandlers),h=Ge.cloneArray(s.extraHeaders),g=Ge.cloneObject(s.mediaConstraints,{audio:!0,video:!0}),T=s.mediaStream||null,S=Ge.cloneObject(s.pcConfig,{iceServers:[]}),E=s.rtcConstraints||null,A=s.rtcOfferConstraints||null;if(this._rtcOfferConstraints=A,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 Zs.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Zs.NotSupportedError("WebRTC not supported");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(_));this._sessionTimers.enabled&&Ge.isDecimal(s.sessionTimersExpires)&&(s.sessionTimersExpires>=ce.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=s.sessionTimersExpires:this._sessionTimers.defaultExpires=ce.SESSION_EXPIRES);for(var R in d)Object.prototype.hasOwnProperty.call(d,R)&&this.on(R,d[R]);this._from_tag=Ge.newTag();var C=s.anonymous||!1,H={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:C,outbound:!0}),C?(H.from_display_name="Anonymous",H.from_uri=new Qc("sip","anonymous","anonymous.invalid"),h.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),h.push("Privacy: id")):s.fromUserName&&(H.from_uri=new Qc("sip",s.fromUserName,this._ua.configuration.uri.host),h.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),s.fromDisplayName&&(H.from_display_name=s.fromDisplayName),h.push("Contact: ".concat(this._contact)),h.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&h.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new W_.InitialOutgoingInviteRequest(a,this._ua,H,h),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,A,T)}},{key:"init_incoming",value:function(a,s){var r=this;Y.debug("init_incoming()");var _,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")&&(_=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),_&&(this._timers.expiresTimer=setTimeout(function(){r._status===ee.STATUS_WAITING_FOR_ANSWER&&(a.reply(487),r._failed("system",null,ce.causes.EXPIRES))},_)),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]:{};Y.debug("answer()");var r=this._request,_=Ge.cloneArray(s.extraHeaders),d=Ge.cloneObject(s.mediaConstraints),h=s.mediaStream||null,g=Ge.cloneObject(s.pcConfig,{iceServers:[]}),T=s.rtcConstraints||null,S=s.rtcAnswerConstraints||null,E=Ge.cloneObject(s.rtcOfferConstraints),A,R=!1,C=!1,H=!1,k=!1;if(this._rtcAnswerConstraints=S,this._rtcOfferConstraints=s.rtcOfferConstraints||null,this._data=s.data||this._data,this._direction!=="incoming")throw new Zs.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==ee.STATUS_WAITING_FOR_ANSWER)throw new Zs.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Ge.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),_.unshift("Contact: ".concat(this._contact));var re=r.parseSDP();Array.isArray(re.media)||(re.media=[re.media]);var x=_s(re.media),F;try{for(x.s();!(F=x.n()).done;){var _e=F.value;_e.type==="audio"&&(R=!0,(!_e.direction||_e.direction==="sendrecv")&&(H=!0)),_e.type==="video"&&(C=!0,(!_e.direction||_e.direction==="sendrecv")&&(k=!0))}}catch(V){x.e(V)}finally{x.f()}if(h&&d.audio===!1){A=h.getAudioTracks();var pe=_s(A),P;try{for(pe.s();!(P=pe.n()).done;){var N=P.value;h.removeTrack(N)}}catch(V){pe.e(V)}finally{pe.f()}}if(h&&d.video===!1){A=h.getVideoTracks();var q=_s(A),j;try{for(q.s();!(j=q.n()).done;){var K=j.value;h.removeTrack(K)}}catch(V){q.e(V)}finally{q.f()}}!h&&d.audio===void 0&&(d.audio=H),!h&&d.video===void 0&&(d.video=k),!h&&!R&&!E.offerToReceiveAudio&&(d.audio=!1),!h&&!C&&!E.offerToReceiveVideo&&(d.video=!1),this._createRTCConnection(g,T),Promise.resolve().then(function(){if(h)return h;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),Y.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(z){a._connection.addTrack(z,V)})}).then(function(){if(!a._late_sdp){var V={originator:"remote",type:"offer",sdp:r.body};Y.debug('emit "sdp"'),a.emit("sdp",V);var z=new RTCSessionDescription({type:"offer",sdp:V.sdp});return a._connectionPromiseQueue=a._connectionPromiseQueue.then(function(){return a._connection.setRemoteDescription(z)}).catch(function(D){throw r.reply(488),a._failed("system",null,ce.causes.WEBRTC_ERROR),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),a.emit("peerconnection:setremotedescriptionfailed",D),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,_),r.reply(200,null,_,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&&Y.warn(V)})}},{key:"terminate",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Y.debug("terminate()");var r=s.cause||ce.causes.BYE,_=Ge.cloneArray(s.extraHeaders),d=s.body,h,g=s.status_code,T=s.reason_phrase;if(this._status===ee.STATUS_TERMINATED)throw new Zs.InvalidStateError(this._status);switch(this._status){case ee.STATUS_NULL:case ee.STATUS_INVITE_SENT:case ee.STATUS_1XX_RECEIVED:if(Y.debug("canceling session"),g&&(g<200||g>=700))throw new TypeError("Invalid status_code: ".concat(g));g&&(T=T||ce.REASON_PHRASE[g]||"",h="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=h):this._status===ee.STATUS_1XX_RECEIVED&&this._request.cancel(h),this._status=ee.STATUS_CANCELED,this._failed("local",null,ce.causes.CANCELED);break;case ee.STATUS_WAITING_FOR_ANSWER:case ee.STATUS_ANSWERED:if(Y.debug("rejecting session"),g=g||480,g<300||g>=700)throw new TypeError("Invalid status_code: ".concat(g));this._request.reply(g,T,_,d),this._failed("local",null,ce.causes.REJECTED);break;case ee.STATUS_WAITING_FOR_ACK:case ee.STATUS_CONFIRMED:if(Y.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&&_.push("Reason: SIP ;cause=".concat(g,'; text="').concat(T,'"')),this._status===ee.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==zc.C.STATUS_TERMINATED){var S=this._dialog;this.receiveRequest=function(E){var A=E.method;A===ce.ACK&&(a.sendRequest(ce.BYE,{extraHeaders:_,body:d}),S.terminate())},this._request.server_transaction.on("stateChanged",function(){a._request.server_transaction.state===zc.C.STATUS_TERMINATED&&(a.sendRequest(ce.BYE,{extraHeaders:_,body:d}),S.terminate())}),this._ended("local",null,r),this._dialog=S,this._ua.newDialog(S)}else this.sendRequest(ce.BYE,{extraHeaders:_,body:d}),this._ended("local",null,r)}}},{key:"sendDTMF",value:function(a){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Y.debug("sendDTMF() | tones: %s",a);var r=0,_=s.duration||null,d=s.interToneGap||null,h=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 Zs.InvalidStateError(this._status);if(h!==ce.DTMF_TRANSPORT.INFO&&h!==ce.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(h));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(_&&!Ge.isDecimal(_))throw new TypeError("Invalid tone duration: ".concat(_));if(_?_<Pt.C.MIN_DURATION?(Y.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(Pt.C.MIN_DURATION," milliseconds")),_=Pt.C.MIN_DURATION):_>Pt.C.MAX_DURATION?(Y.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(Pt.C.MAX_DURATION," milliseconds")),_=Pt.C.MAX_DURATION):_=Math.abs(_):_=Pt.C.DEFAULT_DURATION,s.duration=_,d&&!Ge.isDecimal(d))throw new TypeError("Invalid interToneGap: ".concat(d));if(d?d<Pt.C.MIN_INTER_TONE_GAP?(Y.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,h===ce.DTMF_TRANSPORT.RFC2833){var g=this._getDTMFRTPSender();g&&(a=g.toneBuffer+a,g.insertDTMF(a,_,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 A=this._tones[r];if(r+=1,A===",")E=2e3;else{var R=new Pt(this);s.eventHandlers={onFailed:function(){S._tones=null}},R.send(A,s),E=_+d}setTimeout(T.bind(this),E)}}},{key:"sendInfo",value:function(a,s){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(Y.debug("sendInfo()"),this._status!==ee.STATUS_CONFIRMED&&this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_1XX_RECEIVED)throw new Zs.InvalidStateError(this._status);var _=new Xc(this);_.send(a,s,r)}},{key:"mute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};Y.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};Y.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(Y.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 _={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:_,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:_,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(Y.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 _={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:_,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:_,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;Y.debug("renegotiate()");var _=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:_,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:d,rtcOfferConstraints:_,extraHeaders:s.extraHeaders}),!0}},{key:"refer",value:function(a,s){var r=this;Y.debug("refer()");var _=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(_));var d=new J_(this);d.sendRefer(a,s);var h=d.id;return this._referSubscribers[h]=d,d.on("requestFailed",function(){delete r._referSubscribers[h]}),d.on("accepted",function(){delete r._referSubscribers[h]}),d.on("failed",function(){delete r._referSubscribers[h]}),d}},{key:"sendRequest",value:function(a,s){return Y.debug("sendRequest()"),this._dialog.sendRequest(a,s)}},{key:"receiveRequest",value:function(a){var s=this;if(Y.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};Y.debug('emit "sdp"'),this.emit("sdp",r);var _=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(_)}).then(function(){s._is_confirmed||s._confirmed("remote",a)}).catch(function(h){s.terminate({cause:ce.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',h),s.emit("peerconnection:setremotedescriptionfailed",h)})}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 Xc(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(){Y.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(){Y.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(){Y.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){Y.debug("newDTMF()"),this.emit("newDTMF",a)}},{key:"newInfo",value:function(a){Y.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?(Y.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Y.debug("_isReadyToReOffer() | session not established yet"),!1):(Y.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(Y.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Y.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(_){Y.warn("close() | error closing the RTCPeerConnection: %o",_)}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=Lr.T1;function _(){this._status===ee.STATUS_WAITING_FOR_ACK&&(a.reply(200,null,["Contact: ".concat(this._contact)],s),r<Lr.T2&&(r=r*2,r>Lr.T2&&(r=Lr.T2)),this._timers.invite2xxTimer=setTimeout(_.bind(this),r))}this._timers.invite2xxTimer=setTimeout(_.bind(this),r)}},{key:"_setACKTimer",value:function(){var a=this;this._timers.ackTimer=setTimeout(function(){a._status===ee.STATUS_WAITING_FOR_ACK&&(Y.debug("no ACK received, terminating the session"),clearTimeout(a._timers.invite2xxTimer),a.sendRequest(ce.BYE),a._ended("remote",null,ce.causes.NO_ACK))},Lr.TIMER_H)}},{key:"_createRTCConnection",value:function(a,s){var r=this;this._connection=new RTCPeerConnection(a,s),this._connection.addEventListener("iceconnectionstatechange",function(){var _=r._connection.iceConnectionState;_==="failed"&&r.terminate({cause:ce.causes.RTP_TIMEOUT,status_code:408,reason_phrase:ce.causes.RTP_TIMEOUT})}),Y.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(a,s){var r=this;if(Y.debug("createLocalDescription()"),a!=="offer"&&a!=="answer")throw new Error('createLocalDescription() | invalid type "'.concat(a,'"'));var _=this._connection;return this._rtcReady=!1,Promise.resolve().then(function(){return a==="offer"?_.createOffer(s).catch(function(d){return Y.warn('emit "peerconnection:createofferfailed" [error:%o]',d),r.emit("peerconnection:createofferfailed",d),Promise.reject(d)}):_.createAnswer(s).catch(function(d){return Y.warn('emit "peerconnection:createanswerfailed" [error:%o]',d),r.emit("peerconnection:createanswerfailed",d),Promise.reject(d)})}).then(function(d){return _.setLocalDescription(d).catch(function(h){return r._rtcReady=!0,Y.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',h),r.emit("peerconnection:setlocaldescriptionfailed",h),Promise.reject(h)})}).then(function(){var d=s&&s.iceRestart;if(_.iceGatheringState==="complete"&&!d||_.iceGatheringState==="gathering"&&r._iceReady){r._rtcReady=!0;var h={originator:"local",type:a,sdp:_.localDescription.sdp};return Y.debug('emit "sdp"'),r.emit("sdp",h),Promise.resolve(h.sdp)}return new Promise(function(g){var T=!1,S,E;r._iceReady=!1;var A=function(){_.removeEventListener("icecandidate",S),_.removeEventListener("icegatheringstatechange",E),T=!0,r._rtcReady=!0,r._iceReady=!0;var C={originator:"local",type:a,sdp:_.localDescription.sdp};Y.debug('emit "sdp"'),r.emit("sdp",C),g(C.sdp)};_.addEventListener("icecandidate",S=function(C){var H=C.candidate;H?r.emit("icecandidate",{candidate:H,ready:A}):T||A()}),_.addEventListener("icegatheringstatechange",E=function(){_.iceGatheringState==="complete"&&!T&&A()})})})}},{key:"_createDialog",value:function(a,s,r){var _=s==="UAS"?a.to_tag:a.from_tag,d=s==="UAS"?a.from_tag:a.to_tag,h=a.call_id+_+d,g=this._earlyDialogs[h];if(r)return g?!0:(g=new ql(this,a,s,ql.C.STATUS_EARLY),g.error?(Y.debug(g.error),this._failed("remote",a,ce.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[h]=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[h],!0;var T=new ql(this,a,s);return T.error?(Y.debug(T.error),this._failed("remote",a,ce.causes.INTERNAL_ERROR),!1):(this._dialog=T,!0)}},{key:"_receiveReinvite",value:function(a){var s=this;Y.debug("receiveReinvite()");var r=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,_={request:a,callback:void 0,reject:h.bind(this)},d=!1;function h(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};d=!0;var S=T.status_code||403,E=T.reason_phrase||"",A=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,A)}if(this.emit("reinvite",_),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"){Y.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){Y.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 _.callback=="function"&&_.callback()}}},{key:"_receiveUpdate",value:function(a){var s=this;Y.debug("receiveUpdate()");var r=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,_={request:a,callback:void 0,reject:h.bind(this)},d=!1;function h(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};d=!0;var S=T.status_code||403,E=T.reason_phrase||"",A=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,A)}if(this.emit("update",_),d)return;if(!a.body){g.call(this,null);return}if(r!=="application/sdp"){Y.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){Y.warn(T)});function g(T){var S=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,S),a.reply(200,null,S,T),typeof _.callback=="function"&&_.callback()}}},{key:"_processInDialogSdpOffer",value:function(a){var s=this;Y.debug("_processInDialogSdpOffer()");var r=a.parseSDP(),_=!1,d=_s(r.media),h;try{for(d.s();!(h=d.n()).done;){var g=h.value;if(Bl.indexOf(g.type)!==-1){var T=g.direction||r.direction||"sendrecv";if(T==="sendonly"||T==="inactive")_=!0;else{_=!1;break}}}}catch(A){d.e(A)}finally{d.f()}var S={originator:"remote",type:"offer",sdp:a.body};Y.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(A){throw a.reply(488),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',A),s.emit("peerconnection:setremotedescriptionfailed",A),A})}).then(function(){if(s._status===ee.STATUS_TERMINATED)throw new Error("terminated");s._remoteHold===!0&&_===!1?(s._remoteHold=!1,s._onunhold("remote")):s._remoteHold===!1&&_===!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(A){throw a.reply(500),Y.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',A),A})}).catch(function(A){Y.warn("_processInDialogSdpOffer() failed [error: %o]",A)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(a){var s=this;if(Y.debug("receiveRefer()"),!a.refer_to){Y.debug("no Refer-To header field present in REFER"),a.reply(400);return}if(a.refer_to.uri.scheme!==ce.SIP){Y.debug("Refer-To header field points to a non-SIP URI scheme"),a.reply(416);return}a.reply(202);var r=new Y_(this,a.cseq);Y.debug('emit "refer"'),this.emit("refer",{request:a,accept:function(g,T){_.call(s,g,T)},reject:function(){d.call(s)}});function _(h){var g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(h=typeof h=="function"?h: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 A=E.response;r.notify(A.status_code,A.reason_phrase)}),T.on("accepted",function(E){var A=E.response;r.notify(A.status_code,A.reason_phrase)}),T.on("_failed",function(E){var A=E.message,R=E.cause;A?r.notify(A.status_code,A.reason_phrase):r.notify(487,R)}),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,h)}function d(){r.notify(603)}}},{key:"_receiveNotify",value:function(a){switch(Y.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;Y.debug("receiveReplaces()");function r(d){var h=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(){h.terminate()}),g.init_incoming(a,d)}function _(){Y.debug("Replaced INVITE rejected by the user"),a.reply(486)}this.emit("replaces",{request:a,accept:function(h){r.call(s,h)},reject:function(){_.call(s)}})}},{key:"_sendInitialRequest",value:function(a,s,r){var _=this,d=new K_(this._ua,this._request,{onRequestTimeout:function(){_.onRequestTimeout()},onTransportError:function(){_.onTransportError()},onAuthenticated:function(g){_._request=g},onReceiveResponse:function(g){_._receiveInviteResponse(g)}});Promise.resolve().then(function(){if(r)return r;if(a.audio||a.video)return _._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(function(h){throw _._status===ee.STATUS_TERMINATED?new Error("terminated"):(_._failed("local",null,ce.causes.USER_DENIED_MEDIA_ACCESS),Y.warn('emit "getusermediafailed" [error:%o]',h),_.emit("getusermediafailed",h),h)})}).then(function(h){if(_._status===ee.STATUS_TERMINATED)throw new Error("terminated");return _._localMediaStream=h,h&&h.getTracks().forEach(function(g){_._connection.addTrack(g,h)}),_._connecting(_._request),_._createLocalDescription("offer",s).catch(function(g){throw _._failed("local",null,ce.causes.WEBRTC_ERROR),g})}).then(function(h){if(_._is_canceled||_._status===ee.STATUS_TERMINATED)throw new Error("terminated");_._request.body=h,_._status=ee.STATUS_INVITE_SENT,Y.debug('emit "sending" [request:%o]',_._request),_.emit("sending",{request:_._request}),d.send()}).catch(function(h){_._status!==ee.STATUS_TERMINATED&&Y.warn(h)})}},{key:"_getDTMFRTPSender",value:function(){var a=this._connection.getSenders().find(function(s){return s.track&&s.track.kind==="audio"});if(!(a&&a.dtmf)){Y.warn("sendDTMF() | no local audio track to send DTMF with");return}return a.dtmf}},{key:"_receiveInviteResponse",value:function(a){var s=this;if(Y.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){Y.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){Y.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 _={originator:"remote",type:"answer",sdp:a.body};Y.debug('emit "sdp"'),this.emit("sdp",_);var d=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(d)}).then(function(){return s._progress("remote",a)}).catch(function(S){Y.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 h={originator:"remote",type:"answer",sdp:a.body};Y.debug('emit "sdp"'),this.emit("sdp",h);var g=new RTCSessionDescription({type:"answer",sdp:h.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),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),s.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,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Y.debug("sendReinvite()");var r=Ge.cloneArray(s.extraHeaders),_=Ge.cloneObject(s.eventHandlers),d=s.rtcOfferConstraints||this._rtcOfferConstraints||null,h=!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};Y.debug('emit "sdp"'),a.emit("sdp",E),a.sendRequest(ce.INVITE,{extraHeaders:r,body:S,eventHandlers:{onSuccessResponse:function(R){g.call(a,R),h=!0},onErrorResponse:function(R){T.call(a,R)},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),!h)){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 A={originator:"remote",type:"answer",sdp:S.body};Y.debug('emit "sdp"'),this.emit("sdp",A);var R=new RTCSessionDescription({type:"answer",sdp:A.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return E._connection.setRemoteDescription(R)}).then(function(){_.succeeded&&_.succeeded(S)}).catch(function(C){T.call(E),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',C),E.emit("peerconnection:setremotedescriptionfailed",C)})}}function T(S){_.failed&&_.failed(S)}}},{key:"_sendUpdate",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Y.debug("sendUpdate()");var r=Ge.cloneArray(s.extraHeaders),_=Ge.cloneObject(s.eventHandlers),d=s.rtcOfferConstraints||this._rtcOfferConstraints||null,h=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")),h?(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 A={originator:"local",type:"offer",sdp:E};Y.debug('emit "sdp"'),a.emit("sdp",A),a.sendRequest(ce.UPDATE,{extraHeaders:r,body:E,eventHandlers:{onSuccessResponse:function(C){T.call(a,C),g=!0},onErrorResponse:function(C){S.call(a,C)},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(A){T.call(a,A)},onErrorResponse:function(A){S.call(a,A)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}});function T(E){var A=this;if(this._status!==ee.STATUS_TERMINATED&&!g)if(this._handleSessionTimersInIncomingResponse(E),h){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 R={originator:"remote",type:"answer",sdp:E.body};Y.debug('emit "sdp"'),this.emit("sdp",R);var C=new RTCSessionDescription({type:"answer",sdp:R.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return A._connection.setRemoteDescription(C)}).then(function(){_.succeeded&&_.succeeded(E)}).catch(function(H){S.call(A),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',H),A.emit("peerconnection:setremotedescriptionfailed",H)})}else _.succeeded&&_.succeeded(E)}function S(E){_.failed&&_.failed(E)}}},{key:"_acceptAndTerminate",value:function(a,s,r){Y.debug("acceptAndTerminate()");var _=[];s&&(r=r||ce.REASON_PHRASE[s]||"",_.push("Reason: SIP ;cause=".concat(s,'; text="').concat(r,'"'))),(this._dialog||this._createDialog(a,"UAC"))&&(this.sendRequest(ce.ACK),this.sendRequest(ce.BYE,{extraHeaders:_})),this._status=ee.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(a){if(!this._localHold&&!this._remoteHold)return a;if(a=Jc.parse(a),this._localHold&&!this._remoteHold){Y.debug("mangleOffer() | me on hold, mangling offer");var s=_s(a.media),r;try{for(s.s();!(r=s.n()).done;){var _=r.value;Bl.indexOf(_.type)!==-1&&(_.direction?_.direction==="sendrecv"?_.direction="sendonly":_.direction==="recvonly"&&(_.direction="inactive"):_.direction="sendonly")}}catch(A){s.e(A)}finally{s.f()}}else if(this._localHold&&this._remoteHold){Y.debug("mangleOffer() | both on hold, mangling offer");var d=_s(a.media),h;try{for(d.s();!(h=d.n()).done;){var g=h.value;Bl.indexOf(g.type)!==-1&&(g.direction="inactive")}}catch(A){d.e(A)}finally{d.f()}}else if(this._remoteHold){Y.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;Bl.indexOf(E.type)!==-1&&(E.direction?E.direction==="sendrecv"?E.direction="recvonly":E.direction==="recvonly"&&(E.direction="inactive"):E.direction="recvonly")}}catch(A){T.e(A)}finally{T.f()}}return Jc.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()&&(Y.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&&(Y.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(h){return h.track&&h.track.kind==="audio"}),r=_s(s),_;try{for(r.s();!(_=r.n()).done;){var d=_.value;d.track.enabled=!a}}catch(h){r.e(h)}finally{r.f()}}},{key:"_toggleMuteVideo",value:function(a){var s=this._connection.getSenders().filter(function(h){return h.track&&h.track.kind==="video"}),r=_s(s),_;try{for(r.s();!(_=r.n()).done;){var d=_.value;d.track.enabled=!a}}catch(h){r.e(h)}finally{r.f()}}},{key:"_newRTCSession",value:function(a,s){Y.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:a,session:this,request:s})}},{key:"_connecting",value:function(a){Y.debug("session connecting"),Y.debug('emit "connecting"'),this.emit("connecting",{request:a})}},{key:"_progress",value:function(a,s){Y.debug("session progress"),Y.debug('emit "progress"'),this.emit("progress",{originator:a,response:s||null})}},{key:"_accepted",value:function(a,s){Y.debug("session accepted"),this._start_time=new Date,Y.debug('emit "accepted"'),this.emit("accepted",{originator:a,response:s||null})}},{key:"_confirmed",value:function(a,s){Y.debug("session confirmed"),this._is_confirmed=!0,Y.debug('emit "confirmed"'),this.emit("confirmed",{originator:a,ack:s||null})}},{key:"_ended",value:function(a,s,r){Y.debug("session ended"),this._end_time=new Date,this._close(),Y.debug('emit "ended"'),this.emit("ended",{originator:a,message:s||null,cause:r})}},{key:"_failed",value:function(a,s,r){Y.debug("session failed"),Y.debug('emit "_failed"'),this.emit("_failed",{originator:a,message:s||null,cause:r}),this._close(),Y.debug('emit "failed"'),this.emit("failed",{originator:a,message:s||null,cause:r})}},{key:"_onhold",value:function(a){Y.debug("session onhold"),this._setLocalMediaStatus(),Y.debug('emit "hold"'),this.emit("hold",{originator:a})}},{key:"_onunhold",value:function(a){Y.debug("session onunhold"),this._setLocalMediaStatus(),Y.debug('emit "unhold"'),this.emit("unhold",{originator:a})}},{key:"_onmute",value:function(a){var s=a.audio,r=a.video;Y.debug("session onmute"),this._setLocalMediaStatus(),Y.debug('emit "muted"'),this.emit("muted",{audio:s,video:r})}},{key:"_onunmute",value:function(a){var s=a.audio,r=a.video;Y.debug("session onunmute"),this._setLocalMediaStatus(),Y.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}(B_);function Gl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Gl=function(n){return typeof n}:Gl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Gl(c)}function X_(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Q_(c,t,n){return t&&Zc(c.prototype,t),n&&Zc(c,n),c}function Z_(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&&Aa(c,t)}function Aa(c,t){return Aa=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Aa(c,t)}function ep(c){var t=np();return function(){var o=Wl(c),a;if(t){var s=Wl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return tp(this,a)}}function tp(c,t){return t&&(Gl(t)==="object"||typeof t=="function")?t:sp(c)}function sp(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function np(){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 Wl(c){return Wl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Wl(c)}var rp=ct.EventEmitter,ip=ft,Ra=nt,lp=fs,$r=Rt(),op=Ur,ef=bs,ap=Is(),Kl=new ip("Message"),up=function(c){Z_(n,c);var t=ep(n);function n(o){var a;return X_(this,n),a=t.call(this),a._ua=o,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 Q_(n,[{key:"send",value:function(a,s){var r=this,_=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 h=$r.cloneArray(_.extraHeaders),g=$r.cloneObject(_.eventHandlers),T=_.contentType||"text/plain",S={};_.fromUserName&&(S.from_uri=new ap("sip",_.fromUserName,this._ua.configuration.uri.host),h.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),_.fromDisplayName&&(S.from_display_name=_.fromDisplayName);for(var E in g)Object.prototype.hasOwnProperty.call(g,E)&&this.on(E,g[E]);h.push("Content-Type: ".concat(T)),this._request=new lp.OutgoingRequest(Ra.MESSAGE,a,this._ua,S,h),s&&(this._request.body=s);var A=new op(this._ua,this._request,{onRequestTimeout:function(){r._onRequestTimeout()},onTransportError:function(){r._onTransportError()},onReceiveResponse:function(C){r._receiveResponse(C)}});this._newMessage("local",this._request),A.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=$r.cloneArray(a.extraHeaders),r=a.body;if(this._direction!=="incoming")throw new ef.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,_=$r.cloneArray(a.extraHeaders),d=a.body;if(this._direction!=="incoming")throw new ef.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,_,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=$r.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){Kl.debug("MESSAGE failed"),this._close(),Kl.debug('emit "failed"'),this.emit("failed",{originator:a,response:s||null,cause:r})}},{key:"_succeeded",value:function(a,s){Kl.debug("MESSAGE succeeded"),this._close(),Kl.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}(rp);function Yl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Yl=function(n){return typeof n}:Yl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Yl(c)}function cp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function tf(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function fp(c,t,n){return t&&tf(c.prototype,t),n&&tf(c,n),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&&ba(c,t)}function ba(c,t){return ba=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},ba(c,t)}function hp(c){var t=mp();return function(){var o=Jl(c),a;if(t){var s=Jl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return _p(this,a)}}function _p(c,t){return t&&(Yl(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 Jl(c){return Jl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Jl(c)}var gp=ct.EventEmitter,Tp=ft,Ia=nt,vp=fs,Hr=Rt(),Sp=Ur,sf=bs,zl=new Tp("Options"),Ep=function(c){dp(n,c);var t=hp(n);function n(o){var a;return cp(this,n),a=t.call(this),a._ua=o,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 fp(n,[{key:"send",value:function(a,s){var r=this,_=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 h=Hr.cloneArray(_.extraHeaders),g=Hr.cloneObject(_.eventHandlers),T=_.contentType||"application/sdp";for(var S in g)Object.prototype.hasOwnProperty.call(g,S)&&this.on(S,g[S]);h.push("Content-Type: ".concat(T)),this._request=new vp.OutgoingRequest(Ia.OPTIONS,a,this._ua,null,h),s&&(this._request.body=s);var E=new Sp(this._ua,this._request,{onRequestTimeout:function(){r._onRequestTimeout()},onTransportError:function(){r._onTransportError()},onReceiveResponse:function(R){r._receiveResponse(R)}});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=Hr.cloneArray(a.extraHeaders),r=a.body;if(this._direction!=="incoming")throw new sf.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,_=Hr.cloneArray(a.extraHeaders),d=a.body;if(this._direction!=="incoming")throw new sf.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,_,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=Hr.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){zl.debug("OPTIONS failed"),this._close(),zl.debug('emit "failed"'),this.emit("failed",{originator:a,response:s||null,cause:r})}},{key:"_succeeded",value:function(a,s){zl.debug("OPTIONS succeeded"),this._close(),zl.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}(gp),wa={},yp=ft,Oa=Rt(),Cp=ts(),Fr=new yp("Socket");wa.isSocket=function(c){if(Array.isArray(c))return!1;if(typeof c>"u")return Fr.warn("undefined JsSIP.Socket instance"),!1;try{if(!Oa.isString(c.url))throw Fr.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!Oa.isString(c.via_transport))throw Fr.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(Cp.parse(c.sip_uri,"SIP_URI")===-1)throw Fr.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 Fr.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 Ap(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function nf(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Rp(c,t,n){return t&&nf(c.prototype,t),n&&nf(c,n),c}var bp=ft,Ip=wa,rf=nt,xt=new bp("Transport"),$t={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}},wp=function(){function c(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:$t.recovery_options;Ap(this,c),xt.debug("new()"),this.status=$t.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(o){xt.warn("cannot use TextDecoder: ".concat(o))}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(o){if(!Ip.isSocket(o.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(o.weight&&!Number(o.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:o.socket,weight:o.weight||0,status:$t.SOCKET_STATUS_READY})},this),this._getSocket()}return Rp(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=$t.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=$t.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(xt.debug("send()"),!this.isConnected())return xt.warn("unable to send message, transport is not connected"),!1;var o=n.toString();return xt.debug(`sending message:
50
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,_;return{s:function(){n=c[Symbol.iterator]()},n:function(){var h=n.next();return s=h.done,h},e:function(h){r=!0,_=h},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw _}}}}function L_(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,o=new Array(t);n<t;n++)o[n]=c[n];return o}function $_(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function Kc(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Yc(c,t,n){return t&&Kc(c.prototype,t),n&&Kc(c,n),c}function H_(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&&Ca(c,t)}function Ca(c,t){return Ca=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Ca(c,t)}function F_(c){var t=q_();return function(){var o=jl(c),a;if(t){var s=jl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return V_(this,a)}}function V_(c,t){return t&&(Vl(t)==="object"||typeof t=="function")?t:j_(c)}function j_(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function q_(){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 jl(c){return jl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},jl(c)}var B_=ct.EventEmitter,Jc=Nt,G_=ft,ce=nt,Zs=bs,zc=xr,Ge=Rt(),Lr=Ac,W_=fs,ql=Jh,K_=Ur,Pt=a_,Xc=S_,Y_=R_,J_=M_,Qc=Is(),Y=new G_("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"],z_=function(c){H_(n,c);var t=F_(n);Yc(n,null,[{key:"C",get:function(){return ee}}]);function n(o){var a;return $_(this,n),Y.debug("new"),a=t.call(this),a._id=null,a._ua=o,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 Yc(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;Y.debug("connect()");var _=a,d=Ge.cloneObject(s.eventHandlers),h=Ge.cloneArray(s.extraHeaders),m=Ge.cloneObject(s.mediaConstraints,{audio:!0,video:!0}),T=s.mediaStream||null,S=Ge.cloneObject(s.pcConfig,{iceServers:[]}),E=s.rtcConstraints||null,A=s.rtcOfferConstraints||null;if(this._rtcOfferConstraints=A,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 Zs.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Zs.NotSupportedError("WebRTC not supported");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(_));this._sessionTimers.enabled&&Ge.isDecimal(s.sessionTimersExpires)&&(s.sessionTimersExpires>=ce.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=s.sessionTimersExpires:this._sessionTimers.defaultExpires=ce.SESSION_EXPIRES);for(var R in d)Object.prototype.hasOwnProperty.call(d,R)&&this.on(R,d[R]);this._from_tag=Ge.newTag();var C=s.anonymous||!1,H={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:C,outbound:!0}),C?(H.from_display_name="Anonymous",H.from_uri=new Qc("sip","anonymous","anonymous.invalid"),h.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),h.push("Privacy: id")):s.fromUserName&&(H.from_uri=new Qc("sip",s.fromUserName,this._ua.configuration.uri.host),h.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),s.fromDisplayName&&(H.from_display_name=s.fromDisplayName),h.push("Contact: ".concat(this._contact)),h.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&h.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new W_.InitialOutgoingInviteRequest(a,this._ua,H,h),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(m,A,T)}},{key:"init_incoming",value:function(a,s){var r=this;Y.debug("init_incoming()");var _,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")&&(_=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),_&&(this._timers.expiresTimer=setTimeout(function(){r._status===ee.STATUS_WAITING_FOR_ANSWER&&(a.reply(487),r._failed("system",null,ce.causes.EXPIRES))},_)),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]:{};Y.debug("answer()");var r=this._request,_=Ge.cloneArray(s.extraHeaders),d=Ge.cloneObject(s.mediaConstraints),h=s.mediaStream||null,m=Ge.cloneObject(s.pcConfig,{iceServers:[]}),T=s.rtcConstraints||null,S=s.rtcAnswerConstraints||null,E=Ge.cloneObject(s.rtcOfferConstraints),A,R=!1,C=!1,H=!1,k=!1;if(this._rtcAnswerConstraints=S,this._rtcOfferConstraints=s.rtcOfferConstraints||null,this._data=s.data||this._data,this._direction!=="incoming")throw new Zs.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==ee.STATUS_WAITING_FOR_ANSWER)throw new Zs.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Ge.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),_.unshift("Contact: ".concat(this._contact));var re=r.parseSDP();Array.isArray(re.media)||(re.media=[re.media]);var x=_s(re.media),F;try{for(x.s();!(F=x.n()).done;){var _e=F.value;_e.type==="audio"&&(R=!0,(!_e.direction||_e.direction==="sendrecv")&&(H=!0)),_e.type==="video"&&(C=!0,(!_e.direction||_e.direction==="sendrecv")&&(k=!0))}}catch(V){x.e(V)}finally{x.f()}if(h&&d.audio===!1){A=h.getAudioTracks();var pe=_s(A),P;try{for(pe.s();!(P=pe.n()).done;){var N=P.value;h.removeTrack(N)}}catch(V){pe.e(V)}finally{pe.f()}}if(h&&d.video===!1){A=h.getVideoTracks();var q=_s(A),j;try{for(q.s();!(j=q.n()).done;){var K=j.value;h.removeTrack(K)}}catch(V){q.e(V)}finally{q.f()}}!h&&d.audio===void 0&&(d.audio=H),!h&&d.video===void 0&&(d.video=k),!h&&!R&&!E.offerToReceiveAudio&&(d.audio=!1),!h&&!C&&!E.offerToReceiveVideo&&(d.video=!1),this._createRTCConnection(m,T),Promise.resolve().then(function(){if(h)return h;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),Y.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(z){a._connection.addTrack(z,V)})}).then(function(){if(!a._late_sdp){var V={originator:"remote",type:"offer",sdp:r.body};Y.debug('emit "sdp"'),a.emit("sdp",V);var z=new RTCSessionDescription({type:"offer",sdp:V.sdp});return a._connectionPromiseQueue=a._connectionPromiseQueue.then(function(){return a._connection.setRemoteDescription(z)}).catch(function(D){throw r.reply(488),a._failed("system",null,ce.causes.WEBRTC_ERROR),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),a.emit("peerconnection:setremotedescriptionfailed",D),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,_),r.reply(200,null,_,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&&Y.warn(V)})}},{key:"terminate",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Y.debug("terminate()");var r=s.cause||ce.causes.BYE,_=Ge.cloneArray(s.extraHeaders),d=s.body,h,m=s.status_code,T=s.reason_phrase;if(this._status===ee.STATUS_TERMINATED)throw new Zs.InvalidStateError(this._status);switch(this._status){case ee.STATUS_NULL:case ee.STATUS_INVITE_SENT:case ee.STATUS_1XX_RECEIVED:if(Y.debug("canceling session"),m&&(m<200||m>=700))throw new TypeError("Invalid status_code: ".concat(m));m&&(T=T||ce.REASON_PHRASE[m]||"",h="SIP ;cause=".concat(m,' ;text="').concat(T,'"')),this._status===ee.STATUS_NULL||this._status===ee.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=h):this._status===ee.STATUS_1XX_RECEIVED&&this._request.cancel(h),this._status=ee.STATUS_CANCELED,this._failed("local",null,ce.causes.CANCELED);break;case ee.STATUS_WAITING_FOR_ANSWER:case ee.STATUS_ANSWERED:if(Y.debug("rejecting session"),m=m||480,m<300||m>=700)throw new TypeError("Invalid status_code: ".concat(m));this._request.reply(m,T,_,d),this._failed("local",null,ce.causes.REJECTED);break;case ee.STATUS_WAITING_FOR_ACK:case ee.STATUS_CONFIRMED:if(Y.debug("terminating session"),T=s.reason_phrase||ce.REASON_PHRASE[m]||"",m&&(m<200||m>=700))throw new TypeError("Invalid status_code: ".concat(m));if(m&&_.push("Reason: SIP ;cause=".concat(m,'; text="').concat(T,'"')),this._status===ee.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==zc.C.STATUS_TERMINATED){var S=this._dialog;this.receiveRequest=function(E){var A=E.method;A===ce.ACK&&(a.sendRequest(ce.BYE,{extraHeaders:_,body:d}),S.terminate())},this._request.server_transaction.on("stateChanged",function(){a._request.server_transaction.state===zc.C.STATUS_TERMINATED&&(a.sendRequest(ce.BYE,{extraHeaders:_,body:d}),S.terminate())}),this._ended("local",null,r),this._dialog=S,this._ua.newDialog(S)}else this.sendRequest(ce.BYE,{extraHeaders:_,body:d}),this._ended("local",null,r)}}},{key:"sendDTMF",value:function(a){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Y.debug("sendDTMF() | tones: %s",a);var r=0,_=s.duration||null,d=s.interToneGap||null,h=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 Zs.InvalidStateError(this._status);if(h!==ce.DTMF_TRANSPORT.INFO&&h!==ce.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(h));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(_&&!Ge.isDecimal(_))throw new TypeError("Invalid tone duration: ".concat(_));if(_?_<Pt.C.MIN_DURATION?(Y.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(Pt.C.MIN_DURATION," milliseconds")),_=Pt.C.MIN_DURATION):_>Pt.C.MAX_DURATION?(Y.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(Pt.C.MAX_DURATION," milliseconds")),_=Pt.C.MAX_DURATION):_=Math.abs(_):_=Pt.C.DEFAULT_DURATION,s.duration=_,d&&!Ge.isDecimal(d))throw new TypeError("Invalid interToneGap: ".concat(d));if(d?d<Pt.C.MIN_INTER_TONE_GAP?(Y.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,h===ce.DTMF_TRANSPORT.RFC2833){var m=this._getDTMFRTPSender();m&&(a=m.toneBuffer+a,m.insertDTMF(a,_,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 A=this._tones[r];if(r+=1,A===",")E=2e3;else{var R=new Pt(this);s.eventHandlers={onFailed:function(){S._tones=null}},R.send(A,s),E=_+d}setTimeout(T.bind(this),E)}}},{key:"sendInfo",value:function(a,s){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(Y.debug("sendInfo()"),this._status!==ee.STATUS_CONFIRMED&&this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_1XX_RECEIVED)throw new Zs.InvalidStateError(this._status);var _=new Xc(this);_.send(a,s,r)}},{key:"mute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};Y.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};Y.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(Y.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 _={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:_,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:_,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(Y.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 _={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:_,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:_,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;Y.debug("renegotiate()");var _=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:_,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:d,rtcOfferConstraints:_,extraHeaders:s.extraHeaders}),!0}},{key:"refer",value:function(a,s){var r=this;Y.debug("refer()");var _=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(_));var d=new J_(this);d.sendRefer(a,s);var h=d.id;return this._referSubscribers[h]=d,d.on("requestFailed",function(){delete r._referSubscribers[h]}),d.on("accepted",function(){delete r._referSubscribers[h]}),d.on("failed",function(){delete r._referSubscribers[h]}),d}},{key:"sendRequest",value:function(a,s){return Y.debug("sendRequest()"),this._dialog.sendRequest(a,s)}},{key:"receiveRequest",value:function(a){var s=this;if(Y.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};Y.debug('emit "sdp"'),this.emit("sdp",r);var _=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(_)}).then(function(){s._is_confirmed||s._confirmed("remote",a)}).catch(function(h){s.terminate({cause:ce.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',h),s.emit("peerconnection:setremotedescriptionfailed",h)})}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 Xc(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(){Y.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(){Y.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(){Y.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){Y.debug("newDTMF()"),this.emit("newDTMF",a)}},{key:"newInfo",value:function(a){Y.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?(Y.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Y.debug("_isReadyToReOffer() | session not established yet"),!1):(Y.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(Y.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Y.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(_){Y.warn("close() | error closing the RTCPeerConnection: %o",_)}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=Lr.T1;function _(){this._status===ee.STATUS_WAITING_FOR_ACK&&(a.reply(200,null,["Contact: ".concat(this._contact)],s),r<Lr.T2&&(r=r*2,r>Lr.T2&&(r=Lr.T2)),this._timers.invite2xxTimer=setTimeout(_.bind(this),r))}this._timers.invite2xxTimer=setTimeout(_.bind(this),r)}},{key:"_setACKTimer",value:function(){var a=this;this._timers.ackTimer=setTimeout(function(){a._status===ee.STATUS_WAITING_FOR_ACK&&(Y.debug("no ACK received, terminating the session"),clearTimeout(a._timers.invite2xxTimer),a.sendRequest(ce.BYE),a._ended("remote",null,ce.causes.NO_ACK))},Lr.TIMER_H)}},{key:"_createRTCConnection",value:function(a,s){var r=this;this._connection=new RTCPeerConnection(a,s),this._connection.addEventListener("iceconnectionstatechange",function(){var _=r._connection.iceConnectionState;_==="failed"&&r.terminate({cause:ce.causes.RTP_TIMEOUT,status_code:408,reason_phrase:ce.causes.RTP_TIMEOUT})}),Y.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(a,s){var r=this;if(Y.debug("createLocalDescription()"),a!=="offer"&&a!=="answer")throw new Error('createLocalDescription() | invalid type "'.concat(a,'"'));var _=this._connection;return this._rtcReady=!1,Promise.resolve().then(function(){return a==="offer"?_.createOffer(s).catch(function(d){return Y.warn('emit "peerconnection:createofferfailed" [error:%o]',d),r.emit("peerconnection:createofferfailed",d),Promise.reject(d)}):_.createAnswer(s).catch(function(d){return Y.warn('emit "peerconnection:createanswerfailed" [error:%o]',d),r.emit("peerconnection:createanswerfailed",d),Promise.reject(d)})}).then(function(d){return _.setLocalDescription(d).catch(function(h){return r._rtcReady=!0,Y.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',h),r.emit("peerconnection:setlocaldescriptionfailed",h),Promise.reject(h)})}).then(function(){var d=s&&s.iceRestart;if(_.iceGatheringState==="complete"&&!d||_.iceGatheringState==="gathering"&&r._iceReady){r._rtcReady=!0;var h={originator:"local",type:a,sdp:_.localDescription.sdp};return Y.debug('emit "sdp"'),r.emit("sdp",h),Promise.resolve(h.sdp)}return new Promise(function(m){var T=!1,S,E;r._iceReady=!1;var A=function(){_.removeEventListener("icecandidate",S),_.removeEventListener("icegatheringstatechange",E),T=!0,r._rtcReady=!0,r._iceReady=!0;var C={originator:"local",type:a,sdp:_.localDescription.sdp};Y.debug('emit "sdp"'),r.emit("sdp",C),m(C.sdp)};_.addEventListener("icecandidate",S=function(C){var H=C.candidate;H?r.emit("icecandidate",{candidate:H,ready:A}):T||A()}),_.addEventListener("icegatheringstatechange",E=function(){_.iceGatheringState==="complete"&&!T&&A()})})})}},{key:"_createDialog",value:function(a,s,r){var _=s==="UAS"?a.to_tag:a.from_tag,d=s==="UAS"?a.from_tag:a.to_tag,h=a.call_id+_+d,m=this._earlyDialogs[h];if(r)return m?!0:(m=new ql(this,a,s,ql.C.STATUS_EARLY),m.error?(Y.debug(m.error),this._failed("remote",a,ce.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[h]=m,!0));if(this._from_tag=a.from_tag,this._to_tag=a.to_tag,m)return m.update(a,s),this._dialog=m,delete this._earlyDialogs[h],!0;var T=new ql(this,a,s);return T.error?(Y.debug(T.error),this._failed("remote",a,ce.causes.INTERNAL_ERROR),!1):(this._dialog=T,!0)}},{key:"_receiveReinvite",value:function(a){var s=this;Y.debug("receiveReinvite()");var r=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,_={request:a,callback:void 0,reject:h.bind(this)},d=!1;function h(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};d=!0;var S=T.status_code||403,E=T.reason_phrase||"",A=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,A)}if(this.emit("reinvite",_),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){m.call(s,T)}).catch(function(){a.reply(500)});return}if(r!=="application/sdp"){Y.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(T){s._status!==ee.STATUS_TERMINATED&&m.call(s,T)}).catch(function(T){Y.warn(T)});function m(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 _.callback=="function"&&_.callback()}}},{key:"_receiveUpdate",value:function(a){var s=this;Y.debug("receiveUpdate()");var r=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,_={request:a,callback:void 0,reject:h.bind(this)},d=!1;function h(){var T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};d=!0;var S=T.status_code||403,E=T.reason_phrase||"",A=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,A)}if(this.emit("update",_),d)return;if(!a.body){m.call(this,null);return}if(r!=="application/sdp"){Y.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(T){s._status!==ee.STATUS_TERMINATED&&m.call(s,T)}).catch(function(T){Y.warn(T)});function m(T){var S=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,S),a.reply(200,null,S,T),typeof _.callback=="function"&&_.callback()}}},{key:"_processInDialogSdpOffer",value:function(a){var s=this;Y.debug("_processInDialogSdpOffer()");var r=a.parseSDP(),_=!1,d=_s(r.media),h;try{for(d.s();!(h=d.n()).done;){var m=h.value;if(Bl.indexOf(m.type)!==-1){var T=m.direction||r.direction||"sendrecv";if(T==="sendonly"||T==="inactive")_=!0;else{_=!1;break}}}}catch(A){d.e(A)}finally{d.f()}var S={originator:"remote",type:"offer",sdp:a.body};Y.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(A){throw a.reply(488),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',A),s.emit("peerconnection:setremotedescriptionfailed",A),A})}).then(function(){if(s._status===ee.STATUS_TERMINATED)throw new Error("terminated");s._remoteHold===!0&&_===!1?(s._remoteHold=!1,s._onunhold("remote")):s._remoteHold===!1&&_===!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(A){throw a.reply(500),Y.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',A),A})}).catch(function(A){Y.warn("_processInDialogSdpOffer() failed [error: %o]",A)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(a){var s=this;if(Y.debug("receiveRefer()"),!a.refer_to){Y.debug("no Refer-To header field present in REFER"),a.reply(400);return}if(a.refer_to.uri.scheme!==ce.SIP){Y.debug("Refer-To header field points to a non-SIP URI scheme"),a.reply(416);return}a.reply(202);var r=new Y_(this,a.cseq);Y.debug('emit "refer"'),this.emit("refer",{request:a,accept:function(m,T){_.call(s,m,T)},reject:function(){d.call(s)}});function _(h){var m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(h=typeof h=="function"?h: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 A=E.response;r.notify(A.status_code,A.reason_phrase)}),T.on("accepted",function(E){var A=E.response;r.notify(A.status_code,A.reason_phrase)}),T.on("_failed",function(E){var A=E.message,R=E.cause;A?r.notify(A.status_code,A.reason_phrase):r.notify(487,R)}),a.refer_to.uri.hasHeader("replaces")){var S=decodeURIComponent(a.refer_to.uri.getHeader("replaces"));m.extraHeaders=Ge.cloneArray(m.extraHeaders),m.extraHeaders.push("Replaces: ".concat(S))}T.connect(a.refer_to.uri.toAor(),m,h)}function d(){r.notify(603)}}},{key:"_receiveNotify",value:function(a){switch(Y.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;Y.debug("receiveReplaces()");function r(d){var h=this;if(this._status!==ee.STATUS_WAITING_FOR_ACK&&this._status!==ee.STATUS_CONFIRMED)return!1;var m=new n(this._ua);m.on("confirmed",function(){h.terminate()}),m.init_incoming(a,d)}function _(){Y.debug("Replaced INVITE rejected by the user"),a.reply(486)}this.emit("replaces",{request:a,accept:function(h){r.call(s,h)},reject:function(){_.call(s)}})}},{key:"_sendInitialRequest",value:function(a,s,r){var _=this,d=new K_(this._ua,this._request,{onRequestTimeout:function(){_.onRequestTimeout()},onTransportError:function(){_.onTransportError()},onAuthenticated:function(m){_._request=m},onReceiveResponse:function(m){_._receiveInviteResponse(m)}});Promise.resolve().then(function(){if(r)return r;if(a.audio||a.video)return _._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(function(h){throw _._status===ee.STATUS_TERMINATED?new Error("terminated"):(_._failed("local",null,ce.causes.USER_DENIED_MEDIA_ACCESS),Y.warn('emit "getusermediafailed" [error:%o]',h),_.emit("getusermediafailed",h),h)})}).then(function(h){if(_._status===ee.STATUS_TERMINATED)throw new Error("terminated");return _._localMediaStream=h,h&&h.getTracks().forEach(function(m){_._connection.addTrack(m,h)}),_._connecting(_._request),_._createLocalDescription("offer",s).catch(function(m){throw _._failed("local",null,ce.causes.WEBRTC_ERROR),m})}).then(function(h){if(_._is_canceled||_._status===ee.STATUS_TERMINATED)throw new Error("terminated");_._request.body=h,_._status=ee.STATUS_INVITE_SENT,Y.debug('emit "sending" [request:%o]',_._request),_.emit("sending",{request:_._request}),d.send()}).catch(function(h){_._status!==ee.STATUS_TERMINATED&&Y.warn(h)})}},{key:"_getDTMFRTPSender",value:function(){var a=this._connection.getSenders().find(function(s){return s.track&&s.track.kind==="audio"});if(!(a&&a.dtmf)){Y.warn("sendDTMF() | no local audio track to send DTMF with");return}return a.dtmf}},{key:"_receiveInviteResponse",value:function(a){var s=this;if(Y.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){Y.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){Y.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 _={originator:"remote",type:"answer",sdp:a.body};Y.debug('emit "sdp"'),this.emit("sdp",_);var d=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(d)}).then(function(){return s._progress("remote",a)}).catch(function(S){Y.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 h={originator:"remote",type:"answer",sdp:a.body};Y.debug('emit "sdp"'),this.emit("sdp",h);var m=new RTCSessionDescription({type:"answer",sdp:h.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(m).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),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),s.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,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Y.debug("sendReinvite()");var r=Ge.cloneArray(s.extraHeaders),_=Ge.cloneObject(s.eventHandlers),d=s.rtcOfferConstraints||this._rtcOfferConstraints||null,h=!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};Y.debug('emit "sdp"'),a.emit("sdp",E),a.sendRequest(ce.INVITE,{extraHeaders:r,body:S,eventHandlers:{onSuccessResponse:function(R){m.call(a,R),h=!0},onErrorResponse:function(R){T.call(a,R)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){T()});function m(S){var E=this;if(this._status!==ee.STATUS_TERMINATED&&(this.sendRequest(ce.ACK),!h)){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 A={originator:"remote",type:"answer",sdp:S.body};Y.debug('emit "sdp"'),this.emit("sdp",A);var R=new RTCSessionDescription({type:"answer",sdp:A.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return E._connection.setRemoteDescription(R)}).then(function(){_.succeeded&&_.succeeded(S)}).catch(function(C){T.call(E),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',C),E.emit("peerconnection:setremotedescriptionfailed",C)})}}function T(S){_.failed&&_.failed(S)}}},{key:"_sendUpdate",value:function(){var a=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Y.debug("sendUpdate()");var r=Ge.cloneArray(s.extraHeaders),_=Ge.cloneObject(s.eventHandlers),d=s.rtcOfferConstraints||this._rtcOfferConstraints||null,h=s.sdpOffer||!1,m=!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")),h?(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 A={originator:"local",type:"offer",sdp:E};Y.debug('emit "sdp"'),a.emit("sdp",A),a.sendRequest(ce.UPDATE,{extraHeaders:r,body:E,eventHandlers:{onSuccessResponse:function(C){T.call(a,C),m=!0},onErrorResponse:function(C){S.call(a,C)},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(A){T.call(a,A)},onErrorResponse:function(A){S.call(a,A)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}});function T(E){var A=this;if(this._status!==ee.STATUS_TERMINATED&&!m)if(this._handleSessionTimersInIncomingResponse(E),h){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 R={originator:"remote",type:"answer",sdp:E.body};Y.debug('emit "sdp"'),this.emit("sdp",R);var C=new RTCSessionDescription({type:"answer",sdp:R.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return A._connection.setRemoteDescription(C)}).then(function(){_.succeeded&&_.succeeded(E)}).catch(function(H){S.call(A),Y.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',H),A.emit("peerconnection:setremotedescriptionfailed",H)})}else _.succeeded&&_.succeeded(E)}function S(E){_.failed&&_.failed(E)}}},{key:"_acceptAndTerminate",value:function(a,s,r){Y.debug("acceptAndTerminate()");var _=[];s&&(r=r||ce.REASON_PHRASE[s]||"",_.push("Reason: SIP ;cause=".concat(s,'; text="').concat(r,'"'))),(this._dialog||this._createDialog(a,"UAC"))&&(this.sendRequest(ce.ACK),this.sendRequest(ce.BYE,{extraHeaders:_})),this._status=ee.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(a){if(!this._localHold&&!this._remoteHold)return a;if(a=Jc.parse(a),this._localHold&&!this._remoteHold){Y.debug("mangleOffer() | me on hold, mangling offer");var s=_s(a.media),r;try{for(s.s();!(r=s.n()).done;){var _=r.value;Bl.indexOf(_.type)!==-1&&(_.direction?_.direction==="sendrecv"?_.direction="sendonly":_.direction==="recvonly"&&(_.direction="inactive"):_.direction="sendonly")}}catch(A){s.e(A)}finally{s.f()}}else if(this._localHold&&this._remoteHold){Y.debug("mangleOffer() | both on hold, mangling offer");var d=_s(a.media),h;try{for(d.s();!(h=d.n()).done;){var m=h.value;Bl.indexOf(m.type)!==-1&&(m.direction="inactive")}}catch(A){d.e(A)}finally{d.f()}}else if(this._remoteHold){Y.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;Bl.indexOf(E.type)!==-1&&(E.direction?E.direction==="sendrecv"?E.direction="recvonly":E.direction==="recvonly"&&(E.direction="inactive"):E.direction="recvonly")}}catch(A){T.e(A)}finally{T.f()}}return Jc.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()&&(Y.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&&(Y.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(h){return h.track&&h.track.kind==="audio"}),r=_s(s),_;try{for(r.s();!(_=r.n()).done;){var d=_.value;d.track.enabled=!a}}catch(h){r.e(h)}finally{r.f()}}},{key:"_toggleMuteVideo",value:function(a){var s=this._connection.getSenders().filter(function(h){return h.track&&h.track.kind==="video"}),r=_s(s),_;try{for(r.s();!(_=r.n()).done;){var d=_.value;d.track.enabled=!a}}catch(h){r.e(h)}finally{r.f()}}},{key:"_newRTCSession",value:function(a,s){Y.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:a,session:this,request:s})}},{key:"_connecting",value:function(a){Y.debug("session connecting"),Y.debug('emit "connecting"'),this.emit("connecting",{request:a})}},{key:"_progress",value:function(a,s){Y.debug("session progress"),Y.debug('emit "progress"'),this.emit("progress",{originator:a,response:s||null})}},{key:"_accepted",value:function(a,s){Y.debug("session accepted"),this._start_time=new Date,Y.debug('emit "accepted"'),this.emit("accepted",{originator:a,response:s||null})}},{key:"_confirmed",value:function(a,s){Y.debug("session confirmed"),this._is_confirmed=!0,Y.debug('emit "confirmed"'),this.emit("confirmed",{originator:a,ack:s||null})}},{key:"_ended",value:function(a,s,r){Y.debug("session ended"),this._end_time=new Date,this._close(),Y.debug('emit "ended"'),this.emit("ended",{originator:a,message:s||null,cause:r})}},{key:"_failed",value:function(a,s,r){Y.debug("session failed"),Y.debug('emit "_failed"'),this.emit("_failed",{originator:a,message:s||null,cause:r}),this._close(),Y.debug('emit "failed"'),this.emit("failed",{originator:a,message:s||null,cause:r})}},{key:"_onhold",value:function(a){Y.debug("session onhold"),this._setLocalMediaStatus(),Y.debug('emit "hold"'),this.emit("hold",{originator:a})}},{key:"_onunhold",value:function(a){Y.debug("session onunhold"),this._setLocalMediaStatus(),Y.debug('emit "unhold"'),this.emit("unhold",{originator:a})}},{key:"_onmute",value:function(a){var s=a.audio,r=a.video;Y.debug("session onmute"),this._setLocalMediaStatus(),Y.debug('emit "muted"'),this.emit("muted",{audio:s,video:r})}},{key:"_onunmute",value:function(a){var s=a.audio,r=a.video;Y.debug("session onunmute"),this._setLocalMediaStatus(),Y.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}(B_);function Gl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Gl=function(n){return typeof n}:Gl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Gl(c)}function X_(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 o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Q_(c,t,n){return t&&Zc(c.prototype,t),n&&Zc(c,n),c}function Z_(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&&Aa(c,t)}function Aa(c,t){return Aa=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},Aa(c,t)}function ep(c){var t=np();return function(){var o=Wl(c),a;if(t){var s=Wl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return tp(this,a)}}function tp(c,t){return t&&(Gl(t)==="object"||typeof t=="function")?t:sp(c)}function sp(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function np(){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 Wl(c){return Wl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Wl(c)}var rp=ct.EventEmitter,ip=ft,Ra=nt,lp=fs,$r=Rt(),op=Ur,ef=bs,ap=Is(),Kl=new ip("Message"),up=function(c){Z_(n,c);var t=ep(n);function n(o){var a;return X_(this,n),a=t.call(this),a._ua=o,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 Q_(n,[{key:"send",value:function(a,s){var r=this,_=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 h=$r.cloneArray(_.extraHeaders),m=$r.cloneObject(_.eventHandlers),T=_.contentType||"text/plain",S={};_.fromUserName&&(S.from_uri=new ap("sip",_.fromUserName,this._ua.configuration.uri.host),h.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),_.fromDisplayName&&(S.from_display_name=_.fromDisplayName);for(var E in m)Object.prototype.hasOwnProperty.call(m,E)&&this.on(E,m[E]);h.push("Content-Type: ".concat(T)),this._request=new lp.OutgoingRequest(Ra.MESSAGE,a,this._ua,S,h),s&&(this._request.body=s);var A=new op(this._ua,this._request,{onRequestTimeout:function(){r._onRequestTimeout()},onTransportError:function(){r._onTransportError()},onReceiveResponse:function(C){r._receiveResponse(C)}});this._newMessage("local",this._request),A.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=$r.cloneArray(a.extraHeaders),r=a.body;if(this._direction!=="incoming")throw new ef.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,_=$r.cloneArray(a.extraHeaders),d=a.body;if(this._direction!=="incoming")throw new ef.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,_,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=$r.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){Kl.debug("MESSAGE failed"),this._close(),Kl.debug('emit "failed"'),this.emit("failed",{originator:a,response:s||null,cause:r})}},{key:"_succeeded",value:function(a,s){Kl.debug("MESSAGE succeeded"),this._close(),Kl.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}(rp);function Yl(c){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Yl=function(n){return typeof n}:Yl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Yl(c)}function cp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function tf(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function fp(c,t,n){return t&&tf(c.prototype,t),n&&tf(c,n),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&&ba(c,t)}function ba(c,t){return ba=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},ba(c,t)}function hp(c){var t=gp();return function(){var o=Jl(c),a;if(t){var s=Jl(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return _p(this,a)}}function _p(c,t){return t&&(Yl(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 gp(){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 Jl(c){return Jl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Jl(c)}var mp=ct.EventEmitter,Tp=ft,Ia=nt,vp=fs,Hr=Rt(),Sp=Ur,sf=bs,zl=new Tp("Options"),Ep=function(c){dp(n,c);var t=hp(n);function n(o){var a;return cp(this,n),a=t.call(this),a._ua=o,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 fp(n,[{key:"send",value:function(a,s){var r=this,_=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 h=Hr.cloneArray(_.extraHeaders),m=Hr.cloneObject(_.eventHandlers),T=_.contentType||"application/sdp";for(var S in m)Object.prototype.hasOwnProperty.call(m,S)&&this.on(S,m[S]);h.push("Content-Type: ".concat(T)),this._request=new vp.OutgoingRequest(Ia.OPTIONS,a,this._ua,null,h),s&&(this._request.body=s);var E=new Sp(this._ua,this._request,{onRequestTimeout:function(){r._onRequestTimeout()},onTransportError:function(){r._onTransportError()},onReceiveResponse:function(R){r._receiveResponse(R)}});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=Hr.cloneArray(a.extraHeaders),r=a.body;if(this._direction!=="incoming")throw new sf.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,_=Hr.cloneArray(a.extraHeaders),d=a.body;if(this._direction!=="incoming")throw new sf.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,_,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=Hr.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){zl.debug("OPTIONS failed"),this._close(),zl.debug('emit "failed"'),this.emit("failed",{originator:a,response:s||null,cause:r})}},{key:"_succeeded",value:function(a,s){zl.debug("OPTIONS succeeded"),this._close(),zl.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}(mp),wa={},yp=ft,Oa=Rt(),Cp=ts(),Fr=new yp("Socket");wa.isSocket=function(c){if(Array.isArray(c))return!1;if(typeof c>"u")return Fr.warn("undefined JsSIP.Socket instance"),!1;try{if(!Oa.isString(c.url))throw Fr.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!Oa.isString(c.via_transport))throw Fr.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(Cp.parse(c.sip_uri,"SIP_URI")===-1)throw Fr.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 Fr.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 Ap(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function nf(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function Rp(c,t,n){return t&&nf(c.prototype,t),n&&nf(c,n),c}var bp=ft,Ip=wa,rf=nt,xt=new bp("Transport"),$t={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}},wp=function(){function c(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:$t.recovery_options;Ap(this,c),xt.debug("new()"),this.status=$t.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(o){xt.warn("cannot use TextDecoder: ".concat(o))}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(o){if(!Ip.isSocket(o.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(o.weight&&!Number(o.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:o.socket,weight:o.weight||0,status:$t.SOCKET_STATUS_READY})},this),this._getSocket()}return Rp(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=$t.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=$t.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(xt.debug("send()"),!this.isConnected())return xt.warn("unable to send message, transport is not connected"),!1;var o=n.toString();return xt.debug(`sending message:
51
51
 
52
52
  `.concat(o,`
53
53
  `)),this.socket.send(o)}},{key:"isConnected",value:function(){return this.status===$t.STATUS_CONNECTED}},{key:"isConnecting",value:function(){return this.status===$t.STATUS_CONNECTING}},{key:"_reconnect",value:function(){var n=this;this.recover_attempts+=1;var o=Math.floor(Math.random()*Math.pow(2,this.recover_attempts)+1);o<this.recovery_options.min_interval?o=this.recovery_options.min_interval:o>this.recovery_options.max_interval&&(o=this.recovery_options.max_interval),xt.debug("reconnection attempt: ".concat(this.recover_attempts,". next connection attempt in ").concat(o," seconds")),this.recovery_timer=setTimeout(function(){!n.close_requested&&!(n.isConnected()||n.isConnecting())&&(n._getSocket(),n.connect())},o*1e3)}},{key:"_getSocket",value:function(){var n=[];if(this.sockets.forEach(function(a){a.status!==$t.SOCKET_STATUS_ERROR&&(n.length===0?n.push(a):a.weight>n[0].weight?n=[a]:a.weight===n[0].weight&&n.push(a))}),n.length===0){this.sockets.forEach(function(a){a.status=$t.SOCKET_STATUS_READY}),this._getSocket();return}var o=Math.floor(Math.random()*n.length);this.socket=n[o].socket}},{key:"_onConnect",value:function(){this.recover_attempts=0,this.status=$t.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}},{key:"_onDisconnect",value:function(n,o,a){this.status=$t.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:n,code:o,reason:a}),!this.close_requested&&(this.sockets.forEach(function(s){this.socket===s.socket&&(s.status=$t.SOCKET_STATUS_ERROR)},this),this._reconnect(n))}},{key:"_onData",value:function(n){if(n===`\r
@@ -60,8 +60,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
60
60
  `));this.ondata({transport:this,message:n})}},{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}(),lf={};function of(c,t){var n;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(n=Op(c))||t&&c&&typeof c.length=="number"){n&&(c=n);var o=0,a=function(){};return{s:a,n:function(){return o>=c.length?{done:!0}:{done:!1,value:c[o++]}},e:function(h){throw h},f:a}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
61
61
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,_;return{s:function(){n=c[Symbol.iterator]()},n:function(){var h=n.next();return s=h.done,h},e:function(h){r=!0,_=h},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw _}}}}function Op(c,t){if(c){if(typeof c=="string")return af(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 af(c,t)}}function af(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=c[n];return o}var Dp=ft,Da=ts(),Na=fs,Xl=new Dp("Parser");lf.parseMessage=function(c,t){var n,o,a=c.indexOf(`\r
62
62
  `);if(a===-1){Xl.warn("parseMessage() | no CRLF found, not a SIP message");return}var s=c.substring(0,a),r=Da.parse(s,"Request_Response");if(r===-1){Xl.warn('parseMessage() | error parsing first line of SIP message: "'.concat(s,'"'));return}else r.status_code?(n=new Na.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new Na.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;for(var _=a+2;;){if(a=Np(c,_),a===-2){o=_+2;break}else if(a===-1){Xl.warn("parseMessage() | malformed message");return}if(r=xp(n,c,_,a),r!==!0){Xl.warn("parseMessage() |",r.error);return}_=a+2}if(n.hasHeader("content-length")){var d=n.getHeader("content-length");n.body=c.substr(o,d)}else n.body=c.substring(o);return n};function Np(c,t){var n=t,o=0,a=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;o===0;){if(a=c.indexOf(`\r
63
- `,n),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?n=a+2:o=a}return o}function xp(c,t,n,o){var a,s=t.indexOf(":",n),r=t.substring(n,s).trim(),_=t.substring(s+1,o).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",_),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",_),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",_),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=Da.parse(_,"Record_Route"),a===-1)a=void 0;else{var d=of(a),h;try{for(d.s();!(h=d.n()).done;){var g=h.value;c.addHeader("record-route",_.substring(g.possition,g.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=g.parsed}}catch(A){d.e(A)}finally{d.f()}}break;case"call-id":case"i":c.setHeader("call-id",_),a=c.parseHeader("call-id"),a&&(c.call_id=_);break;case"contact":case"m":if(a=Da.parse(_,"Contact"),a===-1)a=void 0;else{var T=of(a),S;try{for(T.s();!(S=T.n()).done;){var E=S.value;c.addHeader("contact",_.substring(E.possition,E.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=E.parsed}}catch(A){T.e(A)}finally{T.f()}}break;case"content-length":case"l":c.setHeader("content-length",_),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",_),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",_),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof Na.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",_),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",_),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",_),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",_),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",_),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",_),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",_),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,_),a=0}return a===void 0?{error:'error parsing header "'.concat(r,'"')}:!0}function Ql(c,t){var n;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(n=Up(c))||t&&c&&typeof c.length=="number"){n&&(c=n);var o=0,a=function(){};return{s:a,n:function(){return o>=c.length?{done:!0}:{done:!1,value:c[o++]}},e:function(h){throw h},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 s=!0,r=!1,_;return{s:function(){n=c[Symbol.iterator]()},n:function(){var h=n.next();return s=h.done,h},e:function(h){r=!0,_=h},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw _}}}}function Up(c,t){if(c){if(typeof c=="string")return uf(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 uf(c,t)}}function uf(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=c[n];return o}var kp=ft,cf=nt,ff=fs,xa=Rt(),Ua=new kp("sanityCheck"),Pp=[Gp],Mp=[Hp,Fp,Vp,jp],Lp=[qp,Bp],Fe,ns,df,$p=function(c,t,n){Fe=c,ns=t,df=n;var o=Ql(Pp),a;try{for(o.s();!(a=o.n()).done;){var s=a.value;if(s()===!1)return!1}}catch(S){o.e(S)}finally{o.f()}if(Fe instanceof ff.IncomingRequest){var r=Ql(Mp),_;try{for(r.s();!(_=r.n()).done;){var d=_.value;if(d()===!1)return!1}}catch(S){r.e(S)}finally{r.f()}}else if(Fe instanceof ff.IncomingResponse){var h=Ql(Lp),g;try{for(h.s();!(g=h.n()).done;){var T=g.value;if(T()===!1)return!1}}catch(S){h.e(S)}finally{h.f()}}return!0};function Hp(){if(Fe.s("to").uri.scheme!=="sip")return Vr(416),!1}function Fp(){if(!Fe.to_tag&&Fe.call_id.substr(0,5)===ns.configuration.jssip_id)return Vr(482),!1}function Vp(){var c=xa.str_utf8_length(Fe.body),t=Fe.getHeader("content-length");if(c<t)return Vr(400),!1}function jp(){var c=Fe.from_tag,t=Fe.call_id,n=Fe.cseq,o;if(!Fe.to_tag)if(Fe.method===cf.INVITE){if(ns._transactions.ist[Fe.via_branch])return!1;for(var a in ns._transactions.ist)if(Object.prototype.hasOwnProperty.call(ns._transactions.ist,a)&&(o=ns._transactions.ist[a],o.request.from_tag===c&&o.request.call_id===t&&o.request.cseq===n))return Vr(482),!1}else{if(ns._transactions.nist[Fe.via_branch])return!1;for(var s in ns._transactions.nist)if(Object.prototype.hasOwnProperty.call(ns._transactions.nist,s)&&(o=ns._transactions.nist[s],o.request.from_tag===c&&o.request.call_id===t&&o.request.cseq===n))return Vr(482),!1}}function qp(){if(Fe.getHeaders("via").length>1)return Ua.debug("more than one Via header field present in the response, dropping the response"),!1}function Bp(){var c=xa.str_utf8_length(Fe.body),t=Fe.getHeader("content-length");if(c<t)return Ua.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function Gp(){for(var c=["from","to","call_id","cseq","via"],t=0,n=c;t<n.length;t++){var o=n[t];if(!Fe.hasHeader(o))return Ua.debug("missing mandatory header field : ".concat(o,", dropping the response")),!1}}function Vr(c){var t=Fe.getHeaders("via"),n,o="SIP/2.0 ".concat(c," ").concat(cf.REASON_PHRASE[c],`\r
63
+ `,n),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?n=a+2:o=a}return o}function xp(c,t,n,o){var a,s=t.indexOf(":",n),r=t.substring(n,s).trim(),_=t.substring(s+1,o).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",_),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",_),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",_),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=Da.parse(_,"Record_Route"),a===-1)a=void 0;else{var d=of(a),h;try{for(d.s();!(h=d.n()).done;){var m=h.value;c.addHeader("record-route",_.substring(m.possition,m.offset)),c.headers["Record-Route"][c.getHeaders("record-route").length-1].parsed=m.parsed}}catch(A){d.e(A)}finally{d.f()}}break;case"call-id":case"i":c.setHeader("call-id",_),a=c.parseHeader("call-id"),a&&(c.call_id=_);break;case"contact":case"m":if(a=Da.parse(_,"Contact"),a===-1)a=void 0;else{var T=of(a),S;try{for(T.s();!(S=T.n()).done;){var E=S.value;c.addHeader("contact",_.substring(E.possition,E.offset)),c.headers.Contact[c.getHeaders("contact").length-1].parsed=E.parsed}}catch(A){T.e(A)}finally{T.f()}}break;case"content-length":case"l":c.setHeader("content-length",_),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",_),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",_),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof Na.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",_),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",_),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",_),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",_),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",_),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",_),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",_),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,_),a=0}return a===void 0?{error:'error parsing header "'.concat(r,'"')}:!0}function Ql(c,t){var n;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(n=Up(c))||t&&c&&typeof c.length=="number"){n&&(c=n);var o=0,a=function(){};return{s:a,n:function(){return o>=c.length?{done:!0}:{done:!1,value:c[o++]}},e:function(h){throw h},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 s=!0,r=!1,_;return{s:function(){n=c[Symbol.iterator]()},n:function(){var h=n.next();return s=h.done,h},e:function(h){r=!0,_=h},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw _}}}}function Up(c,t){if(c){if(typeof c=="string")return uf(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 uf(c,t)}}function uf(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=c[n];return o}var kp=ft,cf=nt,ff=fs,xa=Rt(),Ua=new kp("sanityCheck"),Pp=[Gp],Mp=[Hp,Fp,Vp,jp],Lp=[qp,Bp],Fe,ns,df,$p=function(c,t,n){Fe=c,ns=t,df=n;var o=Ql(Pp),a;try{for(o.s();!(a=o.n()).done;){var s=a.value;if(s()===!1)return!1}}catch(S){o.e(S)}finally{o.f()}if(Fe instanceof ff.IncomingRequest){var r=Ql(Mp),_;try{for(r.s();!(_=r.n()).done;){var d=_.value;if(d()===!1)return!1}}catch(S){r.e(S)}finally{r.f()}}else if(Fe instanceof ff.IncomingResponse){var h=Ql(Lp),m;try{for(h.s();!(m=h.n()).done;){var T=m.value;if(T()===!1)return!1}}catch(S){h.e(S)}finally{h.f()}}return!0};function Hp(){if(Fe.s("to").uri.scheme!=="sip")return Vr(416),!1}function Fp(){if(!Fe.to_tag&&Fe.call_id.substr(0,5)===ns.configuration.jssip_id)return Vr(482),!1}function Vp(){var c=xa.str_utf8_length(Fe.body),t=Fe.getHeader("content-length");if(c<t)return Vr(400),!1}function jp(){var c=Fe.from_tag,t=Fe.call_id,n=Fe.cseq,o;if(!Fe.to_tag)if(Fe.method===cf.INVITE){if(ns._transactions.ist[Fe.via_branch])return!1;for(var a in ns._transactions.ist)if(Object.prototype.hasOwnProperty.call(ns._transactions.ist,a)&&(o=ns._transactions.ist[a],o.request.from_tag===c&&o.request.call_id===t&&o.request.cseq===n))return Vr(482),!1}else{if(ns._transactions.nist[Fe.via_branch])return!1;for(var s in ns._transactions.nist)if(Object.prototype.hasOwnProperty.call(ns._transactions.nist,s)&&(o=ns._transactions.nist[s],o.request.from_tag===c&&o.request.call_id===t&&o.request.cseq===n))return Vr(482),!1}}function qp(){if(Fe.getHeaders("via").length>1)return Ua.debug("more than one Via header field present in the response, dropping the response"),!1}function Bp(){var c=xa.str_utf8_length(Fe.body),t=Fe.getHeader("content-length");if(c<t)return Ua.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function Gp(){for(var c=["from","to","call_id","cseq","via"],t=0,n=c;t<n.length;t++){var o=n[t];if(!Fe.hasHeader(o))return Ua.debug("missing mandatory header field : ".concat(o,", dropping the response")),!1}}function Vr(c){var t=Fe.getHeaders("via"),n,o="SIP/2.0 ".concat(c," ").concat(cf.REASON_PHRASE[c],`\r
65
65
  `),a=Ql(t),s;try{for(a.s();!(s=a.n()).done;){var r=s.value;o+="Via: ".concat(r,`\r
66
66
  `)}}catch(_){a.e(_)}finally{a.f()}n=Fe.getHeader("To"),Fe.to_tag||(n+=";tag=".concat(xa.newTag())),o+="To: ".concat(n,`\r
67
67
  `),o+="From: ".concat(Fe.getHeader("From"),`\r
@@ -69,38 +69,38 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
69
69
  `),o+="CSeq: ".concat(Fe.cseq," ").concat(Fe.method,`\r
70
70
  `),o+=`\r
71
71
  `,df.send(o)}var ka={};function hf(c,t){var n;if(typeof Symbol>"u"||c[Symbol.iterator]==null){if(Array.isArray(c)||(n=Wp(c))||t&&c&&typeof c.length=="number"){n&&(c=n);var o=0,a=function(){};return{s:a,n:function(){return o>=c.length?{done:!0}:{done:!1,value:c[o++]}},e:function(h){throw h},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 s=!0,r=!1,_;return{s:function(){n=c[Symbol.iterator]()},n:function(){var h=n.next();return s=h.done,h},e:function(h){r=!0,_=h},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw _}}}}function Wp(c,t){if(c){if(typeof c=="string")return _f(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 _f(c,t)}}function _f(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=c[n];return o}var kn=Rt(),en=nt,Pa=ts(),pf=Is(),Ma=wa,La=bs;ka.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:en.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:en.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:en.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(kn.createRandomToken(12),".invalid")};var Zl={mandatory:{sockets:function(t){var n=[];if(Ma.isSocket(t))n.push({socket:t});else if(Array.isArray(t)&&t.length){var o=hf(t),a;try{for(o.s();!(a=o.n()).done;){var s=a.value;Object.prototype.hasOwnProperty.call(s,"socket")&&Ma.isSocket(s.socket)?n.push(s):Ma.isSocket(s)&&n.push({socket:s})}}catch(r){o.e(r)}finally{o.f()}}else return;return n},uri:function(t){/^sip:/i.test(t)||(t="".concat(en.SIP,":").concat(t));var n=pf.parse(t);if(n)return n.user?n:void 0}},optional:{authorization_user:function(t){if(Pa.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(kn.isDecimal(t)){var n=Number(t);if(n>0)return n}},connection_recovery_min_interval:function(t){if(kn.isDecimal(t)){var n=Number(t);if(n>0)return n}},contact_uri:function(t){if(typeof t=="string"){var n=Pa.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)),Pa.parse(t,"uuid")!==-1)return t},no_answer_timeout:function(t){if(kn.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===en.INVITE||t===en.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(kn.isDecimal(t)){var n=Number(t);if(n>0)return n}},registrar_server:function(t){/^sip:/i.test(t)||(t="".concat(en.SIP,":").concat(t));var n=pf.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 o=hf(t),a;try{for(o.s();!(a=o.n()).done;){var s=a.value;typeof s=="string"&&n.push(s)}}catch(r){o.e(r)}finally{o.f()}}else return;return n}}};ka.load=function(c,t){for(var n in Zl.mandatory)if(t.hasOwnProperty(n)){var o=t[n],a=Zl.mandatory[n](o);if(a!==void 0)c[n]=a;else throw new La.ConfigurationError(n,o)}else throw new La.ConfigurationError(n);for(var s in Zl.optional)if(t.hasOwnProperty(s)){var r=t[s];if(kn.isEmpty(r))continue;var _=Zl.optional[s](r);if(_!==void 0)c[s]=_;else throw new La.ConfigurationError(s,r)}};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 Kp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function mf(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function gf(c,t,n){return t&&mf(c.prototype,t),n&&mf(c,n),c}function Yp(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&&$a(c,t)}function $a(c,t){return $a=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},$a(c,t)}function Jp(c){var t=Xp();return function(){var o=to(c),a;if(t){var s=to(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return zp(this,a)}}function zp(c,t){return t&&(eo(t)==="object"||typeof t=="function")?t:Tf(c)}function Tf(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Xp(){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 to(c){return to=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},to(c)}var Qp=ct.EventEmitter,Zp=ft,_t=nt,em=Vh,vf=z_,Sf=up,Ef=Ep,Ha=xr,tm=wp,so=Rt(),sm=bs,nm=Is(),rm=lf,Fa=fs,im=$p,Va=ka,qe=new Zp("UA"),pt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},lm=function(c){Yp(n,c);var t=Jp(n);gf(n,null,[{key:"C",get:function(){return pt}}]);function n(o){var a;if(Kp(this,n),qe.debug("new() [configuration:%o]",o),a=t.call(this),a._cache={credentials:{}},a._configuration=Object.assign({},Va.settings),a._dynConfiguration={},a._dialogs={},a._applicants={},a._sessions={},a._transport=null,a._contact=null,a._status=pt.STATUS_INIT,a._error=null,a._transactions={nist:{},nict:{},ist:{},ict:{}},a._data={},a._closeTimer=null,o===void 0)throw new TypeError("Not enough arguments");try{a._loadConfig(o)}catch(s){throw a._status=pt.STATUS_NOT_READY,a._error=pt.CONFIGURATION_ERROR,s}return a._registrator=new em(Tf(a)),a}return gf(n,[{key:"start",value:function(){qe.debug("start()"),this._status===pt.STATUS_INIT?this._transport.connect():this._status===pt.STATUS_USER_CLOSED?(qe.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=pt.STATUS_INIT,this._transport.connect()):this._status===pt.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,s){qe.debug("call()");var r=new vf(this);return r.connect(a,s),r}},{key:"sendMessage",value:function(a,s,r){qe.debug("sendMessage()");var _=new Sf(this);return _.send(a,s,r),_}},{key:"sendOptions",value:function(a,s,r){qe.debug("sendOptions()");var _=new Ef(this);return _.send(a,s,r),_}},{key:"terminateSessions",value:function(a){qe.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(qe.debug("stop()"),this._dynConfiguration={},this._status===pt.STATUS_USER_CLOSED){qe.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)){qe.debug("closing session ".concat(r));try{this._sessions[r].terminate()}catch{}}for(var _ in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,_))try{this._applicants[_].close()}catch{}this._status=pt.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 so.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,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 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,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){qe.debug("Request-URI does not point to us"),a.method!==_t.ACK&&a.reply_sl(404);return}if(a.ruri.scheme===_t.SIPS){a.reply_sl(416);return}if(!Ha.checkTransaction(this,a)){if(s===_t.INVITE?new Ha.InviteServerTransaction(this,this._transport,a):s!==_t.ACK&&s!==_t.CANCEL&&new Ha.NonInviteServerTransaction(this,this._transport,a),s===_t.OPTIONS){if(this.listeners("newOptions").length===0){a.reply(200);return}var r=new Ef(this);r.init_incoming(a)}else if(s===_t.MESSAGE){if(this.listeners("newMessage").length===0){a.reply(405);return}var _=new Sf(this);_.init_incoming(a)}else if(s===_t.INVITE&&!a.to_tag&&this.listeners("newRTCSession").length===0){a.reply(405);return}var d,h;if(a.to_tag)d=this._findDialog(a.call_id,a.from_tag,a.to_tag),d?d.receiveRequest(a):s===_t.NOTIFY?(h=this._findSession(a),h?h.receiveRequest(a):(qe.debug("received NOTIFY request for a non existent subscription"),a.reply(481,"Subscription does not exist"))):s!==_t.ACK&&a.reply(481);else switch(s){case _t.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?(h=d.owner,h.isEnded()?a.reply(603):h.receiveRequest(a)):a.reply(481)}else h=new vf(this),h.init_incoming(a);else qe.warn("INVITE received but WebRTC is not supported"),a.reply(488);break;case _t.BYE:a.reply(481);break;case _t.CANCEL:h=this._findSession(a),h?h.receiveRequest(a):qe.debug("received CANCEL request for a non existent session");break;case _t.ACK:break;case _t.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,_=a.to_tag,d=s+r,h=this._sessions[d],g=s+_,T=this._sessions[g];return h||T||null}},{key:"_findDialog",value:function(a,s,r){var _=a+s+r,d=this._dialogs[_];return d||(_=a+r+s,d=this._dialogs[_],d||null)}},{key:"_loadConfig",value:function(a){try{Va.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=so.newUUID()),this._configuration.jssip_id=so.createRandomToken(5);var s=this._configuration.uri.clone();s.user=null,this._configuration.hostport_params=s.toString().replace(/^sip:/i,"");try{this._transport=new tm(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=om.bind(this),this._transport.onconnect=am.bind(this),this._transport.ondisconnect=um.bind(this),this._transport.ondata=cm.bind(this)}catch(g){throw qe.warn(g),new sm.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 nm("sip",so.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,A="<";return S?A+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":A+=this.pub_gruu||this.uri.toString(),E&&(S?!this.temp_gruu:!this.pub_gruu)&&(A+=";ob"),A+=">",A}};var _=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var d in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,d)&&(_.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 h in this._configuration)if(Object.prototype.hasOwnProperty.call(Va.settings,h))switch(h){case"uri":case"registrar_server":qe.debug("- ".concat(h,": ").concat(this._configuration[h]));break;case"password":case"ha1":case"authorization_jwt":qe.debug("- ".concat(h,": NOT SHOWN"));break;default:qe.debug("- ".concat(h,": ").concat(JSON.stringify(this._configuration[h])))}}},{key:"C",get:function(){return pt}},{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}(Qp);function om(c){this.emit("connecting",c)}function am(c){this._status!==pt.STATUS_USER_CLOSED&&(this._status=pt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function um(c){for(var t=["nict","ict","nist","ist"],n=0,o=t;n<o.length;n++){var a=o[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!==pt.STATUS_USER_CLOSED&&(this._status=pt.STATUS_NOT_READY,this._error=pt.NETWORK_ERROR)}function cm(c){var t=c.transport,n=c.message;if(n=rm.parseMessage(n,this),!!n&&!(this._status===pt.STATUS_USER_CLOSED&&n instanceof Fa.IncomingRequest)&&im(n,this,t)){if(n instanceof Fa.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Fa.IncomingResponse){var o;switch(n.method){case _t.INVITE:o=this._transactions.ict[n.via_branch],o&&o.receiveResponse(n);break;case _t.ACK:break;default:o=this._transactions.nict[n.via_branch],o&&o.receiveResponse(n);break}}}}function fm(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function yf(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function dm(c,t,n){return t&&yf(c.prototype,t),n&&yf(c,n),c}var hm=ft,_m=ts(),wt=new hm("WebSocketInterface"),pm=function(){function c(t){fm(this,c),wt.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var n=_m.parse(t,"absoluteURI");if(n===-1)throw wt.warn("invalid WebSocket URI: ".concat(t)),new TypeError("Invalid argument: ".concat(t));if(n.scheme!=="wss"&&n.scheme!=="ws")throw wt.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 dm(c,[{key:"connect",value:function(){if(wt.debug("connect()"),this.isConnected()){wt.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){wt.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),wt.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(){wt.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 wt.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(wt.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(){wt.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(n){var o=n.wasClean,a=n.code,s=n.reason;wt.debug("WebSocket ".concat(this._url," closed")),o===!1&&wt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!o,a,s)}},{key:"_onMessage",value:function(n){var o=n.data;wt.debug("received WebSocket message"),this.ondata(o)}},{key:"_onError",value:function(n){wt.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}(),ja=Tl,mm=nt,gm=bs,Tm=Rt(),vm=lm,Sm=Is(),Em=Zo(),ym=ts(),Cm=pm,Am=Nn("JsSIP");Am("version %s",ja.version);var Cf={C:mm,Exceptions:gm,Utils:Tm,UA:vm,URI:Sm,NameAddrHeader:Em,WebSocketInterface:Cm,Grammar:ym,debug:Nn,get name(){return ja.title},get version(){return ja.version}};const Pn=Nn,Mn="JsSIP";var ot=class{constructor(t){t?(this._debug=Pn.default(`${Mn}:${t}`),this._warn=Pn.default(`${Mn}:WARN:${t}`),this._error=Pn.default(`${Mn}:ERROR:${t}`)):(this._debug=Pn.default(Mn),this._warn=Pn.default(`${Mn}:WARN`),this._error=Pn.default(`${Mn}: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 no=Me(ot),Af=Tl;var De={USER_AGENT:`${Af.title} ${Af.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 $=Me(De);var et={},qa,Rf;function Ba(){if(Rf)return qa;Rf=1;const c=ps(),t=Yt();return qa=class $d{static parse(o){if(o=t.parse(o,"Name_Addr_Header"),o!==-1)return o}constructor(o,a,s){if(!o||!(o instanceof c))throw new TypeError('missing or invalid "uri" parameter');this._uri=o,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(o){this._display_name=o===0?"0":o}setParam(o,a){o&&(this._parameters[o.toLowerCase()]=typeof a>"u"||a===null?null:a.toString())}getParam(o){if(o)return this._parameters[o.toLowerCase()]}hasParam(o){if(o)return this._parameters.hasOwnProperty(o.toLowerCase())&&!0||!1}deleteParam(o){if(o=o.toLowerCase(),this._parameters.hasOwnProperty(o)){const a=this._parameters[o];return delete this._parameters[o],a}}clearParams(){this._parameters={}}clone(){return new $d(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(o){return o.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let o=this._display_name?`"${this._quote(this._display_name)}" `:"";o+=`<${this._uri.toString()}>`;for(const a in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,a)&&(o+=`;${a}`,this._parameters[a]!==null&&(o+=`=${this._parameters[a]}`));return o}},qa}var Ga,bf;function Yt(){return bf||(bf=1,Ga=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,o){var a={CRLF:h,DIGIT:g,ALPHA:T,HEXDIG:S,WSP:E,OCTET:A,DQUOTE:R,SP:C,HTAB:H,alphanum:k,reserved:re,unreserved:x,mark:F,escaped:_e,LWS:pe,SWS:P,HCOLON:N,TEXT_UTF8_TRIM:q,TEXT_UTF8char:j,UTF8_NONASCII:K,UTF8_CONT:V,LHEX:z,token:D,token_nodot:U,separators:X,word:je,STAR:Q,SLASH:W,EQUAL:B,LPAREN:ie,RPAREN:ve,RAQUOT:Ie,LAQUOT:Pe,COMMA:Re,SEMI:oe,COLON:ye,LDQUOT:lt,RDQUOT:at,comment:Ee,ctext:Ce,quoted_string:be,quoted_string_clean:Oe,qdtext:ge,quoted_pair:he,SIP_URI_noparams:me,SIP_URI:we,uri_scheme:Ne,uri_scheme_sips:st,uri_scheme_sip:He,userinfo:Vt,user:At,user_unreserved:qn,password:Bn,hostport:un,host:ls,hostname:Cs,domainlabel:cn,toplabel:Gn,IPv6reference:Wn,IPv6address:fn,h16:Te,ls32:ae,IPv4address:ut,dec_octet:Zt,port:$s,uri_parameters:ai,uri_parameter:Kn,transport_param:Yn,user_param:ui,method_param:ci,ttl_param:fi,maddr_param:di,lr_param:hi,other_param:_i,pname:pi,pvalue:mi,paramchar:Hs,param_unreserved:Fs,headers:gi,header:dn,hname:hn,hvalue:Ti,hnv_unreserved:Vs,Request_Response:_n,Request_Line:Do,Request_URI:vi,absoluteURI:Jn,hier_part:zn,net_path:Si,abs_path:pn,opaque_part:mn,uric:js,uric_no_slash:qs,path_segments:Ei,segment:gn,param:Bs,pchar:As,scheme:Gs,authority:yi,srvr:Ci,reg_name:Ai,query:Ri,SIP_Version:Xn,INVITEm:Qn,ACKm:bi,OPTIONSm:Ii,BYEm:wi,CANCELm:Oi,REGISTERm:Di,SUBSCRIBEm:Ni,NOTIFYm:xi,REFERm:Ui,Method:Tn,Status_Line:vn,Status_Code:ki,extension_code:Pi,Reason_Phrase:Mi,Allow_Events:No,Call_ID:Nu,Contact:xu,contact_param:Zn,name_addr:jt,display_name:qt,contact_params:Ws,c_p_q:er,c_p_expires:Li,delta_seconds:os,qvalue:as,generic_param:ze,gen_value:Xe,Content_Disposition:xo,disp_type:Uo,disp_param:tr,handling_param:sr,Content_Encoding:ko,Content_Length:Uu,Content_Type:ku,media_type:Po,m_type:$i,discrete_type:Hi,composite_type:Fi,extension_token:Sn,x_token:En,m_subtype:Vi,m_parameter:nr,m_value:rr,CSeq:Mo,CSeq_value:Lo,Expires:$o,Event:Pu,event_type:yn,From:Cn,from_param:ji,tag_param:An,Max_Forwards:qi,Min_Expires:Mu,Name_Addr_Header:Lu,Proxy_Authenticate:$u,challenge:Bi,other_challenge:ir,auth_param:Ks,digest_cln:us,realm:Rn,realm_value:Gi,domain:Wi,URI:bn,nonce:In,nonce_value:Ki,opaque:Yi,stale:Ji,algorithm:zi,qop_options:Xi,qop_value:wn,Proxy_Require:lr,Record_Route:Hu,rec_route:or,Reason:ar,reason_param:Qi,reason_cause:ur,Require:Ho,Route:Fu,route_param:cr,Subscription_State:fr,substate_value:Fo,subexp_params:dr,event_reason_value:hr,Subject:Vo,Supported:Vu,To:ju,to_param:Zi,Via:el,via_param:_r,via_params:Ys,via_ttl:pr,via_maddr:tl,via_received:sl,via_branch:nl,response_port:rl,rport:il,sent_protocol:ll,protocol_name:ol,transport:al,sent_by:ul,via_host:cl,via_port:fl,ttl:mr,WWW_Authenticate:dl,Session_Expires:qu,s_e_expires:jo,s_e_params:gr,s_e_refresher:Tr,extension_header:qo,header_value:Bo,message_body:Go,uuid_URI:Bu,uuid:Wo,hex4:Bt,hex8:Gt,hex12:hl,Refer_To:Ko,Replaces:Gu,call_id:Yo,replaces_param:vr,to_tag:Sr,from_tag:_l,early_flag:pl};if(o!==void 0){if(a[o]===void 0)throw new Error("Invalid rule name: "+c(o)+".")}else o="CRLF";var s=0,r=0,_=[];function d(i){s<r||(s>r&&(r=s,_=[]),_.push(i))}function h(){var i;return n.substr(s,2)===`\r
72
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,r=!1,_;return{s:function(){n=c[Symbol.iterator]()},n:function(){var h=n.next();return s=h.done,h},e:function(h){r=!0,_=h},f:function(){try{!s&&n.return!=null&&n.return()}finally{if(r)throw _}}}}function Wp(c,t){if(c){if(typeof c=="string")return _f(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 _f(c,t)}}function _f(c,t){(t==null||t>c.length)&&(t=c.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=c[n];return o}var kn=Rt(),en=nt,Pa=ts(),pf=Is(),Ma=wa,La=bs;ka.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:en.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:en.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:en.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(kn.createRandomToken(12),".invalid")};var Zl={mandatory:{sockets:function(t){var n=[];if(Ma.isSocket(t))n.push({socket:t});else if(Array.isArray(t)&&t.length){var o=hf(t),a;try{for(o.s();!(a=o.n()).done;){var s=a.value;Object.prototype.hasOwnProperty.call(s,"socket")&&Ma.isSocket(s.socket)?n.push(s):Ma.isSocket(s)&&n.push({socket:s})}}catch(r){o.e(r)}finally{o.f()}}else return;return n},uri:function(t){/^sip:/i.test(t)||(t="".concat(en.SIP,":").concat(t));var n=pf.parse(t);if(n)return n.user?n:void 0}},optional:{authorization_user:function(t){if(Pa.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(kn.isDecimal(t)){var n=Number(t);if(n>0)return n}},connection_recovery_min_interval:function(t){if(kn.isDecimal(t)){var n=Number(t);if(n>0)return n}},contact_uri:function(t){if(typeof t=="string"){var n=Pa.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)),Pa.parse(t,"uuid")!==-1)return t},no_answer_timeout:function(t){if(kn.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===en.INVITE||t===en.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(kn.isDecimal(t)){var n=Number(t);if(n>0)return n}},registrar_server:function(t){/^sip:/i.test(t)||(t="".concat(en.SIP,":").concat(t));var n=pf.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 o=hf(t),a;try{for(o.s();!(a=o.n()).done;){var s=a.value;typeof s=="string"&&n.push(s)}}catch(r){o.e(r)}finally{o.f()}}else return;return n}}};ka.load=function(c,t){for(var n in Zl.mandatory)if(t.hasOwnProperty(n)){var o=t[n],a=Zl.mandatory[n](o);if(a!==void 0)c[n]=a;else throw new La.ConfigurationError(n,o)}else throw new La.ConfigurationError(n);for(var s in Zl.optional)if(t.hasOwnProperty(s)){var r=t[s];if(kn.isEmpty(r))continue;var _=Zl.optional[s](r);if(_!==void 0)c[s]=_;else throw new La.ConfigurationError(s,r)}};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 Kp(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function gf(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function mf(c,t,n){return t&&gf(c.prototype,t),n&&gf(c,n),c}function Yp(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&&$a(c,t)}function $a(c,t){return $a=Object.setPrototypeOf||function(o,a){return o.__proto__=a,o},$a(c,t)}function Jp(c){var t=Xp();return function(){var o=to(c),a;if(t){var s=to(this).constructor;a=Reflect.construct(o,arguments,s)}else a=o.apply(this,arguments);return zp(this,a)}}function zp(c,t){return t&&(eo(t)==="object"||typeof t=="function")?t:Tf(c)}function Tf(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c}function Xp(){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 to(c){return to=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},to(c)}var Qp=ct.EventEmitter,Zp=ft,_t=nt,eg=Vh,vf=z_,Sf=up,Ef=Ep,Ha=xr,tg=wp,so=Rt(),sg=bs,ng=Is(),rg=lf,Fa=fs,ig=$p,Va=ka,qe=new Zp("UA"),pt={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},lg=function(c){Yp(n,c);var t=Jp(n);mf(n,null,[{key:"C",get:function(){return pt}}]);function n(o){var a;if(Kp(this,n),qe.debug("new() [configuration:%o]",o),a=t.call(this),a._cache={credentials:{}},a._configuration=Object.assign({},Va.settings),a._dynConfiguration={},a._dialogs={},a._applicants={},a._sessions={},a._transport=null,a._contact=null,a._status=pt.STATUS_INIT,a._error=null,a._transactions={nist:{},nict:{},ist:{},ict:{}},a._data={},a._closeTimer=null,o===void 0)throw new TypeError("Not enough arguments");try{a._loadConfig(o)}catch(s){throw a._status=pt.STATUS_NOT_READY,a._error=pt.CONFIGURATION_ERROR,s}return a._registrator=new eg(Tf(a)),a}return mf(n,[{key:"start",value:function(){qe.debug("start()"),this._status===pt.STATUS_INIT?this._transport.connect():this._status===pt.STATUS_USER_CLOSED?(qe.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=pt.STATUS_INIT,this._transport.connect()):this._status===pt.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,s){qe.debug("call()");var r=new vf(this);return r.connect(a,s),r}},{key:"sendMessage",value:function(a,s,r){qe.debug("sendMessage()");var _=new Sf(this);return _.send(a,s,r),_}},{key:"sendOptions",value:function(a,s,r){qe.debug("sendOptions()");var _=new Ef(this);return _.send(a,s,r),_}},{key:"terminateSessions",value:function(a){qe.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(qe.debug("stop()"),this._dynConfiguration={},this._status===pt.STATUS_USER_CLOSED){qe.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)){qe.debug("closing session ".concat(r));try{this._sessions[r].terminate()}catch{}}for(var _ in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,_))try{this._applicants[_].close()}catch{}this._status=pt.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 so.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,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 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,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){qe.debug("Request-URI does not point to us"),a.method!==_t.ACK&&a.reply_sl(404);return}if(a.ruri.scheme===_t.SIPS){a.reply_sl(416);return}if(!Ha.checkTransaction(this,a)){if(s===_t.INVITE?new Ha.InviteServerTransaction(this,this._transport,a):s!==_t.ACK&&s!==_t.CANCEL&&new Ha.NonInviteServerTransaction(this,this._transport,a),s===_t.OPTIONS){if(this.listeners("newOptions").length===0){a.reply(200);return}var r=new Ef(this);r.init_incoming(a)}else if(s===_t.MESSAGE){if(this.listeners("newMessage").length===0){a.reply(405);return}var _=new Sf(this);_.init_incoming(a)}else if(s===_t.INVITE&&!a.to_tag&&this.listeners("newRTCSession").length===0){a.reply(405);return}var d,h;if(a.to_tag)d=this._findDialog(a.call_id,a.from_tag,a.to_tag),d?d.receiveRequest(a):s===_t.NOTIFY?(h=this._findSession(a),h?h.receiveRequest(a):(qe.debug("received NOTIFY request for a non existent subscription"),a.reply(481,"Subscription does not exist"))):s!==_t.ACK&&a.reply(481);else switch(s){case _t.INVITE:if(window.RTCPeerConnection)if(a.hasHeader("replaces")){var m=a.replaces;d=this._findDialog(m.call_id,m.from_tag,m.to_tag),d?(h=d.owner,h.isEnded()?a.reply(603):h.receiveRequest(a)):a.reply(481)}else h=new vf(this),h.init_incoming(a);else qe.warn("INVITE received but WebRTC is not supported"),a.reply(488);break;case _t.BYE:a.reply(481);break;case _t.CANCEL:h=this._findSession(a),h?h.receiveRequest(a):qe.debug("received CANCEL request for a non existent session");break;case _t.ACK:break;case _t.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,_=a.to_tag,d=s+r,h=this._sessions[d],m=s+_,T=this._sessions[m];return h||T||null}},{key:"_findDialog",value:function(a,s,r){var _=a+s+r,d=this._dialogs[_];return d||(_=a+r+s,d=this._dialogs[_],d||null)}},{key:"_loadConfig",value:function(a){try{Va.load(this._configuration,a)}catch(m){throw m}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=so.newUUID()),this._configuration.jssip_id=so.createRandomToken(5);var s=this._configuration.uri.clone();s.user=null,this._configuration.hostport_params=s.toString().replace(/^sip:/i,"");try{this._transport=new tg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=og.bind(this),this._transport.onconnect=ag.bind(this),this._transport.ondisconnect=ug.bind(this),this._transport.ondata=cg.bind(this)}catch(m){throw qe.warn(m),new sg.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 ng("sip",so.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,A="<";return S?A+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":A+=this.pub_gruu||this.uri.toString(),E&&(S?!this.temp_gruu:!this.pub_gruu)&&(A+=";ob"),A+=">",A}};var _=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var d in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,d)&&(_.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 h in this._configuration)if(Object.prototype.hasOwnProperty.call(Va.settings,h))switch(h){case"uri":case"registrar_server":qe.debug("- ".concat(h,": ").concat(this._configuration[h]));break;case"password":case"ha1":case"authorization_jwt":qe.debug("- ".concat(h,": NOT SHOWN"));break;default:qe.debug("- ".concat(h,": ").concat(JSON.stringify(this._configuration[h])))}}},{key:"C",get:function(){return pt}},{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}(Qp);function og(c){this.emit("connecting",c)}function ag(c){this._status!==pt.STATUS_USER_CLOSED&&(this._status=pt.STATUS_READY,this._error=null,this.emit("connected",c),this._dynConfiguration.register&&this._registrator.register())}function ug(c){for(var t=["nict","ict","nist","ist"],n=0,o=t;n<o.length;n++){var a=o[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!==pt.STATUS_USER_CLOSED&&(this._status=pt.STATUS_NOT_READY,this._error=pt.NETWORK_ERROR)}function cg(c){var t=c.transport,n=c.message;if(n=rg.parseMessage(n,this),!!n&&!(this._status===pt.STATUS_USER_CLOSED&&n instanceof Fa.IncomingRequest)&&ig(n,this,t)){if(n instanceof Fa.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Fa.IncomingResponse){var o;switch(n.method){case _t.INVITE:o=this._transactions.ict[n.via_branch],o&&o.receiveResponse(n);break;case _t.ACK:break;default:o=this._transactions.nict[n.via_branch],o&&o.receiveResponse(n);break}}}}function fg(c,t){if(!(c instanceof t))throw new TypeError("Cannot call a class as a function")}function yf(c,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(c,o.key,o)}}function dg(c,t,n){return t&&yf(c.prototype,t),n&&yf(c,n),c}var hg=ft,_g=ts(),wt=new hg("WebSocketInterface"),pg=function(){function c(t){fg(this,c),wt.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var n=_g.parse(t,"absoluteURI");if(n===-1)throw wt.warn("invalid WebSocket URI: ".concat(t)),new TypeError("Invalid argument: ".concat(t));if(n.scheme!=="wss"&&n.scheme!=="ws")throw wt.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 dg(c,[{key:"connect",value:function(){if(wt.debug("connect()"),this.isConnected()){wt.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){wt.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),wt.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(){wt.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 wt.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(wt.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(){wt.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(n){var o=n.wasClean,a=n.code,s=n.reason;wt.debug("WebSocket ".concat(this._url," closed")),o===!1&&wt.debug("WebSocket abrupt disconnection"),this.ondisconnect(!o,a,s)}},{key:"_onMessage",value:function(n){var o=n.data;wt.debug("received WebSocket message"),this.ondata(o)}},{key:"_onError",value:function(n){wt.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}(),ja=Tl,gg=nt,mg=bs,Tg=Rt(),vg=lg,Sg=Is(),Eg=Zo(),yg=ts(),Cg=pg,Ag=Nn("JsSIP");Ag("version %s",ja.version);var Cf={C:gg,Exceptions:mg,Utils:Tg,UA:vg,URI:Sg,NameAddrHeader:Eg,WebSocketInterface:Cg,Grammar:yg,debug:Nn,get name(){return ja.title},get version(){return ja.version}};const Pn=Nn,Mn="JsSIP";var ot=class{constructor(t){t?(this._debug=Pn.default(`${Mn}:${t}`),this._warn=Pn.default(`${Mn}:WARN:${t}`),this._error=Pn.default(`${Mn}:ERROR:${t}`)):(this._debug=Pn.default(Mn),this._warn=Pn.default(`${Mn}:WARN`),this._error=Pn.default(`${Mn}: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 no=Me(ot),Af=Tl;var De={USER_AGENT:`${Af.title} ${Af.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 $=Me(De);var et={},qa,Rf;function Ba(){if(Rf)return qa;Rf=1;const c=ps(),t=Yt();return qa=class $d{static parse(o){if(o=t.parse(o,"Name_Addr_Header"),o!==-1)return o}constructor(o,a,s){if(!o||!(o instanceof c))throw new TypeError('missing or invalid "uri" parameter');this._uri=o,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(o){this._display_name=o===0?"0":o}setParam(o,a){o&&(this._parameters[o.toLowerCase()]=typeof a>"u"||a===null?null:a.toString())}getParam(o){if(o)return this._parameters[o.toLowerCase()]}hasParam(o){if(o)return this._parameters.hasOwnProperty(o.toLowerCase())&&!0||!1}deleteParam(o){if(o=o.toLowerCase(),this._parameters.hasOwnProperty(o)){const a=this._parameters[o];return delete this._parameters[o],a}}clearParams(){this._parameters={}}clone(){return new $d(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(o){return o.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let o=this._display_name?`"${this._quote(this._display_name)}" `:"";o+=`<${this._uri.toString()}>`;for(const a in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,a)&&(o+=`;${a}`,this._parameters[a]!==null&&(o+=`=${this._parameters[a]}`));return o}},qa}var Ga,bf;function Yt(){return bf||(bf=1,Ga=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,o){var a={CRLF:h,DIGIT:m,ALPHA:T,HEXDIG:S,WSP:E,OCTET:A,DQUOTE:R,SP:C,HTAB:H,alphanum:k,reserved:re,unreserved:x,mark:F,escaped:_e,LWS:pe,SWS:P,HCOLON:N,TEXT_UTF8_TRIM:q,TEXT_UTF8char:j,UTF8_NONASCII:K,UTF8_CONT:V,LHEX:z,token:D,token_nodot:U,separators:X,word:je,STAR:Q,SLASH:W,EQUAL:B,LPAREN:ie,RPAREN:ve,RAQUOT:Ie,LAQUOT:Pe,COMMA:Re,SEMI:oe,COLON:ye,LDQUOT:lt,RDQUOT:at,comment:Ee,ctext:Ce,quoted_string:be,quoted_string_clean:Oe,qdtext:me,quoted_pair:he,SIP_URI_noparams:ge,SIP_URI:we,uri_scheme:Ne,uri_scheme_sips:st,uri_scheme_sip:He,userinfo:Vt,user:At,user_unreserved:qn,password:Bn,hostport:un,host:ls,hostname:Cs,domainlabel:cn,toplabel:Gn,IPv6reference:Wn,IPv6address:fn,h16:Te,ls32:ae,IPv4address:ut,dec_octet:Zt,port:$s,uri_parameters:ai,uri_parameter:Kn,transport_param:Yn,user_param:ui,method_param:ci,ttl_param:fi,maddr_param:di,lr_param:hi,other_param:_i,pname:pi,pvalue:gi,paramchar:Hs,param_unreserved:Fs,headers:mi,header:dn,hname:hn,hvalue:Ti,hnv_unreserved:Vs,Request_Response:_n,Request_Line:Do,Request_URI:vi,absoluteURI:Jn,hier_part:zn,net_path:Si,abs_path:pn,opaque_part:gn,uric:js,uric_no_slash:qs,path_segments:Ei,segment:mn,param:Bs,pchar:As,scheme:Gs,authority:yi,srvr:Ci,reg_name:Ai,query:Ri,SIP_Version:Xn,INVITEm:Qn,ACKm:bi,OPTIONSm:Ii,BYEm:wi,CANCELm:Oi,REGISTERm:Di,SUBSCRIBEm:Ni,NOTIFYm:xi,REFERm:Ui,Method:Tn,Status_Line:vn,Status_Code:ki,extension_code:Pi,Reason_Phrase:Mi,Allow_Events:No,Call_ID:Nu,Contact:xu,contact_param:Zn,name_addr:jt,display_name:qt,contact_params:Ws,c_p_q:er,c_p_expires:Li,delta_seconds:os,qvalue:as,generic_param:ze,gen_value:Xe,Content_Disposition:xo,disp_type:Uo,disp_param:tr,handling_param:sr,Content_Encoding:ko,Content_Length:Uu,Content_Type:ku,media_type:Po,m_type:$i,discrete_type:Hi,composite_type:Fi,extension_token:Sn,x_token:En,m_subtype:Vi,m_parameter:nr,m_value:rr,CSeq:Mo,CSeq_value:Lo,Expires:$o,Event:Pu,event_type:yn,From:Cn,from_param:ji,tag_param:An,Max_Forwards:qi,Min_Expires:Mu,Name_Addr_Header:Lu,Proxy_Authenticate:$u,challenge:Bi,other_challenge:ir,auth_param:Ks,digest_cln:us,realm:Rn,realm_value:Gi,domain:Wi,URI:bn,nonce:In,nonce_value:Ki,opaque:Yi,stale:Ji,algorithm:zi,qop_options:Xi,qop_value:wn,Proxy_Require:lr,Record_Route:Hu,rec_route:or,Reason:ar,reason_param:Qi,reason_cause:ur,Require:Ho,Route:Fu,route_param:cr,Subscription_State:fr,substate_value:Fo,subexp_params:dr,event_reason_value:hr,Subject:Vo,Supported:Vu,To:ju,to_param:Zi,Via:el,via_param:_r,via_params:Ys,via_ttl:pr,via_maddr:tl,via_received:sl,via_branch:nl,response_port:rl,rport:il,sent_protocol:ll,protocol_name:ol,transport:al,sent_by:ul,via_host:cl,via_port:fl,ttl:gr,WWW_Authenticate:dl,Session_Expires:qu,s_e_expires:jo,s_e_params:mr,s_e_refresher:Tr,extension_header:qo,header_value:Bo,message_body:Go,uuid_URI:Bu,uuid:Wo,hex4:Bt,hex8:Gt,hex12:hl,Refer_To:Ko,Replaces:Gu,call_id:Yo,replaces_param:vr,to_tag:Sr,from_tag:_l,early_flag:pl};if(o!==void 0){if(a[o]===void 0)throw new Error("Invalid rule name: "+c(o)+".")}else o="CRLF";var s=0,r=0,_=[];function d(i){s<r||(s>r&&(r=s,_=[]),_.push(i))}function h(){var i;return n.substr(s,2)===`\r
73
73
  `?(i=`\r
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=C(),i===null&&(i=H()),i}function A(){var i;return/^[\0-\xFF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\0-\\xFF]")),i}function R(){var i;return/^["]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d('["]')),i}function C(){var i;return n.charCodeAt(s)===32?(i=" ",s++):(i=null,d('" "')),i}function H(){var i;return n.charCodeAt(s)===9?(i=" ",s++):(i=null,d('"\\t"')),i}function k(){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 re(){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=k(),i===null&&(i=F()),i}function F(){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 _e(){var i,e,l,u,f;return u=s,f=s,n.charCodeAt(s)===37?(i="%",s++):(i=null,d('"%"')),i!==null?(e=S(),e!==null?(l=S(),l!==null?i=[i,e,l]:(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,l,u,f,p;for(u=s,f=s,p=s,i=[],e=E();e!==null;)i.push(e),e=E();if(i!==null?(e=h(),e!==null?i=[i,e]:(i=null,s=p)):(i=null,s=p),i=i!==null?i:"",i!==null){if(l=E(),l!==null)for(e=[];l!==null;)e.push(l),l=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,l,u,f;for(u=s,f=s,i=[],e=C(),e===null&&(e=H());e!==null;)i.push(e),e=C(),e===null&&(e=H());return i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,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,l=[],u=pe();u!==null;)l.push(u),u=pe();for(l!==null?(u=j(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;){for(e.push(l),m=s,l=[],u=pe();u!==null;)l.push(u),u=pe();l!==null?(u=j(),u!==null?l=[l,u]:(l=null,s=m)):(l=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=K()),i}function K(){var i;return/^[\x80-\uFFFF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\x80-\\uFFFF]")),i}function V(){var i;return/^[\x80-\xBF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\x80-\\xBF]")),i}function z(){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 D(){var i,e,l;if(l=s,e=k(),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=k(),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)}(l)),i===null&&(s=l),i}function U(){var i,e,l;if(l=s,e=k(),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=k(),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)}(l)),i===null&&(s=l),i}function X(){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=R(),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=C(),i===null&&(i=H())))))))))))))))))),i}function je(){var i,e,l;if(l=s,e=k(),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=R(),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=k(),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=R(),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)}(l)),i===null&&(s=l),i}function Q(){var i,e,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===42?(e="*",s++):(e=null,d('"*"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===47?(e="/",s++):(e=null,d('"/"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"/"}()),i===null&&(s=u),i}function B(){var i,e,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===40?(e="(",s++):(e=null,d('"("')),e!==null?(l=P(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"("}()),i===null&&(s=u),i}function ve(){var i,e,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===41?(e=")",s++):(e=null,d('")"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u;return l=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=l),i}function Pe(){var i,e,l,u;return l=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=l),i}function Re(){var i,e,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===44?(e=",",s++):(e=null,d('","')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===59?(e=";",s++):(e=null,d('";"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return":"}()),i===null&&(s=u),i}function lt(){var i,e,l,u;return l=s,u=s,i=P(),i!==null?(e=R(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return'"'}()),i===null&&(s=l),i}function at(){var i,e,l,u;return l=s,u=s,i=R(),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=l),i}function Ee(){var i,e,l,u;if(u=s,i=ie(),i!==null){for(e=[],l=Ce(),l===null&&(l=he(),l===null&&(l=Ee()));l!==null;)e.push(l),l=Ce(),l===null&&(l=he(),l===null&&(l=Ee()));e!==null?(l=ve(),l!==null?i=[i,e,l]:(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=K(),i===null&&(i=pe())))),i}function be(){var i,e,l,u,f,p;if(f=s,p=s,i=P(),i!==null)if(e=R(),e!==null){for(l=[],u=ge(),u===null&&(u=he());u!==null;)l.push(u),u=ge(),u===null&&(u=he());l!==null?(u=R(),u!==null?i=[i,e,l,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,l,u,f,p;if(f=s,p=s,i=P(),i!==null)if(e=R(),e!==null){for(l=[],u=ge(),u===null&&(u=he());u!==null;)l.push(u),u=ge(),u===null&&(u=he());l!==null?(u=R(),u!==null?i=[i,e,l,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=K())))),i}function he(){var i,e,l;return l=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=l)):(i=null,s=l),i}function me(){var i,e,l,u,f,p;return f=s,p=s,i=Ne(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Vt(),l=l!==null?l:"",l!==null?(u=un(),u!==null?i=[i,e,l,u]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i!==null&&(i=function(m){try{I.uri=new zo(I.scheme,I.user,I.host,I.port),delete I.scheme,delete I.user,delete I.host,delete I.host_type,delete I.port}catch{I=-1}}()),i===null&&(s=f),i}function we(){var i,e,l,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?(l=Vt(),l=l!==null?l:"",l!==null?(u=un(),u!==null?(f=ai(),f!==null?(p=gi(),p=p!==null?p:"",p!==null?i=[i,e,l,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{I.uri=new zo(I.scheme,I.user,I.host,I.port,I.uri_params,I.uri_headers),delete I.scheme,delete I.user,delete I.host,delete I.host_type,delete I.port,delete I.uri_params,o==="SIP_URI"&&(I=I.uri)}catch{I=-1}}()),i===null&&(s=m),i}function Ne(){var i;return i=st(),i===null&&(i=He()),i}function st(){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(l,u){I.scheme=u.toLowerCase()}(e,i)),i===null&&(s=e),i}function He(){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(l,u){I.scheme=u.toLowerCase()}(e,i)),i===null&&(s=e),i}function Vt(){var i,e,l,u,f,p;return u=s,f=s,i=At(),i!==null?(p=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Bn(),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?(n.charCodeAt(s)===64?(l="@",s++):(l=null,d('"@"')),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){I.user=decodeURIComponent(n.substring(s-1,m))}(u)),i===null&&(s=u),i}function At(){var i,e;if(e=x(),e===null&&(e=_e(),e===null&&(e=qn())),e!==null)for(i=[];e!==null;)i.push(e),e=x(),e===null&&(e=_e(),e===null&&(e=qn()));else i=null;return i}function qn(){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 Bn(){var i,e,l;for(l=s,i=[],e=x(),e===null&&(e=_e(),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=_e(),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){I.password=n.substring(s,u)}(l)),i===null&&(s=l),i}function un(){var i,e,l,u,f;return u=s,i=ls(),i!==null?(f=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=$s(),l!==null?e=[e,l]:(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 ls(){var i,e;return e=s,i=Cs(),i===null&&(i=ut(),i===null&&(i=Wn())),i!==null&&(i=function(l){return I.host=n.substring(s,l).toLowerCase(),I.host}(e)),i===null&&(s=e),i}function Cs(){var i,e,l,u,f,p;for(u=s,f=s,i=[],p=s,e=cn(),e!==null?(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p);e!==null;)i.push(e),p=s,e=cn(),e!==null?(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p);return i!==null?(e=Gn(),e!==null?(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l=l!==null?l:"",l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(m){return I.host_type="domain",n.substring(s,m)}(u)),i===null&&(s=u),i}function cn(){var i,e,l,u;if(u=s,i=k(),i!==null){for(e=[],l=k(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,d('"_"'))));l!==null;)e.push(l),l=k(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,d('"_"'))));e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function Gn(){var i,e,l,u;if(u=s,i=T(),i!==null){for(e=[],l=k(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,d('"_"'))));l!==null;)e.push(l),l=k(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,d('"_"'))));e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function Wn(){var i,e,l,u,f;return u=s,f=s,n.charCodeAt(s)===91?(i="[",s++):(i=null,d('"["')),i!==null?(e=fn(),e!==null?(n.charCodeAt(s)===93?(l="]",s++):(l=null,d('"]"')),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return I.host_type="IPv6",n.substring(s,p)}(u)),i===null&&(s=u),i}function fn(){var i,e,l,u,f,p,m,v,y,O,le,xe,Dt,Js,L,b;return Js=s,L=s,i=Te(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==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?(O=":",s++):(O=null,d('":"')),O!==null?(le=Te(),le!==null?(n.charCodeAt(s)===58?(xe=":",s++):(xe=null,d('":"')),xe!==null?(Dt=ae(),Dt!==null?i=[i,e,l,u,f,p,m,v,y,O,le,xe,Dt]:(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?(l=":",s++):(l=null,d('":"')),l!==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?(O=Te(),O!==null?(n.charCodeAt(s)===58?(le=":",s++):(le=null,d('":"')),le!==null?(xe=ae(),xe!==null?i=[i,e,l,u,f,p,m,v,y,O,le,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?(l=":",s++):(l=null,d('":"')),l!==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?(O=ae(),O!==null?i=[i,e,l,u,f,p,m,v,y,O]:(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?(l=":",s++):(l=null,d('":"')),l!==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,l,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?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=ae(),p!==null?i=[i,e,l,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?(l=":",s++):(l=null,d('":"')),l!==null?(u=ae(),u!==null?i=[i,e,l,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?(l=Te(),l!==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?(O=":",s++):(O=null,d('":"')),O!==null?(le=ae(),le!==null?i=[i,e,l,u,f,p,m,v,y,O,le]:(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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(n.substr(s,2)==="::"?(l="::",s+=2):(l=null,d('"::"')),l!==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?(O=ae(),O!==null?i=[i,e,l,u,f,p,m,v,y,O]:(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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==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,l,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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==null?(b=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=b)):(u=null,s=b),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,l,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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==null?(b=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=b)):(u=null,s=b),u=u!==null?u:"",u!==null?(b=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,s=b)):(f=null,s=b),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,l,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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==null?(b=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=b)):(u=null,s=b),u=u!==null?u:"",u!==null?(b=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,s=b)):(f=null,s=b),f=f!==null?f:"",f!==null?(b=s,n.charCodeAt(s)===58?(p=":",s++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?p=[p,m]:(p=null,s=b)):(p=null,s=b),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,l,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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==null?(b=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=b)):(u=null,s=b),u=u!==null?u:"",u!==null?(b=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,s=b)):(f=null,s=b),f=f!==null?f:"",f!==null?(b=s,n.charCodeAt(s)===58?(p=":",s++):(p=null,d('":"')),p!==null?(m=Te(),m!==null?p=[p,m]:(p=null,s=b)):(p=null,s=b),p=p!==null?p:"",p!==null?(b=s,n.charCodeAt(s)===58?(m=":",s++):(m=null,d('":"')),m!==null?(v=Te(),v!==null?m=[m,v]:(m=null,s=b)):(m=null,s=b),m=m!==null?m:"",m!==null?(n.substr(s,2)==="::"?(v="::",s+=2):(v=null,d('"::"')),v!==null?i=[i,e,l,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 I.host_type="IPv6",n.substring(s,Se)}(Js)),i===null&&(s=Js),i}function Te(){var i,e,l,u,f;return f=s,i=S(),i!==null?(e=S(),e=e!==null?e:"",e!==null?(l=S(),l=l!==null?l:"",l!==null?(u=S(),u=u!==null?u:"",u!==null?i=[i,e,l,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function ae(){var i,e,l,u;return u=s,i=Te(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i===null&&(i=ut()),i}function ut(){var i,e,l,u,f,p,m,v,y;return v=s,y=s,i=Zt(),i!==null?(n.charCodeAt(s)===46?(e=".",s++):(e=null,d('"."')),e!==null?(l=Zt(),l!==null?(n.charCodeAt(s)===46?(u=".",s++):(u=null,d('"."')),u!==null?(f=Zt(),f!==null?(n.charCodeAt(s)===46?(p=".",s++):(p=null,d('"."')),p!==null?(m=Zt(),m!==null?i=[i,e,l,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(O){return I.host_type="IPv4",n.substring(s,O)}(v)),i===null&&(s=v),i}function Zt(){var i,e,l,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?(l=g(),l!==null?i=[i,e,l]:(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?(l=g(),l!==null?i=[i,e,l]:(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 $s(){var i,e,l,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?(l=g(),l=l!==null?l:"",l!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?i=[i,e,l,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("")),I.port=y,y}(p,i)),i===null&&(s=p),i}function ai(){var i,e,l,u;for(i=[],u=s,n.charCodeAt(s)===59?(e=";",s++):(e=null,d('";"')),e!==null?(l=Kn(),l!==null?e=[e,l]:(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?(l=Kn(),l!==null?e=[e,l]:(e=null,s=u)):(e=null,s=u);return i}function Kn(){var i;return i=Yn(),i===null&&(i=ui(),i===null&&(i=ci(),i===null&&(i=fi(),i===null&&(i=di(),i===null&&(i=hi(),i===null&&(i=_i())))))),i}function Yn(){var i,e,l,u;return l=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=D())))),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.uri_params||(I.uri_params={}),I.uri_params.transport=p.toLowerCase()}(l,i[1])),i===null&&(s=l),i}function ui(){var i,e,l,u;return l=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=D())),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.uri_params||(I.uri_params={}),I.uri_params.user=p.toLowerCase()}(l,i[1])),i===null&&(s=l),i}function ci(){var i,e,l,u;return l=s,u=s,n.substr(s,7).toLowerCase()==="method="?(i=n.substr(s,7),s+=7):(i=null,d('"method="')),i!==null?(e=Tn(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.uri_params||(I.uri_params={}),I.uri_params.method=p}(l,i[1])),i===null&&(s=l),i}function fi(){var i,e,l,u;return l=s,u=s,n.substr(s,4).toLowerCase()==="ttl="?(i=n.substr(s,4),s+=4):(i=null,d('"ttl="')),i!==null?(e=mr(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.params||(I.params={}),I.params.ttl=p}(l,i[1])),i===null&&(s=l),i}function di(){var i,e,l,u;return l=s,u=s,n.substr(s,6).toLowerCase()==="maddr="?(i=n.substr(s,6),s+=6):(i=null,d('"maddr="')),i!==null?(e=ls(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.uri_params||(I.uri_params={}),I.uri_params.maddr=p}(l,i[1])),i===null&&(s=l),i}function hi(){var i,e,l,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?(l=D(),l!==null?e=[e,l]:(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){I.uri_params||(I.uri_params={}),I.uri_params.lr=void 0}()),i===null&&(s=u),i}function _i(){var i,e,l,u,f,p;return u=s,f=s,i=pi(),i!==null?(p=s,n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(l=mi(),l!==null?e=[e,l]:(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){I.uri_params||(I.uri_params={}),typeof y>"u"?y=void 0:y=y[1],I.uri_params[v.toLowerCase()]=y}(u,i[0],i[1])),i===null&&(s=u),i}function pi(){var i,e,l;if(l=s,e=Hs(),e!==null)for(i=[];e!==null;)i.push(e),e=Hs();else i=null;return i!==null&&(i=function(u,f){return f.join("")}(l,i)),i===null&&(s=l),i}function mi(){var i,e,l;if(l=s,e=Hs(),e!==null)for(i=[];e!==null;)i.push(e),e=Hs();else i=null;return i!==null&&(i=function(u,f){return f.join("")}(l,i)),i===null&&(s=l),i}function Hs(){var i;return i=Fs(),i===null&&(i=x(),i===null&&(i=_e())),i}function Fs(){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 gi(){var i,e,l,u,f,p,m;if(p=s,n.charCodeAt(s)===63?(i="?",s++):(i=null,d('"?"')),i!==null)if(e=dn(),e!==null){for(l=[],m=s,n.charCodeAt(s)===38?(u="&",s++):(u=null,d('"&"')),u!==null?(f=dn(),f!==null?u=[u,f]:(u=null,s=m)):(u=null,s=m);u!==null;)l.push(u),m=s,n.charCodeAt(s)===38?(u="&",s++):(u=null,d('"&"')),u!==null?(f=dn(),f!==null?u=[u,f]:(u=null,s=m)):(u=null,s=m);l!==null?i=[i,e,l]:(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i}function dn(){var i,e,l,u,f;return u=s,f=s,i=hn(),i!==null?(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(l=Ti(),l!==null?i=[i,e,l]:(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(""),I.uri_headers||(I.uri_headers={}),I.uri_headers[m]?I.uri_headers[m].push(v):I.uri_headers[m]=[v]}(u,i[0],i[2])),i===null&&(s=u),i}function hn(){var i,e;if(e=Vs(),e===null&&(e=x(),e===null&&(e=_e())),e!==null)for(i=[];e!==null;)i.push(e),e=Vs(),e===null&&(e=x(),e===null&&(e=_e()));else i=null;return i}function Ti(){var i,e;for(i=[],e=Vs(),e===null&&(e=x(),e===null&&(e=_e()));e!==null;)i.push(e),e=Vs(),e===null&&(e=x(),e===null&&(e=_e()));return i}function Vs(){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 _n(){var i;return i=vn(),i===null&&(i=Do()),i}function Do(){var i,e,l,u,f,p;return p=s,i=Tn(),i!==null?(e=C(),e!==null?(l=vi(),l!==null?(u=C(),u!==null?(f=Xn(),f!==null?i=[i,e,l,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function vi(){var i;return i=we(),i===null&&(i=Jn()),i}function Jn(){var i,e,l,u;return u=s,i=Gs(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=zn(),l===null&&(l=mn()),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function zn(){var i,e,l,u,f;return u=s,i=Si(),i===null&&(i=pn()),i!==null?(f=s,n.charCodeAt(s)===63?(e="?",s++):(e=null,d('"?"')),e!==null?(l=Ri(),l!==null?e=[e,l]:(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 Si(){var i,e,l,u;return u=s,n.substr(s,2)==="//"?(i="//",s+=2):(i=null,d('"//"')),i!==null?(e=yi(),e!==null?(l=pn(),l=l!==null?l:"",l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function pn(){var i,e,l;return l=s,n.charCodeAt(s)===47?(i="/",s++):(i=null,d('"/"')),i!==null?(e=Ei(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function mn(){var i,e,l,u;if(u=s,i=qs(),i!==null){for(e=[],l=js();l!==null;)e.push(l),l=js();e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function js(){var i;return i=re(),i===null&&(i=x(),i===null&&(i=_e())),i}function qs(){var i;return i=x(),i===null&&(i=_e(),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 Ei(){var i,e,l,u,f,p;if(f=s,i=gn(),i!==null){for(e=[],p=s,n.charCodeAt(s)===47?(l="/",s++):(l=null,d('"/"')),l!==null?(u=gn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,n.charCodeAt(s)===47?(l="/",s++):(l=null,d('"/"')),l!==null?(u=gn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function gn(){var i,e,l,u,f,p;for(f=s,i=[],e=As();e!==null;)i.push(e),e=As();if(i!==null){for(e=[],p=s,n.charCodeAt(s)===59?(l=";",s++):(l=null,d('";"')),l!==null?(u=Bs(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,n.charCodeAt(s)===59?(l=";",s++):(l=null,d('";"')),l!==null?(u=Bs(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Bs(){var i,e;for(i=[],e=As();e!==null;)i.push(e),e=As();return i}function As(){var i;return i=x(),i===null&&(i=_e(),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 Gs(){var i,e,l,u,f;if(u=s,f=s,i=T(),i!==null){for(e=[],l=T(),l===null&&(l=g(),l===null&&(n.charCodeAt(s)===43?(l="+",s++):(l=null,d('"+"')),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."'))))));l!==null;)e.push(l),l=T(),l===null&&(l=g(),l===null&&(n.charCodeAt(s)===43?(l="+",s++):(l=null,d('"+"')),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."'))))));e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i!==null&&(i=function(p){I.scheme=n.substring(s,p)}(u)),i===null&&(s=u),i}function yi(){var i;return i=Ci(),i===null&&(i=Ai()),i}function Ci(){var i,e,l,u;return l=s,u=s,i=Vt(),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=un(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i=i!==null?i:"",i}function Ai(){var i,e;if(e=x(),e===null&&(e=_e(),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=_e(),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 Ri(){var i,e;for(i=[],e=js();e!==null;)i.push(e),e=js();return i}function Xn(){var i,e,l,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(l=[];u!==null;)l.push(u),u=g();else l=null;if(l!==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,l,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){I.sip_version=n.substring(s,y)}(m)),i===null&&(s=m),i}function Qn(){var i;return n.substr(s,6)==="INVITE"?(i="INVITE",s+=6):(i=null,d('"INVITE"')),i}function bi(){var i;return n.substr(s,3)==="ACK"?(i="ACK",s+=3):(i=null,d('"ACK"')),i}function Ii(){var i;return n.substr(s,7)==="OPTIONS"?(i="OPTIONS",s+=7):(i=null,d('"OPTIONS"')),i}function wi(){var i;return n.substr(s,3)==="BYE"?(i="BYE",s+=3):(i=null,d('"BYE"')),i}function Oi(){var i;return n.substr(s,6)==="CANCEL"?(i="CANCEL",s+=6):(i=null,d('"CANCEL"')),i}function Di(){var i;return n.substr(s,8)==="REGISTER"?(i="REGISTER",s+=8):(i=null,d('"REGISTER"')),i}function Ni(){var i;return n.substr(s,9)==="SUBSCRIBE"?(i="SUBSCRIBE",s+=9):(i=null,d('"SUBSCRIBE"')),i}function xi(){var i;return n.substr(s,6)==="NOTIFY"?(i="NOTIFY",s+=6):(i=null,d('"NOTIFY"')),i}function Ui(){var i;return n.substr(s,5)==="REFER"?(i="REFER",s+=5):(i=null,d('"REFER"')),i}function Tn(){var i,e;return e=s,i=Qn(),i===null&&(i=bi(),i===null&&(i=Ii(),i===null&&(i=wi(),i===null&&(i=Oi(),i===null&&(i=Di(),i===null&&(i=Ni(),i===null&&(i=xi(),i===null&&(i=Ui(),i===null&&(i=D()))))))))),i!==null&&(i=function(l){return I.method=n.substring(s,l),I.method}(e)),i===null&&(s=e),i}function vn(){var i,e,l,u,f,p;return p=s,i=Xn(),i!==null?(e=C(),e!==null?(l=ki(),l!==null?(u=C(),u!==null?(f=Mi(),f!==null?i=[i,e,l,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function ki(){var i,e;return e=s,i=Pi(),i!==null&&(i=function(l,u){I.status_code=parseInt(u.join(""))}(e,i)),i===null&&(s=e),i}function Pi(){var i,e,l,u;return u=s,i=g(),i!==null?(e=g(),e!==null?(l=g(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Mi(){var i,e,l;for(l=s,i=[],e=re(),e===null&&(e=x(),e===null&&(e=_e(),e===null&&(e=K(),e===null&&(e=V(),e===null&&(e=C(),e===null&&(e=H()))))));e!==null;)i.push(e),e=re(),e===null&&(e=x(),e===null&&(e=_e(),e===null&&(e=K(),e===null&&(e=V(),e===null&&(e=C(),e===null&&(e=H()))))));return i!==null&&(i=function(u){I.reason_phrase=n.substring(s,u)}(l)),i===null&&(s=l),i}function No(){var i,e,l,u,f,p;if(f=s,i=yn(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=yn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=yn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Nu(){var i,e,l,u,f,p;return u=s,f=s,i=je(),i!==null?(p=s,n.charCodeAt(s)===64?(e="@",s++):(e=null,d('"@"')),e!==null?(l=je(),l!==null?e=[e,l]:(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){I=n.substring(s,m)}(u)),i===null&&(s=u),i}function xu(){var i,e,l,u,f,p,m;if(f=s,i=Q(),i===null)if(p=s,i=Zn(),i!==null){for(e=[],m=s,l=Re(),l!==null?(u=Zn(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=Re(),l!==null?(u=Zn(),u!==null?l=[l,u]:(l=null,s=m)):(l=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,O;for(O=I.multi_header.length,y=0;y<O;y++)if(I.multi_header[y].parsed===null){I=null;break}I!==null?I=I.multi_header:I=-1}()),i===null&&(s=f),i}function Zn(){var i,e,l,u,f,p,m;if(f=s,p=s,i=me(),i===null&&(i=jt()),i!==null){for(e=[],m=s,l=oe(),l!==null?(u=Ws(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=oe(),l!==null?(u=Ws(),u!==null?l=[l,u]:(l=null,s=m)):(l=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;I.multi_header||(I.multi_header=[]);try{y=new Rs(I.uri,I.display_name,I.params),delete I.uri,delete I.display_name,delete I.params}catch{y=null}I.multi_header.push({possition:s,offset:v,parsed:y})}(f)),i===null&&(s=f),i}function jt(){var i,e,l,u,f;return f=s,i=qt(),i=i!==null?i:"",i!==null?(e=Pe(),e!==null?(l=we(),l!==null?(u=Ie(),u!==null?i=[i,e,l,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function qt(){var i,e,l,u,f,p,m;if(f=s,p=s,i=D(),i!==null){for(e=[],m=s,l=pe(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=pe(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=m)):(l=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"?I.display_name=y:I.display_name=y[1].reduce(function(O,le){return O+le[0]+le[1]},y[0])}(f,i)),i===null&&(s=f),i}function Ws(){var i;return i=er(),i===null&&(i=Li(),i===null&&(i=ze())),i}function er(){var i,e,l,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=B(),e!==null?(l=as(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.params||(I.params={}),I.params.q=m}(u,i[2])),i===null&&(s=u),i}function Li(){var i,e,l,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=B(),e!==null?(l=os(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.params||(I.params={}),I.params.expires=m}(u,i[2])),i===null&&(s=u),i}function os(){var i,e,l;if(l=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(""))}(l,i)),i===null&&(s=l),i}function as(){var i,e,l,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?(l=g(),l=l!==null?l:"",l!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?e=[e,l,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 ze(){var i,e,l,u,f,p;return u=s,f=s,i=D(),i!==null?(p=s,e=B(),e!==null?(l=Xe(),l!==null?e=[e,l]:(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){I.params||(I.params={}),typeof y>"u"?y=void 0:y=y[1],I.params[v.toLowerCase()]=y}(u,i[0],i[1])),i===null&&(s=u),i}function Xe(){var i;return i=D(),i===null&&(i=ls(),i===null&&(i=be())),i}function xo(){var i,e,l,u,f,p;if(f=s,i=Uo(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=tr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=tr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Uo(){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=D())))),i}function tr(){var i;return i=sr(),i===null&&(i=ze()),i}function sr(){var i,e,l,u;return u=s,n.substr(s,8).toLowerCase()==="handling"?(i=n.substr(s,8),s+=8):(i=null,d('"handling"')),i!==null?(e=B(),e!==null?(n.substr(s,8).toLowerCase()==="optional"?(l=n.substr(s,8),s+=8):(l=null,d('"optional"')),l===null&&(n.substr(s,8).toLowerCase()==="required"?(l=n.substr(s,8),s+=8):(l=null,d('"required"')),l===null&&(l=D())),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function ko(){var i,e,l,u,f,p;if(f=s,i=D(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Uu(){var i,e,l;if(l=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){I=parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function ku(){var i,e;return e=s,i=Po(),i!==null&&(i=function(l){I=n.substring(s,l)}(e)),i===null&&(s=e),i}function Po(){var i,e,l,u,f,p,m,v;if(m=s,i=$i(),i!==null)if(e=W(),e!==null)if(l=Vi(),l!==null){for(u=[],v=s,f=oe(),f!==null?(p=nr(),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=nr(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i}function $i(){var i;return i=Hi(),i===null&&(i=Fi()),i}function Hi(){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=Sn()))))),i}function Fi(){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=Sn())),i}function Sn(){var i;return i=D(),i===null&&(i=En()),i}function En(){var i,e,l;return l=s,n.substr(s,2).toLowerCase()==="x-"?(i=n.substr(s,2),s+=2):(i=null,d('"x-"')),i!==null?(e=D(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function Vi(){var i;return i=Sn(),i===null&&(i=D()),i}function nr(){var i,e,l,u;return u=s,i=D(),i!==null?(e=B(),e!==null?(l=rr(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function rr(){var i;return i=D(),i===null&&(i=be()),i}function Mo(){var i,e,l,u;return u=s,i=Lo(),i!==null?(e=pe(),e!==null?(l=Tn(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Lo(){var i,e,l;if(l=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){I.value=parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function $o(){var i,e;return e=s,i=os(),i!==null&&(i=function(l,u){I=u}(e,i)),i===null&&(s=e),i}function Pu(){var i,e,l,u,f,p,m;if(f=s,p=s,i=yn(),i!==null){for(e=[],m=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v,y){I.event=y.join("").toLowerCase()}(f,i[0])),i===null&&(s=f),i}function yn(){var i,e,l,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Cn(){var i,e,l,u,f,p,m;if(f=s,p=s,i=me(),i===null&&(i=jt()),i!==null){for(e=[],m=s,l=oe(),l!==null?(u=ji(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=oe(),l!==null?(u=ji(),u!==null?l=[l,u]:(l=null,s=m)):(l=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=I.tag;try{I=new Rs(I.uri,I.display_name,I.params),y&&I.setParam("tag",y)}catch{I=-1}}()),i===null&&(s=f),i}function ji(){var i;return i=An(),i===null&&(i=ze()),i}function An(){var i,e,l,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=B(),e!==null?(l=D(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.tag=m}(u,i[2])),i===null&&(s=u),i}function qi(){var i,e,l;if(l=s,e=g(),e!==null)for(i=[];e!==null;)i.push(e),e=g();else i=null;return i!==null&&(i=function(u,f){I=parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function Mu(){var i,e;return e=s,i=os(),i!==null&&(i=function(l,u){I=u}(e,i)),i===null&&(s=e),i}function Lu(){var i,e,l,u,f,p,m,v,y,O;for(v=s,y=s,i=[],e=qt();e!==null;)i.push(e),e=qt();if(i!==null)if(e=Pe(),e!==null)if(l=we(),l!==null)if(u=Ie(),u!==null){for(f=[],O=s,p=oe(),p!==null?(m=ze(),m!==null?p=[p,m]:(p=null,s=O)):(p=null,s=O);p!==null;)f.push(p),O=s,p=oe(),p!==null?(m=ze(),m!==null?p=[p,m]:(p=null,s=O)):(p=null,s=O);f!==null?i=[i,e,l,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(le){try{I=new Rs(I.uri,I.display_name,I.params)}catch{I=-1}}()),i===null&&(s=v),i}function $u(){var i;return i=Bi(),i}function Bi(){var i,e,l,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(l=us(),l!==null){for(u=[],v=s,f=Re(),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=Re(),f!==null?(p=us(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i===null&&(i=ir()),i}function ir(){var i,e,l,u,f,p,m,v;if(m=s,i=D(),i!==null)if(e=pe(),e!==null)if(l=Ks(),l!==null){for(u=[],v=s,f=Re(),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=Re(),f!==null?(p=Ks(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,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,e,l,u;return u=s,i=D(),i!==null?(e=B(),e!==null?(l=D(),l===null&&(l=be()),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function us(){var i;return i=Rn(),i===null&&(i=Wi(),i===null&&(i=In(),i===null&&(i=Yi(),i===null&&(i=Ji(),i===null&&(i=zi(),i===null&&(i=Xi(),i===null&&(i=Ks()))))))),i}function Rn(){var i,e,l,u;return u=s,n.substr(s,5).toLowerCase()==="realm"?(i=n.substr(s,5),s+=5):(i=null,d('"realm"')),i!==null?(e=B(),e!==null?(l=Gi(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Gi(){var i,e;return e=s,i=Oe(),i!==null&&(i=function(l,u){I.realm=u}(e,i)),i===null&&(s=e),i}function Wi(){var i,e,l,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=B(),e!==null)if(l=lt(),l!==null)if(u=bn(),u!==null){if(f=[],y=s,m=C(),m!==null)for(p=[];m!==null;)p.push(m),m=C();else p=null;for(p!==null?(m=bn(),m!==null?p=[p,m]:(p=null,s=y)):(p=null,s=y);p!==null;){if(f.push(p),y=s,m=C(),m!==null)for(p=[];m!==null;)p.push(m),m=C();else p=null;p!==null?(m=bn(),m!==null?p=[p,m]:(p=null,s=y)):(p=null,s=y)}f!==null?(p=at(),p!==null?i=[i,e,l,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 bn(){var i;return i=Jn(),i===null&&(i=pn()),i}function In(){var i,e,l,u;return u=s,n.substr(s,5).toLowerCase()==="nonce"?(i=n.substr(s,5),s+=5):(i=null,d('"nonce"')),i!==null?(e=B(),e!==null?(l=Ki(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Ki(){var i,e;return e=s,i=Oe(),i!==null&&(i=function(l,u){I.nonce=u}(e,i)),i===null&&(s=e),i}function Yi(){var i,e,l,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=B(),e!==null?(l=Oe(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.opaque=m}(u,i[2])),i===null&&(s=u),i}function Ji(){var i,e,l,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=B(),e!==null?(f=s,n.substr(s,4).toLowerCase()==="true"?(l=n.substr(s,4),s+=4):(l=null,d('"true"')),l!==null&&(l=function(p){I.stale=!0}()),l===null&&(s=f),l===null&&(f=s,n.substr(s,5).toLowerCase()==="false"?(l=n.substr(s,5),s+=5):(l=null,d('"false"')),l!==null&&(l=function(p){I.stale=!1}()),l===null&&(s=f)),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function zi(){var i,e,l,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=B(),e!==null?(n.substr(s,3).toLowerCase()==="md5"?(l=n.substr(s,3),s+=3):(l=null,d('"MD5"')),l===null&&(n.substr(s,8).toLowerCase()==="md5-sess"?(l=n.substr(s,8),s+=8):(l=null,d('"MD5-sess"')),l===null&&(l=D())),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.algorithm=m.toUpperCase()}(u,i[2])),i===null&&(s=u),i}function Xi(){var i,e,l,u,f,p,m,v,y,O;if(v=s,n.substr(s,3).toLowerCase()==="qop"?(i=n.substr(s,3),s+=3):(i=null,d('"qop"')),i!==null)if(e=B(),e!==null)if(l=lt(),l!==null){if(y=s,u=wn(),u!==null){for(f=[],O=s,n.charCodeAt(s)===44?(p=",",s++):(p=null,d('","')),p!==null?(m=wn(),m!==null?p=[p,m]:(p=null,s=O)):(p=null,s=O);p!==null;)f.push(p),O=s,n.charCodeAt(s)===44?(p=",",s++):(p=null,d('","')),p!==null?(m=wn(),m!==null?p=[p,m]:(p=null,s=O)):(p=null,s=O);f!==null?u=[u,f]:(u=null,s=y)}else u=null,s=y;u!==null?(f=at(),f!==null?i=[i,e,l,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 wn(){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=D())),i!==null&&(i=function(l,u){I.qop||(I.qop=[]),I.qop.push(u.toLowerCase())}(e,i)),i===null&&(s=e),i}function lr(){var i,e,l,u,f,p;if(f=s,i=D(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Hu(){var i,e,l,u,f,p,m;if(f=s,p=s,i=or(),i!==null){for(e=[],m=s,l=Re(),l!==null?(u=or(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=Re(),l!==null?(u=or(),u!==null?l=[l,u]:(l=null,s=m)):(l=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,O;for(O=I.multi_header.length,y=0;y<O;y++)if(I.multi_header[y].parsed===null){I=null;break}I!==null?I=I.multi_header:I=-1}()),i===null&&(s=f),i}function or(){var i,e,l,u,f,p,m;if(f=s,p=s,i=jt(),i!==null){for(e=[],m=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=m)):(l=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;I.multi_header||(I.multi_header=[]);try{y=new Rs(I.uri,I.display_name,I.params),delete I.uri,delete I.display_name,delete I.params}catch{y=null}I.multi_header.push({possition:s,offset:v,parsed:y})}(f)),i===null&&(s=f),i}function ar(){var i,e,l,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=D()),i!==null){for(e=[],m=s,l=oe(),l!==null?(u=Qi(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=oe(),l!==null?(u=Qi(),u!==null?l=[l,u]:(l=null,s=m)):(l=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(I.protocol=y.toLowerCase(),I.params||(I.params={}),I.params.text&&I.params.text[0]==='"'){var O=I.params.text;I.text=O.substring(1,O.length-1),delete I.params.text}}(f,i[0])),i===null&&(s=f),i}function Qi(){var i;return i=ur(),i===null&&(i=ze()),i}function ur(){var i,e,l,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=B(),e!==null){if(u=g(),u!==null)for(l=[];u!==null;)l.push(u),u=g();else l=null;l!==null?i=[i,e,l]:(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(m,v){I.cause=parseInt(v.join(""))}(f,i[2])),i===null&&(s=f),i}function Ho(){var i,e,l,u,f,p;if(f=s,i=D(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Fu(){var i,e,l,u,f,p;if(f=s,i=cr(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=cr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=cr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function cr(){var i,e,l,u,f,p;if(f=s,i=jt(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function fr(){var i,e,l,u,f,p;if(f=s,i=Fo(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=dr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=dr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Fo(){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=D()))),i!==null&&(i=function(l){I.state=n.substring(s,l)}(e)),i===null&&(s=e),i}function dr(){var i,e,l,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=B(),e!==null?(l=hr(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){typeof m<"u"&&(I.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=B(),e!==null?(l=os(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){typeof m<"u"&&(I.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=B(),e!==null?(l=os(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){typeof m<"u"&&(I.retry_after=m)}(u,i[2])),i===null&&(s=u),i===null&&(i=ze()))),i}function hr(){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=D()))))))),i}function Vo(){var i;return i=q(),i=i!==null?i:"",i}function Vu(){var i,e,l,u,f,p;if(f=s,i=D(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i=i!==null?i:"",i}function ju(){var i,e,l,u,f,p,m;if(f=s,p=s,i=me(),i===null&&(i=jt()),i!==null){for(e=[],m=s,l=oe(),l!==null?(u=Zi(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=oe(),l!==null?(u=Zi(),u!==null?l=[l,u]:(l=null,s=m)):(l=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=I.tag;try{I=new Rs(I.uri,I.display_name,I.params),y&&I.setParam("tag",y)}catch{I=-1}}()),i===null&&(s=f),i}function Zi(){var i;return i=An(),i===null&&(i=ze()),i}function el(){var i,e,l,u,f,p;if(f=s,i=_r(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=_r(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=_r(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function _r(){var i,e,l,u,f,p,m,v;if(m=s,i=ll(),i!==null)if(e=pe(),e!==null)if(l=ul(),l!==null){for(u=[],v=s,f=oe(),f!==null?(p=Ys(),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=Ys(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=m)}else i=null,s=m;else i=null,s=m;else i=null,s=m;return i}function Ys(){var i;return i=pr(),i===null&&(i=tl(),i===null&&(i=sl(),i===null&&(i=nl(),i===null&&(i=rl(),i===null&&(i=ze()))))),i}function pr(){var i,e,l,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=B(),e!==null?(l=mr(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.ttl=m}(u,i[2])),i===null&&(s=u),i}function tl(){var i,e,l,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=B(),e!==null?(l=ls(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.maddr=m}(u,i[2])),i===null&&(s=u),i}function sl(){var i,e,l,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=B(),e!==null?(l=ut(),l===null&&(l=fn()),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.received=m}(u,i[2])),i===null&&(s=u),i}function nl(){var i,e,l,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=B(),e!==null?(l=D(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.branch=m}(u,i[2])),i===null&&(s=u),i}function rl(){var i,e,l,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=B(),e!==null?(l=il(),l!==null?e=[e,l]:(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 il(){var i,e,l,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?(l=g(),l=l!==null?l:"",l!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?i=[i,e,l,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){I.rport=parseInt(y.join(""))}(p,i)),i===null&&(s=p),i}function ll(){var i,e,l,u,f,p;return p=s,i=ol(),i!==null?(e=W(),e!==null?(l=D(),l!==null?(u=W(),u!==null?(f=al(),f!==null?i=[i,e,l,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function ol(){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=D()),i!==null&&(i=function(l,u){I.protocol=u}(e,i)),i===null&&(s=e),i}function al(){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=D())))),i!==null&&(i=function(l,u){I.transport=u}(e,i)),i===null&&(s=e),i}function ul(){var i,e,l,u,f;return u=s,i=cl(),i!==null?(f=s,e=ye(),e!==null?(l=fl(),l!==null?e=[e,l]:(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 cl(){var i,e;return e=s,i=ut(),i===null&&(i=Wn(),i===null&&(i=Cs())),i!==null&&(i=function(l){I.host=n.substring(s,l)}(e)),i===null&&(s=e),i}function fl(){var i,e,l,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?(l=g(),l=l!==null?l:"",l!==null?(u=g(),u=u!==null?u:"",u!==null?(f=g(),f=f!==null?f:"",f!==null?i=[i,e,l,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){I.port=parseInt(y.join(""))}(p,i)),i===null&&(s=p),i}function mr(){var i,e,l,u,f;return u=s,f=s,i=g(),i!==null?(e=g(),e=e!==null?e:"",e!==null?(l=g(),l=l!==null?l:"",l!==null?i=[i,e,l]:(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 dl(){var i;return i=Bi(),i}function qu(){var i,e,l,u,f,p;if(f=s,i=jo(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=gr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=gr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function jo(){var i,e;return e=s,i=os(),i!==null&&(i=function(l,u){I.expires=u}(e,i)),i===null&&(s=e),i}function gr(){var i;return i=Tr(),i===null&&(i=ze()),i}function Tr(){var i,e,l,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=B(),e!==null?(n.substr(s,3).toLowerCase()==="uac"?(l=n.substr(s,3),s+=3):(l=null,d('"uac"')),l===null&&(n.substr(s,3).toLowerCase()==="uas"?(l=n.substr(s,3),s+=3):(l=null,d('"uas"'))),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.refresher=m.toLowerCase()}(u,i[2])),i===null&&(s=u),i}function qo(){var i,e,l,u;return u=s,i=D(),i!==null?(e=N(),e!==null?(l=Bo(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Bo(){var i,e;for(i=[],e=j(),e===null&&(e=V(),e===null&&(e=pe()));e!==null;)i.push(e),e=j(),e===null&&(e=V(),e===null&&(e=pe()));return i}function Go(){var i,e;for(i=[],e=A();e!==null;)i.push(e),e=A();return i}function Bu(){var i,e,l;return l=s,n.substr(s,5)==="uuid:"?(i="uuid:",s+=5):(i=null,d('"uuid:"')),i!==null?(e=Wo(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function Wo(){var i,e,l,u,f,p,m,v,y,O,le;return O=s,le=s,i=Gt(),i!==null?(n.charCodeAt(s)===45?(e="-",s++):(e=null,d('"-"')),e!==null?(l=Bt(),l!==null?(n.charCodeAt(s)===45?(u="-",s++):(u=null,d('"-"')),u!==null?(f=Bt(),f!==null?(n.charCodeAt(s)===45?(p="-",s++):(p=null,d('"-"')),p!==null?(m=Bt(),m!==null?(n.charCodeAt(s)===45?(v="-",s++):(v=null,d('"-"')),v!==null?(y=hl(),y!==null?i=[i,e,l,u,f,p,m,v,y]:(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le),i!==null&&(i=function(xe,Dt){I=n.substring(s+5,xe)}(O,i[0])),i===null&&(s=O),i}function Bt(){var i,e,l,u,f;return f=s,i=S(),i!==null?(e=S(),e!==null?(l=S(),l!==null?(u=S(),u!==null?i=[i,e,l,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function Gt(){var i,e,l;return l=s,i=Bt(),i!==null?(e=Bt(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function hl(){var i,e,l,u;return u=s,i=Bt(),i!==null?(e=Bt(),e!==null?(l=Bt(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Ko(){var i,e,l,u,f,p,m;if(f=s,p=s,i=me(),i===null&&(i=jt()),i!==null){for(e=[],m=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);l!==null;)e.push(l),m=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=m)):(l=null,s=m);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){try{I=new Rs(I.uri,I.display_name,I.params)}catch{I=-1}}()),i===null&&(s=f),i}function Gu(){var i,e,l,u,f,p;if(f=s,i=Yo(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=vr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=vr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Yo(){var i,e,l,u,f,p;return u=s,f=s,i=je(),i!==null?(p=s,n.charCodeAt(s)===64?(e="@",s++):(e=null,d('"@"')),e!==null?(l=je(),l!==null?e=[e,l]:(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){I.call_id=n.substring(s,m)}(u)),i===null&&(s=u),i}function vr(){var i;return i=Sr(),i===null&&(i=_l(),i===null&&(i=pl(),i===null&&(i=ze()))),i}function Sr(){var i,e,l,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=B(),e!==null?(l=D(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.to_tag=m}(u,i[2])),i===null&&(s=u),i}function _l(){var i,e,l,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=B(),e!==null?(l=D(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,m){I.from_tag=m}(u,i[2])),i===null&&(s=u),i}function pl(){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(l){I.early_only=!0}()),i===null&&(s=e),i}function Jo(i){i.sort();for(var e=null,l=[],u=0;u<i.length;u++)i[u]!==e&&(l.push(i[u]),e=i[u]);return l}function Wu(){for(var i=1,e=1,l=!1,u=0;u<Math.max(s,r);u++){var f=n.charAt(u);f===`
75
- `?(l||i++,e=1,l=!1):f==="\r"||f==="\u2028"||f==="\u2029"?(i++,e=1,l=!0):(e++,l=!1)}return{line:i,column:e}}var zo=ps(),Rs=Ba(),I={},w=a[o]();if(w===null||s!==n.length){var ml=Math.max(s,r),gl=ml<n.length?n.charAt(ml):null,Xo=Wu();return new this.SyntaxError(Jo(_),gl,ml,Xo.line,Xo.column),-1}return I},toSource:function(){return this._source}};return t.SyntaxError=function(n,o,a,s,r){function _(d,h){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=h?c(h):"end of input","Expected "+g+" but "+T+" found."}this.name="SyntaxError",this.expected=n,this.found=o,this.message=_(n,o),this.offset=a,this.line=s,this.column=r},t.SyntaxError.prototype=Error.prototype,t}()),Ga}var Wa,If;function ps(){if(If)return Wa;If=1;const c=De,t=mt(),n=Yt();return Wa=class Hd{static parse(a){if(a=n.parse(a,"SIP_URI"),a!==-1)return a}constructor(a,s,r,_,d={},h={}){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=_;for(const g in d)Object.prototype.hasOwnProperty.call(d,g)&&this.setParam(g,d[g]);for(const g in h)Object.prototype.hasOwnProperty.call(h,g)&&this.setHeader(g,h[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 _ of this._headers[r])a.push(`${r}=${_}`);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}},Wa}var wf;function mt(){if(wf)return et;wf=1;const c=De,t=ps(),n=Yt();et.str_utf8_length=r=>unescape(encodeURIComponent(r)).length;const o=et.isFunction=r=>r!==void 0?Object.prototype.toString.call(r)==="[object Function]":!1;et.isString=r=>r!==void 0?Object.prototype.toString.call(r)==="[object String]":!1,et.isDecimal=r=>!isNaN(r)&&parseFloat(r)===parseInt(r,10),et.isEmpty=r=>r===null||r===""||r===void 0||Array.isArray(r)&&r.length===0||typeof r=="number"&&isNaN(r),et.hasMethods=function(r,..._){for(const d of _)if(o(r[d]))return!1;return!0};const a=et.createRandomToken=(r,_=32)=>{let d,h,g="";for(d=0;d<r;d++)h=Math.random()*_|0,g+=h.toString(_);return g};et.newTag=()=>a(10),et.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,_=>{const d=Math.random()*16|0;return(_==="x"?d:d&3|8).toString(16)}),et.hostType=r=>{if(r){if(r=n.parse(r,"host"),r!==-1)return r.host_type}else return};const s=et.escapeUser=r=>encodeURIComponent(decodeURIComponent(r)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/");return et.normalizeTarget=(r,_)=>{if(r){if(r instanceof t)return r;if(typeof r=="string"){const d=r.split("@");let h,g;switch(d.length){case 1:if(!_)return;h=r,g=_;break;case 2:h=d[0],g=d[1];break;default:h=d.slice(0,d.length-1).join("@"),g=d[d.length-1]}h=h.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(h)&&(h=h.replace(/[-.()]/g,"")),r=`${c.SIP}:${s(h)}@${g}`;let T;return(T=t.parse(r))?T:void 0}else return}else return},et.headerize=r=>{const _={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},d=r.toLowerCase().replace(/_/g,"-").split("-");let h="";const g=d.length;let T;for(T=0;T<g;T++)T!==0&&(h+="-"),h+=d[T].charAt(0).toUpperCase()+d[T].substring(1);return _[h]&&(h=_[h]),h},et.sipErrorCause=r=>{for(const _ in c.SIP_ERROR_CAUSES)if(c.SIP_ERROR_CAUSES[_].indexOf(r)!==-1)return c.causes[_];return c.causes.SIP_FAILURE_CODE},et.getRandomTestNetIP=()=>{function r(_,d){return Math.floor(Math.random()*(d-_+1)+_)}return`192.0.2.${r(1,254)}`},et.calculateMD5=r=>{function _(Ee,Ce){return Ee<<Ce|Ee>>>32-Ce}function d(Ee,Ce){const be=Ee&2147483648,Oe=Ce&2147483648,ge=Ee&1073741824,he=Ce&1073741824,me=(Ee&1073741823)+(Ce&1073741823);return ge&he?me^2147483648^be^Oe:ge|he?me&1073741824?me^3221225472^be^Oe:me^1073741824^be^Oe:me^be^Oe}function h(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,he,me){return Ee=d(Ee,d(d(h(Ce,be,Oe),ge),me)),d(_(Ee,he),Ce)}function A(Ee,Ce,be,Oe,ge,he,me){return Ee=d(Ee,d(d(g(Ce,be,Oe),ge),me)),d(_(Ee,he),Ce)}function R(Ee,Ce,be,Oe,ge,he,me){return Ee=d(Ee,d(d(T(Ce,be,Oe),ge),me)),d(_(Ee,he),Ce)}function C(Ee,Ce,be,Oe,ge,he,me){return Ee=d(Ee,d(d(S(Ce,be,Oe),ge),me)),d(_(Ee,he),Ce)}function H(Ee){let Ce;const be=Ee.length,Oe=be+8,he=((Oe-Oe%64)/64+1)*16,me=new Array(he-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[he-2]=be<<3,me[he-1]=be>>>29,me}function k(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 re(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=[],F,_e,pe,P,N,q,j,K,V;const z=7,D=12,U=17,X=22,je=5,Q=9,W=14,B=20,ie=4,ve=11,Ie=16,Pe=23,Re=6,oe=10,ye=15,lt=21;for(r=re(r),x=H(r),q=1732584193,j=4023233417,K=2562383102,V=271733878,F=0;F<x.length;F+=16)_e=q,pe=j,P=K,N=V,q=E(q,j,K,V,x[F+0],z,3614090360),V=E(V,q,j,K,x[F+1],D,3905402710),K=E(K,V,q,j,x[F+2],U,606105819),j=E(j,K,V,q,x[F+3],X,3250441966),q=E(q,j,K,V,x[F+4],z,4118548399),V=E(V,q,j,K,x[F+5],D,1200080426),K=E(K,V,q,j,x[F+6],U,2821735955),j=E(j,K,V,q,x[F+7],X,4249261313),q=E(q,j,K,V,x[F+8],z,1770035416),V=E(V,q,j,K,x[F+9],D,2336552879),K=E(K,V,q,j,x[F+10],U,4294925233),j=E(j,K,V,q,x[F+11],X,2304563134),q=E(q,j,K,V,x[F+12],z,1804603682),V=E(V,q,j,K,x[F+13],D,4254626195),K=E(K,V,q,j,x[F+14],U,2792965006),j=E(j,K,V,q,x[F+15],X,1236535329),q=A(q,j,K,V,x[F+1],je,4129170786),V=A(V,q,j,K,x[F+6],Q,3225465664),K=A(K,V,q,j,x[F+11],W,643717713),j=A(j,K,V,q,x[F+0],B,3921069994),q=A(q,j,K,V,x[F+5],je,3593408605),V=A(V,q,j,K,x[F+10],Q,38016083),K=A(K,V,q,j,x[F+15],W,3634488961),j=A(j,K,V,q,x[F+4],B,3889429448),q=A(q,j,K,V,x[F+9],je,568446438),V=A(V,q,j,K,x[F+14],Q,3275163606),K=A(K,V,q,j,x[F+3],W,4107603335),j=A(j,K,V,q,x[F+8],B,1163531501),q=A(q,j,K,V,x[F+13],je,2850285829),V=A(V,q,j,K,x[F+2],Q,4243563512),K=A(K,V,q,j,x[F+7],W,1735328473),j=A(j,K,V,q,x[F+12],B,2368359562),q=R(q,j,K,V,x[F+5],ie,4294588738),V=R(V,q,j,K,x[F+8],ve,2272392833),K=R(K,V,q,j,x[F+11],Ie,1839030562),j=R(j,K,V,q,x[F+14],Pe,4259657740),q=R(q,j,K,V,x[F+1],ie,2763975236),V=R(V,q,j,K,x[F+4],ve,1272893353),K=R(K,V,q,j,x[F+7],Ie,4139469664),j=R(j,K,V,q,x[F+10],Pe,3200236656),q=R(q,j,K,V,x[F+13],ie,681279174),V=R(V,q,j,K,x[F+0],ve,3936430074),K=R(K,V,q,j,x[F+3],Ie,3572445317),j=R(j,K,V,q,x[F+6],Pe,76029189),q=R(q,j,K,V,x[F+9],ie,3654602809),V=R(V,q,j,K,x[F+12],ve,3873151461),K=R(K,V,q,j,x[F+15],Ie,530742520),j=R(j,K,V,q,x[F+2],Pe,3299628645),q=C(q,j,K,V,x[F+0],Re,4096336452),V=C(V,q,j,K,x[F+7],oe,1126891415),K=C(K,V,q,j,x[F+14],ye,2878612391),j=C(j,K,V,q,x[F+5],lt,4237533241),q=C(q,j,K,V,x[F+12],Re,1700485571),V=C(V,q,j,K,x[F+3],oe,2399980690),K=C(K,V,q,j,x[F+10],ye,4293915773),j=C(j,K,V,q,x[F+1],lt,2240044497),q=C(q,j,K,V,x[F+8],Re,1873313359),V=C(V,q,j,K,x[F+15],oe,4264355552),K=C(K,V,q,j,x[F+6],ye,2734768916),j=C(j,K,V,q,x[F+13],lt,1309151649),q=C(q,j,K,V,x[F+4],Re,4149444226),V=C(V,q,j,K,x[F+11],oe,3174756917),K=C(K,V,q,j,x[F+2],ye,718787259),j=C(j,K,V,q,x[F+9],lt,3951481745),q=d(q,_e),j=d(j,pe),K=d(K,P),V=d(V,N);return(k(q)+k(j)+k(K)+k(V)).toLowerCase()},et.closeMediaStream=r=>{if(r)try{let _;if(r.getTracks){_=r.getTracks();for(const d of _)d.stop()}else{_=r.getAudioTracks();for(const d of _)d.stop();_=r.getVideoTracks();for(const d of _)d.stop()}}catch{(typeof r.stop=="function"||typeof r.stop=="object")&&r.stop()}},et.cloneArray=r=>r&&r.slice()||[],et.cloneObject=(r,_={})=>r&&Object.assign({},r)||_,et}const Of=Nt,Rm=ot,gt=De,it=mt(),Df=Ba(),bm=Yt(),Ka=new Rm("SIPMessage");class ro{constructor(t,n,o,a,s,r){if(!t||!n||!o)return null;a=a||{},this.ua=o,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):o.configuration.use_preloaded_route&&this.setHeader("route",`<${o.transport.sip_uri};lr>`),this.setHeader("via",""),this.setHeader("max-forwards",gt.MAX_FORWARDS);const _=a.to_uri||n,d=a.to_tag?{tag:a.to_tag}:null,h=typeof a.to_display_name<"u"?a.to_display_name:null;this.to=new Df(_,h,d),this.setHeader("to",this.to.toString());const g=a.from_uri||o.configuration.uri,T={tag:a.from_tag||it.newTag()};let S;typeof a.from_display_name<"u"?S=a.from_display_name:o.configuration.display_name?S=o.configuration.display_name:S=null,this.from=new Df(g,S,T),this.setHeader("from",this.from.toString());const E=a.call_id||o.configuration.jssip_id+it.createRandomToken(15);this.call_id=E,this.setHeader("call-id",E);const A=a.cseq||Math.floor(Math.random()*1e4);this.cseq=A,this.setHeader("cseq",`${A} ${t}`)}setHeader(t,n){const o=new RegExp(`^\\s*${t}\\s*:`,"i");for(let a=0;a<this.extraHeaders.length;a++)o.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 o=new RegExp(`^\\s*${t}\\s*:`,"i");for(const a of this.extraHeaders)if(o.test(a))return a.substring(a.indexOf(":")+1).trim()}}getHeaders(t){const n=this.headers[it.headerize(t)],o=[];if(n){for(const a of n)o.push(a);return o}else{const a=new RegExp(`^\\s*${t}\\s*:`,"i");for(const s of this.extraHeaders)a.test(s)&&o.push(s.substring(s.indexOf(":")+1).trim());return o}}hasHeader(t){if(this.headers[it.headerize(t)])return!0;{const n=new RegExp(`^\\s*${t}\\s*:`,"i");for(const o of this.extraHeaders)if(n.test(o))return!0}return!1}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=Of.parse(this.body||""),this.sdp)}toString(){let t=`${this.method} ${this.ruri} SIP/2.0\r
74
+ `,s+=2):(i=null,d('"\\r\\n"')),i}function m(){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=C(),i===null&&(i=H()),i}function A(){var i;return/^[\0-\xFF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\0-\\xFF]")),i}function R(){var i;return/^["]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d('["]')),i}function C(){var i;return n.charCodeAt(s)===32?(i=" ",s++):(i=null,d('" "')),i}function H(){var i;return n.charCodeAt(s)===9?(i=" ",s++):(i=null,d('"\\t"')),i}function k(){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 re(){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=k(),i===null&&(i=F()),i}function F(){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 _e(){var i,e,l,u,f;return u=s,f=s,n.charCodeAt(s)===37?(i="%",s++):(i=null,d('"%"')),i!==null?(e=S(),e!==null?(l=S(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){return g.join("")}(u,i)),i===null&&(s=u),i}function pe(){var i,e,l,u,f,p;for(u=s,f=s,p=s,i=[],e=E();e!==null;)i.push(e),e=E();if(i!==null?(e=h(),e!==null?i=[i,e]:(i=null,s=p)):(i=null,s=p),i=i!==null?i:"",i!==null){if(l=E(),l!==null)for(e=[];l!==null;)e.push(l),l=E();else e=null;e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i!==null&&(i=function(g){return" "}()),i===null&&(s=u),i}function P(){var i;return i=pe(),i=i!==null?i:"",i}function N(){var i,e,l,u,f;for(u=s,f=s,i=[],e=C(),e===null&&(e=H());e!==null;)i.push(e),e=C(),e===null&&(e=H());return i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u,f,p,g;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=[],g=s,l=[],u=pe();u!==null;)l.push(u),u=pe();for(l!==null?(u=j(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;){for(e.push(l),g=s,l=[],u=pe();u!==null;)l.push(u),u=pe();l!==null?(u=j(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g)}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=K()),i}function K(){var i;return/^[\x80-\uFFFF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\x80-\\uFFFF]")),i}function V(){var i;return/^[\x80-\xBF]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[\\x80-\\xBF]")),i}function z(){var i;return i=m(),i===null&&(/^[a-f]/.test(n.charAt(s))?(i=n.charAt(s),s++):(i=null,d("[a-f]"))),i}function D(){var i,e,l;if(l=s,e=k(),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=k(),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)}(l)),i===null&&(s=l),i}function U(){var i,e,l;if(l=s,e=k(),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=k(),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)}(l)),i===null&&(s=l),i}function X(){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=R(),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=C(),i===null&&(i=H())))))))))))))))))),i}function je(){var i,e,l;if(l=s,e=k(),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=R(),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=k(),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=R(),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)}(l)),i===null&&(s=l),i}function Q(){var i,e,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===42?(e="*",s++):(e=null,d('"*"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===47?(e="/",s++):(e=null,d('"/"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"/"}()),i===null&&(s=u),i}function B(){var i,e,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===40?(e="(",s++):(e=null,d('"("')),e!==null?(l=P(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return"("}()),i===null&&(s=u),i}function ve(){var i,e,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===41?(e=")",s++):(e=null,d('")"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u;return l=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=l),i}function Pe(){var i,e,l,u;return l=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=l),i}function Re(){var i,e,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===44?(e=",",s++):(e=null,d('","')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===59?(e=";",s++):(e=null,d('";"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(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,l,u,f;return u=s,f=s,i=P(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=P(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return":"}()),i===null&&(s=u),i}function lt(){var i,e,l,u;return l=s,u=s,i=P(),i!==null?(e=R(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f){return'"'}()),i===null&&(s=l),i}function at(){var i,e,l,u;return l=s,u=s,i=R(),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=l),i}function Ee(){var i,e,l,u;if(u=s,i=ie(),i!==null){for(e=[],l=Ce(),l===null&&(l=he(),l===null&&(l=Ee()));l!==null;)e.push(l),l=Ce(),l===null&&(l=he(),l===null&&(l=Ee()));e!==null?(l=ve(),l!==null?i=[i,e,l]:(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=K(),i===null&&(i=pe())))),i}function be(){var i,e,l,u,f,p;if(f=s,p=s,i=P(),i!==null)if(e=R(),e!==null){for(l=[],u=me(),u===null&&(u=he());u!==null;)l.push(u),u=me(),u===null&&(u=he());l!==null?(u=R(),u!==null?i=[i,e,l,u]:(i=null,s=p)):(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(g){return n.substring(s,g)}(f)),i===null&&(s=f),i}function Oe(){var i,e,l,u,f,p;if(f=s,p=s,i=P(),i!==null)if(e=R(),e!==null){for(l=[],u=me(),u===null&&(u=he());u!==null;)l.push(u),u=me(),u===null&&(u=he());l!==null?(u=R(),u!==null?i=[i,e,l,u]:(i=null,s=p)):(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(g){var v=n.substring(s,g).trim();return v.substring(1,v.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(f)),i===null&&(s=f),i}function me(){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=K())))),i}function he(){var i,e,l;return l=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=l)):(i=null,s=l),i}function ge(){var i,e,l,u,f,p;return f=s,p=s,i=Ne(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Vt(),l=l!==null?l:"",l!==null?(u=un(),u!==null?i=[i,e,l,u]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i!==null&&(i=function(g){try{I.uri=new zo(I.scheme,I.user,I.host,I.port),delete I.scheme,delete I.user,delete I.host,delete I.host_type,delete I.port}catch{I=-1}}()),i===null&&(s=f),i}function we(){var i,e,l,u,f,p,g,v;return g=s,v=s,i=Ne(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Vt(),l=l!==null?l:"",l!==null?(u=un(),u!==null?(f=ai(),f!==null?(p=mi(),p=p!==null?p:"",p!==null?i=[i,e,l,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{I.uri=new zo(I.scheme,I.user,I.host,I.port,I.uri_params,I.uri_headers),delete I.scheme,delete I.user,delete I.host,delete I.host_type,delete I.port,delete I.uri_params,o==="SIP_URI"&&(I=I.uri)}catch{I=-1}}()),i===null&&(s=g),i}function Ne(){var i;return i=st(),i===null&&(i=He()),i}function st(){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(l,u){I.scheme=u.toLowerCase()}(e,i)),i===null&&(s=e),i}function He(){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(l,u){I.scheme=u.toLowerCase()}(e,i)),i===null&&(s=e),i}function Vt(){var i,e,l,u,f,p;return u=s,f=s,i=At(),i!==null?(p=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Bn(),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?(n.charCodeAt(s)===64?(l="@",s++):(l=null,d('"@"')),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(g){I.user=decodeURIComponent(n.substring(s-1,g))}(u)),i===null&&(s=u),i}function At(){var i,e;if(e=x(),e===null&&(e=_e(),e===null&&(e=qn())),e!==null)for(i=[];e!==null;)i.push(e),e=x(),e===null&&(e=_e(),e===null&&(e=qn()));else i=null;return i}function qn(){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 Bn(){var i,e,l;for(l=s,i=[],e=x(),e===null&&(e=_e(),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=_e(),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){I.password=n.substring(s,u)}(l)),i===null&&(s=l),i}function un(){var i,e,l,u,f;return u=s,i=ls(),i!==null?(f=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=$s(),l!==null?e=[e,l]:(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 ls(){var i,e;return e=s,i=Cs(),i===null&&(i=ut(),i===null&&(i=Wn())),i!==null&&(i=function(l){return I.host=n.substring(s,l).toLowerCase(),I.host}(e)),i===null&&(s=e),i}function Cs(){var i,e,l,u,f,p;for(u=s,f=s,i=[],p=s,e=cn(),e!==null?(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p);e!==null;)i.push(e),p=s,e=cn(),e!==null?(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l!==null?e=[e,l]:(e=null,s=p)):(e=null,s=p);return i!==null?(e=Gn(),e!==null?(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l=l!==null?l:"",l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(g){return I.host_type="domain",n.substring(s,g)}(u)),i===null&&(s=u),i}function cn(){var i,e,l,u;if(u=s,i=k(),i!==null){for(e=[],l=k(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,d('"_"'))));l!==null;)e.push(l),l=k(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,d('"_"'))));e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function Gn(){var i,e,l,u;if(u=s,i=T(),i!==null){for(e=[],l=k(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,d('"_"'))));l!==null;)e.push(l),l=k(),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===95?(l="_",s++):(l=null,d('"_"'))));e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function Wn(){var i,e,l,u,f;return u=s,f=s,n.charCodeAt(s)===91?(i="[",s++):(i=null,d('"["')),i!==null?(e=fn(),e!==null?(n.charCodeAt(s)===93?(l="]",s++):(l=null,d('"]"')),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p){return I.host_type="IPv6",n.substring(s,p)}(u)),i===null&&(s=u),i}function fn(){var i,e,l,u,f,p,g,v,y,O,le,xe,Dt,Js,L,b;return Js=s,L=s,i=Te(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==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?(g=Te(),g!==null?(n.charCodeAt(s)===58?(v=":",s++):(v=null,d('":"')),v!==null?(y=Te(),y!==null?(n.charCodeAt(s)===58?(O=":",s++):(O=null,d('":"')),O!==null?(le=Te(),le!==null?(n.charCodeAt(s)===58?(xe=":",s++):(xe=null,d('":"')),xe!==null?(Dt=ae(),Dt!==null?i=[i,e,l,u,f,p,g,v,y,O,le,xe,Dt]:(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?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(n.charCodeAt(s)===58?(g=":",s++):(g=null,d('":"')),g!==null?(v=Te(),v!==null?(n.charCodeAt(s)===58?(y=":",s++):(y=null,d('":"')),y!==null?(O=Te(),O!==null?(n.charCodeAt(s)===58?(le=":",s++):(le=null,d('":"')),le!==null?(xe=ae(),xe!==null?i=[i,e,l,u,f,p,g,v,y,O,le,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?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(n.charCodeAt(s)===58?(g=":",s++):(g=null,d('":"')),g!==null?(v=Te(),v!==null?(n.charCodeAt(s)===58?(y=":",s++):(y=null,d('":"')),y!==null?(O=ae(),O!==null?i=[i,e,l,u,f,p,g,v,y,O]:(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?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(n.charCodeAt(s)===58?(g=":",s++):(g=null,d('":"')),g!==null?(v=ae(),v!==null?i=[i,e,l,u,f,p,g,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?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=ae(),p!==null?i=[i,e,l,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?(l=":",s++):(l=null,d('":"')),l!==null?(u=ae(),u!==null?i=[i,e,l,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?(l=Te(),l!==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?(g=Te(),g!==null?(n.charCodeAt(s)===58?(v=":",s++):(v=null,d('":"')),v!==null?(y=Te(),y!==null?(n.charCodeAt(s)===58?(O=":",s++):(O=null,d('":"')),O!==null?(le=ae(),le!==null?i=[i,e,l,u,f,p,g,v,y,O,le]:(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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(n.substr(s,2)==="::"?(l="::",s+=2):(l=null,d('"::"')),l!==null?(u=Te(),u!==null?(n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?(n.charCodeAt(s)===58?(g=":",s++):(g=null,d('":"')),g!==null?(v=Te(),v!==null?(n.charCodeAt(s)===58?(y=":",s++):(y=null,d('":"')),y!==null?(O=ae(),O!==null?i=[i,e,l,u,f,p,g,v,y,O]:(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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==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?(g=Te(),g!==null?(n.charCodeAt(s)===58?(v=":",s++):(v=null,d('":"')),v!==null?(y=ae(),y!==null?i=[i,e,l,u,f,p,g,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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==null?(b=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=b)):(u=null,s=b),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?(g=":",s++):(g=null,d('":"')),g!==null?(v=ae(),v!==null?i=[i,e,l,u,f,p,g,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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==null?(b=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=b)):(u=null,s=b),u=u!==null?u:"",u!==null?(b=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,s=b)):(f=null,s=b),f=f!==null?f:"",f!==null?(n.substr(s,2)==="::"?(p="::",s+=2):(p=null,d('"::"')),p!==null?(g=ae(),g!==null?i=[i,e,l,u,f,p,g]:(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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==null?(b=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=b)):(u=null,s=b),u=u!==null?u:"",u!==null?(b=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,s=b)):(f=null,s=b),f=f!==null?f:"",f!==null?(b=s,n.charCodeAt(s)===58?(p=":",s++):(p=null,d('":"')),p!==null?(g=Te(),g!==null?p=[p,g]:(p=null,s=b)):(p=null,s=b),p=p!==null?p:"",p!==null?(n.substr(s,2)==="::"?(g="::",s+=2):(g=null,d('"::"')),g!==null?(v=Te(),v!==null?i=[i,e,l,u,f,p,g,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?(b=s,n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?e=[e,l]:(e=null,s=b)):(e=null,s=b),e=e!==null?e:"",e!==null?(b=s,n.charCodeAt(s)===58?(l=":",s++):(l=null,d('":"')),l!==null?(u=Te(),u!==null?l=[l,u]:(l=null,s=b)):(l=null,s=b),l=l!==null?l:"",l!==null?(b=s,n.charCodeAt(s)===58?(u=":",s++):(u=null,d('":"')),u!==null?(f=Te(),f!==null?u=[u,f]:(u=null,s=b)):(u=null,s=b),u=u!==null?u:"",u!==null?(b=s,n.charCodeAt(s)===58?(f=":",s++):(f=null,d('":"')),f!==null?(p=Te(),p!==null?f=[f,p]:(f=null,s=b)):(f=null,s=b),f=f!==null?f:"",f!==null?(b=s,n.charCodeAt(s)===58?(p=":",s++):(p=null,d('":"')),p!==null?(g=Te(),g!==null?p=[p,g]:(p=null,s=b)):(p=null,s=b),p=p!==null?p:"",p!==null?(b=s,n.charCodeAt(s)===58?(g=":",s++):(g=null,d('":"')),g!==null?(v=Te(),v!==null?g=[g,v]:(g=null,s=b)):(g=null,s=b),g=g!==null?g:"",g!==null?(n.substr(s,2)==="::"?(v="::",s+=2):(v=null,d('"::"')),v!==null?i=[i,e,l,u,f,p,g,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 I.host_type="IPv6",n.substring(s,Se)}(Js)),i===null&&(s=Js),i}function Te(){var i,e,l,u,f;return f=s,i=S(),i!==null?(e=S(),e=e!==null?e:"",e!==null?(l=S(),l=l!==null?l:"",l!==null?(u=S(),u=u!==null?u:"",u!==null?i=[i,e,l,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function ae(){var i,e,l,u;return u=s,i=Te(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=Te(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i===null&&(i=ut()),i}function ut(){var i,e,l,u,f,p,g,v,y;return v=s,y=s,i=Zt(),i!==null?(n.charCodeAt(s)===46?(e=".",s++):(e=null,d('"."')),e!==null?(l=Zt(),l!==null?(n.charCodeAt(s)===46?(u=".",s++):(u=null,d('"."')),u!==null?(f=Zt(),f!==null?(n.charCodeAt(s)===46?(p=".",s++):(p=null,d('"."')),p!==null?(g=Zt(),g!==null?i=[i,e,l,u,f,p,g]:(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(O){return I.host_type="IPv4",n.substring(s,O)}(v)),i===null&&(s=v),i}function Zt(){var i,e,l,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?(l=m(),l!==null?i=[i,e,l]:(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=m(),e!==null?(l=m(),l!==null?i=[i,e,l]:(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=m(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i===null&&(i=m())))),i}function $s(){var i,e,l,u,f,p,g;return p=s,g=s,i=m(),i=i!==null?i:"",i!==null?(e=m(),e=e!==null?e:"",e!==null?(l=m(),l=l!==null?l:"",l!==null?(u=m(),u=u!==null?u:"",u!==null?(f=m(),f=f!==null?f:"",f!==null?i=[i,e,l,u,f]:(i=null,s=g)):(i=null,s=g)):(i=null,s=g)):(i=null,s=g)):(i=null,s=g),i!==null&&(i=function(v,y){return y=parseInt(y.join("")),I.port=y,y}(p,i)),i===null&&(s=p),i}function ai(){var i,e,l,u;for(i=[],u=s,n.charCodeAt(s)===59?(e=";",s++):(e=null,d('";"')),e!==null?(l=Kn(),l!==null?e=[e,l]:(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?(l=Kn(),l!==null?e=[e,l]:(e=null,s=u)):(e=null,s=u);return i}function Kn(){var i;return i=Yn(),i===null&&(i=ui(),i===null&&(i=ci(),i===null&&(i=fi(),i===null&&(i=di(),i===null&&(i=hi(),i===null&&(i=_i())))))),i}function Yn(){var i,e,l,u;return l=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=D())))),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.uri_params||(I.uri_params={}),I.uri_params.transport=p.toLowerCase()}(l,i[1])),i===null&&(s=l),i}function ui(){var i,e,l,u;return l=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=D())),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.uri_params||(I.uri_params={}),I.uri_params.user=p.toLowerCase()}(l,i[1])),i===null&&(s=l),i}function ci(){var i,e,l,u;return l=s,u=s,n.substr(s,7).toLowerCase()==="method="?(i=n.substr(s,7),s+=7):(i=null,d('"method="')),i!==null?(e=Tn(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.uri_params||(I.uri_params={}),I.uri_params.method=p}(l,i[1])),i===null&&(s=l),i}function fi(){var i,e,l,u;return l=s,u=s,n.substr(s,4).toLowerCase()==="ttl="?(i=n.substr(s,4),s+=4):(i=null,d('"ttl="')),i!==null?(e=gr(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.params||(I.params={}),I.params.ttl=p}(l,i[1])),i===null&&(s=l),i}function di(){var i,e,l,u;return l=s,u=s,n.substr(s,6).toLowerCase()==="maddr="?(i=n.substr(s,6),s+=6):(i=null,d('"maddr="')),i!==null?(e=ls(),e!==null?i=[i,e]:(i=null,s=u)):(i=null,s=u),i!==null&&(i=function(f,p){I.uri_params||(I.uri_params={}),I.uri_params.maddr=p}(l,i[1])),i===null&&(s=l),i}function hi(){var i,e,l,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?(l=D(),l!==null?e=[e,l]:(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(g){I.uri_params||(I.uri_params={}),I.uri_params.lr=void 0}()),i===null&&(s=u),i}function _i(){var i,e,l,u,f,p;return u=s,f=s,i=pi(),i!==null?(p=s,n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(l=gi(),l!==null?e=[e,l]:(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(g,v,y){I.uri_params||(I.uri_params={}),typeof y>"u"?y=void 0:y=y[1],I.uri_params[v.toLowerCase()]=y}(u,i[0],i[1])),i===null&&(s=u),i}function pi(){var i,e,l;if(l=s,e=Hs(),e!==null)for(i=[];e!==null;)i.push(e),e=Hs();else i=null;return i!==null&&(i=function(u,f){return f.join("")}(l,i)),i===null&&(s=l),i}function gi(){var i,e,l;if(l=s,e=Hs(),e!==null)for(i=[];e!==null;)i.push(e),e=Hs();else i=null;return i!==null&&(i=function(u,f){return f.join("")}(l,i)),i===null&&(s=l),i}function Hs(){var i;return i=Fs(),i===null&&(i=x(),i===null&&(i=_e())),i}function Fs(){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 mi(){var i,e,l,u,f,p,g;if(p=s,n.charCodeAt(s)===63?(i="?",s++):(i=null,d('"?"')),i!==null)if(e=dn(),e!==null){for(l=[],g=s,n.charCodeAt(s)===38?(u="&",s++):(u=null,d('"&"')),u!==null?(f=dn(),f!==null?u=[u,f]:(u=null,s=g)):(u=null,s=g);u!==null;)l.push(u),g=s,n.charCodeAt(s)===38?(u="&",s++):(u=null,d('"&"')),u!==null?(f=dn(),f!==null?u=[u,f]:(u=null,s=g)):(u=null,s=g);l!==null?i=[i,e,l]:(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i}function dn(){var i,e,l,u,f;return u=s,f=s,i=hn(),i!==null?(n.charCodeAt(s)===61?(e="=",s++):(e=null,d('"="')),e!==null?(l=Ti(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g,v){g=g.join("").toLowerCase(),v=v.join(""),I.uri_headers||(I.uri_headers={}),I.uri_headers[g]?I.uri_headers[g].push(v):I.uri_headers[g]=[v]}(u,i[0],i[2])),i===null&&(s=u),i}function hn(){var i,e;if(e=Vs(),e===null&&(e=x(),e===null&&(e=_e())),e!==null)for(i=[];e!==null;)i.push(e),e=Vs(),e===null&&(e=x(),e===null&&(e=_e()));else i=null;return i}function Ti(){var i,e;for(i=[],e=Vs(),e===null&&(e=x(),e===null&&(e=_e()));e!==null;)i.push(e),e=Vs(),e===null&&(e=x(),e===null&&(e=_e()));return i}function Vs(){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 _n(){var i;return i=vn(),i===null&&(i=Do()),i}function Do(){var i,e,l,u,f,p;return p=s,i=Tn(),i!==null?(e=C(),e!==null?(l=vi(),l!==null?(u=C(),u!==null?(f=Xn(),f!==null?i=[i,e,l,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function vi(){var i;return i=we(),i===null&&(i=Jn()),i}function Jn(){var i,e,l,u;return u=s,i=Gs(),i!==null?(n.charCodeAt(s)===58?(e=":",s++):(e=null,d('":"')),e!==null?(l=zn(),l===null&&(l=gn()),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function zn(){var i,e,l,u,f;return u=s,i=Si(),i===null&&(i=pn()),i!==null?(f=s,n.charCodeAt(s)===63?(e="?",s++):(e=null,d('"?"')),e!==null?(l=Ri(),l!==null?e=[e,l]:(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 Si(){var i,e,l,u;return u=s,n.substr(s,2)==="//"?(i="//",s+=2):(i=null,d('"//"')),i!==null?(e=yi(),e!==null?(l=pn(),l=l!==null?l:"",l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function pn(){var i,e,l;return l=s,n.charCodeAt(s)===47?(i="/",s++):(i=null,d('"/"')),i!==null?(e=Ei(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function gn(){var i,e,l,u;if(u=s,i=qs(),i!==null){for(e=[],l=js();l!==null;)e.push(l),l=js();e!==null?i=[i,e]:(i=null,s=u)}else i=null,s=u;return i}function js(){var i;return i=re(),i===null&&(i=x(),i===null&&(i=_e())),i}function qs(){var i;return i=x(),i===null&&(i=_e(),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 Ei(){var i,e,l,u,f,p;if(f=s,i=mn(),i!==null){for(e=[],p=s,n.charCodeAt(s)===47?(l="/",s++):(l=null,d('"/"')),l!==null?(u=mn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,n.charCodeAt(s)===47?(l="/",s++):(l=null,d('"/"')),l!==null?(u=mn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function mn(){var i,e,l,u,f,p;for(f=s,i=[],e=As();e!==null;)i.push(e),e=As();if(i!==null){for(e=[],p=s,n.charCodeAt(s)===59?(l=";",s++):(l=null,d('";"')),l!==null?(u=Bs(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,n.charCodeAt(s)===59?(l=";",s++):(l=null,d('";"')),l!==null?(u=Bs(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Bs(){var i,e;for(i=[],e=As();e!==null;)i.push(e),e=As();return i}function As(){var i;return i=x(),i===null&&(i=_e(),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 Gs(){var i,e,l,u,f;if(u=s,f=s,i=T(),i!==null){for(e=[],l=T(),l===null&&(l=m(),l===null&&(n.charCodeAt(s)===43?(l="+",s++):(l=null,d('"+"')),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."'))))));l!==null;)e.push(l),l=T(),l===null&&(l=m(),l===null&&(n.charCodeAt(s)===43?(l="+",s++):(l=null,d('"+"')),l===null&&(n.charCodeAt(s)===45?(l="-",s++):(l=null,d('"-"')),l===null&&(n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."'))))));e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i!==null&&(i=function(p){I.scheme=n.substring(s,p)}(u)),i===null&&(s=u),i}function yi(){var i;return i=Ci(),i===null&&(i=Ai()),i}function Ci(){var i,e,l,u;return l=s,u=s,i=Vt(),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=un(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i=i!==null?i:"",i}function Ai(){var i,e;if(e=x(),e===null&&(e=_e(),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=_e(),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 Ri(){var i,e;for(i=[],e=js();e!==null;)i.push(e),e=js();return i}function Xn(){var i,e,l,u,f,p,g,v;if(g=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=m(),u!==null)for(l=[];u!==null;)l.push(u),u=m();else l=null;if(l!==null)if(n.charCodeAt(s)===46?(u=".",s++):(u=null,d('"."')),u!==null){if(p=m(),p!==null)for(f=[];p!==null;)f.push(p),p=m();else f=null;f!==null?i=[i,e,l,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){I.sip_version=n.substring(s,y)}(g)),i===null&&(s=g),i}function Qn(){var i;return n.substr(s,6)==="INVITE"?(i="INVITE",s+=6):(i=null,d('"INVITE"')),i}function bi(){var i;return n.substr(s,3)==="ACK"?(i="ACK",s+=3):(i=null,d('"ACK"')),i}function Ii(){var i;return n.substr(s,7)==="OPTIONS"?(i="OPTIONS",s+=7):(i=null,d('"OPTIONS"')),i}function wi(){var i;return n.substr(s,3)==="BYE"?(i="BYE",s+=3):(i=null,d('"BYE"')),i}function Oi(){var i;return n.substr(s,6)==="CANCEL"?(i="CANCEL",s+=6):(i=null,d('"CANCEL"')),i}function Di(){var i;return n.substr(s,8)==="REGISTER"?(i="REGISTER",s+=8):(i=null,d('"REGISTER"')),i}function Ni(){var i;return n.substr(s,9)==="SUBSCRIBE"?(i="SUBSCRIBE",s+=9):(i=null,d('"SUBSCRIBE"')),i}function xi(){var i;return n.substr(s,6)==="NOTIFY"?(i="NOTIFY",s+=6):(i=null,d('"NOTIFY"')),i}function Ui(){var i;return n.substr(s,5)==="REFER"?(i="REFER",s+=5):(i=null,d('"REFER"')),i}function Tn(){var i,e;return e=s,i=Qn(),i===null&&(i=bi(),i===null&&(i=Ii(),i===null&&(i=wi(),i===null&&(i=Oi(),i===null&&(i=Di(),i===null&&(i=Ni(),i===null&&(i=xi(),i===null&&(i=Ui(),i===null&&(i=D()))))))))),i!==null&&(i=function(l){return I.method=n.substring(s,l),I.method}(e)),i===null&&(s=e),i}function vn(){var i,e,l,u,f,p;return p=s,i=Xn(),i!==null?(e=C(),e!==null?(l=ki(),l!==null?(u=C(),u!==null?(f=Mi(),f!==null?i=[i,e,l,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function ki(){var i,e;return e=s,i=Pi(),i!==null&&(i=function(l,u){I.status_code=parseInt(u.join(""))}(e,i)),i===null&&(s=e),i}function Pi(){var i,e,l,u;return u=s,i=m(),i!==null?(e=m(),e!==null?(l=m(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Mi(){var i,e,l;for(l=s,i=[],e=re(),e===null&&(e=x(),e===null&&(e=_e(),e===null&&(e=K(),e===null&&(e=V(),e===null&&(e=C(),e===null&&(e=H()))))));e!==null;)i.push(e),e=re(),e===null&&(e=x(),e===null&&(e=_e(),e===null&&(e=K(),e===null&&(e=V(),e===null&&(e=C(),e===null&&(e=H()))))));return i!==null&&(i=function(u){I.reason_phrase=n.substring(s,u)}(l)),i===null&&(s=l),i}function No(){var i,e,l,u,f,p;if(f=s,i=yn(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=yn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=yn(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Nu(){var i,e,l,u,f,p;return u=s,f=s,i=je(),i!==null?(p=s,n.charCodeAt(s)===64?(e="@",s++):(e=null,d('"@"')),e!==null?(l=je(),l!==null?e=[e,l]:(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(g){I=n.substring(s,g)}(u)),i===null&&(s=u),i}function xu(){var i,e,l,u,f,p,g;if(f=s,i=Q(),i===null)if(p=s,i=Zn(),i!==null){for(e=[],g=s,l=Re(),l!==null?(u=Zn(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=Re(),l!==null?(u=Zn(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y,O;for(O=I.multi_header.length,y=0;y<O;y++)if(I.multi_header[y].parsed===null){I=null;break}I!==null?I=I.multi_header:I=-1}()),i===null&&(s=f),i}function Zn(){var i,e,l,u,f,p,g;if(f=s,p=s,i=ge(),i===null&&(i=jt()),i!==null){for(e=[],g=s,l=oe(),l!==null?(u=Ws(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=oe(),l!==null?(u=Ws(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y;I.multi_header||(I.multi_header=[]);try{y=new Rs(I.uri,I.display_name,I.params),delete I.uri,delete I.display_name,delete I.params}catch{y=null}I.multi_header.push({possition:s,offset:v,parsed:y})}(f)),i===null&&(s=f),i}function jt(){var i,e,l,u,f;return f=s,i=qt(),i=i!==null?i:"",i!==null?(e=Pe(),e!==null?(l=we(),l!==null?(u=Ie(),u!==null?i=[i,e,l,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function qt(){var i,e,l,u,f,p,g;if(f=s,p=s,i=D(),i!==null){for(e=[],g=s,l=pe(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=pe(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);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"?I.display_name=y:I.display_name=y[1].reduce(function(O,le){return O+le[0]+le[1]},y[0])}(f,i)),i===null&&(s=f),i}function Ws(){var i;return i=er(),i===null&&(i=Li(),i===null&&(i=ze())),i}function er(){var i,e,l,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=B(),e!==null?(l=as(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.params||(I.params={}),I.params.q=g}(u,i[2])),i===null&&(s=u),i}function Li(){var i,e,l,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=B(),e!==null?(l=os(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.params||(I.params={}),I.params.expires=g}(u,i[2])),i===null&&(s=u),i}function os(){var i,e,l;if(l=s,e=m(),e!==null)for(i=[];e!==null;)i.push(e),e=m();else i=null;return i!==null&&(i=function(u,f){return parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function as(){var i,e,l,u,f,p,g,v;return p=s,g=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?(l=m(),l=l!==null?l:"",l!==null?(u=m(),u=u!==null?u:"",u!==null?(f=m(),f=f!==null?f:"",f!==null?e=[e,l,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=g)):(i=null,s=g),i!==null&&(i=function(y){return parseFloat(n.substring(s,y))}(p)),i===null&&(s=p),i}function ze(){var i,e,l,u,f,p;return u=s,f=s,i=D(),i!==null?(p=s,e=B(),e!==null?(l=Xe(),l!==null?e=[e,l]:(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(g,v,y){I.params||(I.params={}),typeof y>"u"?y=void 0:y=y[1],I.params[v.toLowerCase()]=y}(u,i[0],i[1])),i===null&&(s=u),i}function Xe(){var i;return i=D(),i===null&&(i=ls(),i===null&&(i=be())),i}function xo(){var i,e,l,u,f,p;if(f=s,i=Uo(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=tr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=tr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Uo(){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=D())))),i}function tr(){var i;return i=sr(),i===null&&(i=ze()),i}function sr(){var i,e,l,u;return u=s,n.substr(s,8).toLowerCase()==="handling"?(i=n.substr(s,8),s+=8):(i=null,d('"handling"')),i!==null?(e=B(),e!==null?(n.substr(s,8).toLowerCase()==="optional"?(l=n.substr(s,8),s+=8):(l=null,d('"optional"')),l===null&&(n.substr(s,8).toLowerCase()==="required"?(l=n.substr(s,8),s+=8):(l=null,d('"required"')),l===null&&(l=D())),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function ko(){var i,e,l,u,f,p;if(f=s,i=D(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Uu(){var i,e,l;if(l=s,e=m(),e!==null)for(i=[];e!==null;)i.push(e),e=m();else i=null;return i!==null&&(i=function(u,f){I=parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function ku(){var i,e;return e=s,i=Po(),i!==null&&(i=function(l){I=n.substring(s,l)}(e)),i===null&&(s=e),i}function Po(){var i,e,l,u,f,p,g,v;if(g=s,i=$i(),i!==null)if(e=W(),e!==null)if(l=Vi(),l!==null){for(u=[],v=s,f=oe(),f!==null?(p=nr(),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=nr(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=g)}else i=null,s=g;else i=null,s=g;else i=null,s=g;return i}function $i(){var i;return i=Hi(),i===null&&(i=Fi()),i}function Hi(){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=Sn()))))),i}function Fi(){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=Sn())),i}function Sn(){var i;return i=D(),i===null&&(i=En()),i}function En(){var i,e,l;return l=s,n.substr(s,2).toLowerCase()==="x-"?(i=n.substr(s,2),s+=2):(i=null,d('"x-"')),i!==null?(e=D(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function Vi(){var i;return i=Sn(),i===null&&(i=D()),i}function nr(){var i,e,l,u;return u=s,i=D(),i!==null?(e=B(),e!==null?(l=rr(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function rr(){var i;return i=D(),i===null&&(i=be()),i}function Mo(){var i,e,l,u;return u=s,i=Lo(),i!==null?(e=pe(),e!==null?(l=Tn(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Lo(){var i,e,l;if(l=s,e=m(),e!==null)for(i=[];e!==null;)i.push(e),e=m();else i=null;return i!==null&&(i=function(u,f){I.value=parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function $o(){var i,e;return e=s,i=os(),i!==null&&(i=function(l,u){I=u}(e,i)),i===null&&(s=e),i}function Pu(){var i,e,l,u,f,p,g;if(f=s,p=s,i=yn(),i!==null){for(e=[],g=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v,y){I.event=y.join("").toLowerCase()}(f,i[0])),i===null&&(s=f),i}function yn(){var i,e,l,u,f,p;if(f=s,i=U(),i!==null){for(e=[],p=s,n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,n.charCodeAt(s)===46?(l=".",s++):(l=null,d('"."')),l!==null?(u=U(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Cn(){var i,e,l,u,f,p,g;if(f=s,p=s,i=ge(),i===null&&(i=jt()),i!==null){for(e=[],g=s,l=oe(),l!==null?(u=ji(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=oe(),l!==null?(u=ji(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y=I.tag;try{I=new Rs(I.uri,I.display_name,I.params),y&&I.setParam("tag",y)}catch{I=-1}}()),i===null&&(s=f),i}function ji(){var i;return i=An(),i===null&&(i=ze()),i}function An(){var i,e,l,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=B(),e!==null?(l=D(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.tag=g}(u,i[2])),i===null&&(s=u),i}function qi(){var i,e,l;if(l=s,e=m(),e!==null)for(i=[];e!==null;)i.push(e),e=m();else i=null;return i!==null&&(i=function(u,f){I=parseInt(f.join(""))}(l,i)),i===null&&(s=l),i}function Mu(){var i,e;return e=s,i=os(),i!==null&&(i=function(l,u){I=u}(e,i)),i===null&&(s=e),i}function Lu(){var i,e,l,u,f,p,g,v,y,O;for(v=s,y=s,i=[],e=qt();e!==null;)i.push(e),e=qt();if(i!==null)if(e=Pe(),e!==null)if(l=we(),l!==null)if(u=Ie(),u!==null){for(f=[],O=s,p=oe(),p!==null?(g=ze(),g!==null?p=[p,g]:(p=null,s=O)):(p=null,s=O);p!==null;)f.push(p),O=s,p=oe(),p!==null?(g=ze(),g!==null?p=[p,g]:(p=null,s=O)):(p=null,s=O);f!==null?i=[i,e,l,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(le){try{I=new Rs(I.uri,I.display_name,I.params)}catch{I=-1}}()),i===null&&(s=v),i}function $u(){var i;return i=Bi(),i}function Bi(){var i,e,l,u,f,p,g,v;if(g=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(l=us(),l!==null){for(u=[],v=s,f=Re(),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=Re(),f!==null?(p=us(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=g)}else i=null,s=g;else i=null,s=g;else i=null,s=g;return i===null&&(i=ir()),i}function ir(){var i,e,l,u,f,p,g,v;if(g=s,i=D(),i!==null)if(e=pe(),e!==null)if(l=Ks(),l!==null){for(u=[],v=s,f=Re(),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=Re(),f!==null?(p=Ks(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=g)}else i=null,s=g;else i=null,s=g;else i=null,s=g;return i}function Ks(){var i,e,l,u;return u=s,i=D(),i!==null?(e=B(),e!==null?(l=D(),l===null&&(l=be()),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function us(){var i;return i=Rn(),i===null&&(i=Wi(),i===null&&(i=In(),i===null&&(i=Yi(),i===null&&(i=Ji(),i===null&&(i=zi(),i===null&&(i=Xi(),i===null&&(i=Ks()))))))),i}function Rn(){var i,e,l,u;return u=s,n.substr(s,5).toLowerCase()==="realm"?(i=n.substr(s,5),s+=5):(i=null,d('"realm"')),i!==null?(e=B(),e!==null?(l=Gi(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Gi(){var i,e;return e=s,i=Oe(),i!==null&&(i=function(l,u){I.realm=u}(e,i)),i===null&&(s=e),i}function Wi(){var i,e,l,u,f,p,g,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=B(),e!==null)if(l=lt(),l!==null)if(u=bn(),u!==null){if(f=[],y=s,g=C(),g!==null)for(p=[];g!==null;)p.push(g),g=C();else p=null;for(p!==null?(g=bn(),g!==null?p=[p,g]:(p=null,s=y)):(p=null,s=y);p!==null;){if(f.push(p),y=s,g=C(),g!==null)for(p=[];g!==null;)p.push(g),g=C();else p=null;p!==null?(g=bn(),g!==null?p=[p,g]:(p=null,s=y)):(p=null,s=y)}f!==null?(p=at(),p!==null?i=[i,e,l,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 bn(){var i;return i=Jn(),i===null&&(i=pn()),i}function In(){var i,e,l,u;return u=s,n.substr(s,5).toLowerCase()==="nonce"?(i=n.substr(s,5),s+=5):(i=null,d('"nonce"')),i!==null?(e=B(),e!==null?(l=Ki(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Ki(){var i,e;return e=s,i=Oe(),i!==null&&(i=function(l,u){I.nonce=u}(e,i)),i===null&&(s=e),i}function Yi(){var i,e,l,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=B(),e!==null?(l=Oe(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.opaque=g}(u,i[2])),i===null&&(s=u),i}function Ji(){var i,e,l,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=B(),e!==null?(f=s,n.substr(s,4).toLowerCase()==="true"?(l=n.substr(s,4),s+=4):(l=null,d('"true"')),l!==null&&(l=function(p){I.stale=!0}()),l===null&&(s=f),l===null&&(f=s,n.substr(s,5).toLowerCase()==="false"?(l=n.substr(s,5),s+=5):(l=null,d('"false"')),l!==null&&(l=function(p){I.stale=!1}()),l===null&&(s=f)),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function zi(){var i,e,l,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=B(),e!==null?(n.substr(s,3).toLowerCase()==="md5"?(l=n.substr(s,3),s+=3):(l=null,d('"MD5"')),l===null&&(n.substr(s,8).toLowerCase()==="md5-sess"?(l=n.substr(s,8),s+=8):(l=null,d('"MD5-sess"')),l===null&&(l=D())),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.algorithm=g.toUpperCase()}(u,i[2])),i===null&&(s=u),i}function Xi(){var i,e,l,u,f,p,g,v,y,O;if(v=s,n.substr(s,3).toLowerCase()==="qop"?(i=n.substr(s,3),s+=3):(i=null,d('"qop"')),i!==null)if(e=B(),e!==null)if(l=lt(),l!==null){if(y=s,u=wn(),u!==null){for(f=[],O=s,n.charCodeAt(s)===44?(p=",",s++):(p=null,d('","')),p!==null?(g=wn(),g!==null?p=[p,g]:(p=null,s=O)):(p=null,s=O);p!==null;)f.push(p),O=s,n.charCodeAt(s)===44?(p=",",s++):(p=null,d('","')),p!==null?(g=wn(),g!==null?p=[p,g]:(p=null,s=O)):(p=null,s=O);f!==null?u=[u,f]:(u=null,s=y)}else u=null,s=y;u!==null?(f=at(),f!==null?i=[i,e,l,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 wn(){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=D())),i!==null&&(i=function(l,u){I.qop||(I.qop=[]),I.qop.push(u.toLowerCase())}(e,i)),i===null&&(s=e),i}function lr(){var i,e,l,u,f,p;if(f=s,i=D(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Hu(){var i,e,l,u,f,p,g;if(f=s,p=s,i=or(),i!==null){for(e=[],g=s,l=Re(),l!==null?(u=or(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=Re(),l!==null?(u=or(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y,O;for(O=I.multi_header.length,y=0;y<O;y++)if(I.multi_header[y].parsed===null){I=null;break}I!==null?I=I.multi_header:I=-1}()),i===null&&(s=f),i}function or(){var i,e,l,u,f,p,g;if(f=s,p=s,i=jt(),i!==null){for(e=[],g=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y;I.multi_header||(I.multi_header=[]);try{y=new Rs(I.uri,I.display_name,I.params),delete I.uri,delete I.display_name,delete I.params}catch{y=null}I.multi_header.push({possition:s,offset:v,parsed:y})}(f)),i===null&&(s=f),i}function ar(){var i,e,l,u,f,p,g;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=D()),i!==null){for(e=[],g=s,l=oe(),l!==null?(u=Qi(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=oe(),l!==null?(u=Qi(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v,y){if(I.protocol=y.toLowerCase(),I.params||(I.params={}),I.params.text&&I.params.text[0]==='"'){var O=I.params.text;I.text=O.substring(1,O.length-1),delete I.params.text}}(f,i[0])),i===null&&(s=f),i}function Qi(){var i;return i=ur(),i===null&&(i=ze()),i}function ur(){var i,e,l,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=B(),e!==null){if(u=m(),u!==null)for(l=[];u!==null;)l.push(u),u=m();else l=null;l!==null?i=[i,e,l]:(i=null,s=p)}else i=null,s=p;else i=null,s=p;return i!==null&&(i=function(g,v){I.cause=parseInt(v.join(""))}(f,i[2])),i===null&&(s=f),i}function Ho(){var i,e,l,u,f,p;if(f=s,i=D(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Fu(){var i,e,l,u,f,p;if(f=s,i=cr(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=cr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=cr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function cr(){var i,e,l,u,f,p;if(f=s,i=jt(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function fr(){var i,e,l,u,f,p;if(f=s,i=Fo(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=dr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=dr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Fo(){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=D()))),i!==null&&(i=function(l){I.state=n.substring(s,l)}(e)),i===null&&(s=e),i}function dr(){var i,e,l,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=B(),e!==null?(l=hr(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){typeof g<"u"&&(I.reason=g)}(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=B(),e!==null?(l=os(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){typeof g<"u"&&(I.expires=g)}(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=B(),e!==null?(l=os(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){typeof g<"u"&&(I.retry_after=g)}(u,i[2])),i===null&&(s=u),i===null&&(i=ze()))),i}function hr(){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=D()))))))),i}function Vo(){var i;return i=q(),i=i!==null?i:"",i}function Vu(){var i,e,l,u,f,p;if(f=s,i=D(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=D(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i=i!==null?i:"",i}function ju(){var i,e,l,u,f,p,g;if(f=s,p=s,i=ge(),i===null&&(i=jt()),i!==null){for(e=[],g=s,l=oe(),l!==null?(u=Zi(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=oe(),l!==null?(u=Zi(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){var y=I.tag;try{I=new Rs(I.uri,I.display_name,I.params),y&&I.setParam("tag",y)}catch{I=-1}}()),i===null&&(s=f),i}function Zi(){var i;return i=An(),i===null&&(i=ze()),i}function el(){var i,e,l,u,f,p;if(f=s,i=_r(),i!==null){for(e=[],p=s,l=Re(),l!==null?(u=_r(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=Re(),l!==null?(u=_r(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function _r(){var i,e,l,u,f,p,g,v;if(g=s,i=ll(),i!==null)if(e=pe(),e!==null)if(l=ul(),l!==null){for(u=[],v=s,f=oe(),f!==null?(p=Ys(),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=Ys(),p!==null?f=[f,p]:(f=null,s=v)):(f=null,s=v);u!==null?i=[i,e,l,u]:(i=null,s=g)}else i=null,s=g;else i=null,s=g;else i=null,s=g;return i}function Ys(){var i;return i=pr(),i===null&&(i=tl(),i===null&&(i=sl(),i===null&&(i=nl(),i===null&&(i=rl(),i===null&&(i=ze()))))),i}function pr(){var i,e,l,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=B(),e!==null?(l=gr(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.ttl=g}(u,i[2])),i===null&&(s=u),i}function tl(){var i,e,l,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=B(),e!==null?(l=ls(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.maddr=g}(u,i[2])),i===null&&(s=u),i}function sl(){var i,e,l,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=B(),e!==null?(l=ut(),l===null&&(l=fn()),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.received=g}(u,i[2])),i===null&&(s=u),i}function nl(){var i,e,l,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=B(),e!==null?(l=D(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.branch=g}(u,i[2])),i===null&&(s=u),i}function rl(){var i,e,l,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=B(),e!==null?(l=il(),l!==null?e=[e,l]:(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 il(){var i,e,l,u,f,p,g;return p=s,g=s,i=m(),i=i!==null?i:"",i!==null?(e=m(),e=e!==null?e:"",e!==null?(l=m(),l=l!==null?l:"",l!==null?(u=m(),u=u!==null?u:"",u!==null?(f=m(),f=f!==null?f:"",f!==null?i=[i,e,l,u,f]:(i=null,s=g)):(i=null,s=g)):(i=null,s=g)):(i=null,s=g)):(i=null,s=g),i!==null&&(i=function(v,y){I.rport=parseInt(y.join(""))}(p,i)),i===null&&(s=p),i}function ll(){var i,e,l,u,f,p;return p=s,i=ol(),i!==null?(e=W(),e!==null?(l=D(),l!==null?(u=W(),u!==null?(f=al(),f!==null?i=[i,e,l,u,f]:(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p)):(i=null,s=p),i}function ol(){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=D()),i!==null&&(i=function(l,u){I.protocol=u}(e,i)),i===null&&(s=e),i}function al(){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=D())))),i!==null&&(i=function(l,u){I.transport=u}(e,i)),i===null&&(s=e),i}function ul(){var i,e,l,u,f;return u=s,i=cl(),i!==null?(f=s,e=ye(),e!==null?(l=fl(),l!==null?e=[e,l]:(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 cl(){var i,e;return e=s,i=ut(),i===null&&(i=Wn(),i===null&&(i=Cs())),i!==null&&(i=function(l){I.host=n.substring(s,l)}(e)),i===null&&(s=e),i}function fl(){var i,e,l,u,f,p,g;return p=s,g=s,i=m(),i=i!==null?i:"",i!==null?(e=m(),e=e!==null?e:"",e!==null?(l=m(),l=l!==null?l:"",l!==null?(u=m(),u=u!==null?u:"",u!==null?(f=m(),f=f!==null?f:"",f!==null?i=[i,e,l,u,f]:(i=null,s=g)):(i=null,s=g)):(i=null,s=g)):(i=null,s=g)):(i=null,s=g),i!==null&&(i=function(v,y){I.port=parseInt(y.join(""))}(p,i)),i===null&&(s=p),i}function gr(){var i,e,l,u,f;return u=s,f=s,i=m(),i!==null?(e=m(),e=e!==null?e:"",e!==null?(l=m(),l=l!==null?l:"",l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){return parseInt(g.join(""))}(u,i)),i===null&&(s=u),i}function dl(){var i;return i=Bi(),i}function qu(){var i,e,l,u,f,p;if(f=s,i=jo(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=mr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=mr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function jo(){var i,e;return e=s,i=os(),i!==null&&(i=function(l,u){I.expires=u}(e,i)),i===null&&(s=e),i}function mr(){var i;return i=Tr(),i===null&&(i=ze()),i}function Tr(){var i,e,l,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=B(),e!==null?(n.substr(s,3).toLowerCase()==="uac"?(l=n.substr(s,3),s+=3):(l=null,d('"uac"')),l===null&&(n.substr(s,3).toLowerCase()==="uas"?(l=n.substr(s,3),s+=3):(l=null,d('"uas"'))),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.refresher=g.toLowerCase()}(u,i[2])),i===null&&(s=u),i}function qo(){var i,e,l,u;return u=s,i=D(),i!==null?(e=N(),e!==null?(l=Bo(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Bo(){var i,e;for(i=[],e=j(),e===null&&(e=V(),e===null&&(e=pe()));e!==null;)i.push(e),e=j(),e===null&&(e=V(),e===null&&(e=pe()));return i}function Go(){var i,e;for(i=[],e=A();e!==null;)i.push(e),e=A();return i}function Bu(){var i,e,l;return l=s,n.substr(s,5)==="uuid:"?(i="uuid:",s+=5):(i=null,d('"uuid:"')),i!==null?(e=Wo(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function Wo(){var i,e,l,u,f,p,g,v,y,O,le;return O=s,le=s,i=Gt(),i!==null?(n.charCodeAt(s)===45?(e="-",s++):(e=null,d('"-"')),e!==null?(l=Bt(),l!==null?(n.charCodeAt(s)===45?(u="-",s++):(u=null,d('"-"')),u!==null?(f=Bt(),f!==null?(n.charCodeAt(s)===45?(p="-",s++):(p=null,d('"-"')),p!==null?(g=Bt(),g!==null?(n.charCodeAt(s)===45?(v="-",s++):(v=null,d('"-"')),v!==null?(y=hl(),y!==null?i=[i,e,l,u,f,p,g,v,y]:(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le)):(i=null,s=le),i!==null&&(i=function(xe,Dt){I=n.substring(s+5,xe)}(O,i[0])),i===null&&(s=O),i}function Bt(){var i,e,l,u,f;return f=s,i=S(),i!==null?(e=S(),e!==null?(l=S(),l!==null?(u=S(),u!==null?i=[i,e,l,u]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i}function Gt(){var i,e,l;return l=s,i=Bt(),i!==null?(e=Bt(),e!==null?i=[i,e]:(i=null,s=l)):(i=null,s=l),i}function hl(){var i,e,l,u;return u=s,i=Bt(),i!==null?(e=Bt(),e!==null?(l=Bt(),l!==null?i=[i,e,l]:(i=null,s=u)):(i=null,s=u)):(i=null,s=u),i}function Ko(){var i,e,l,u,f,p,g;if(f=s,p=s,i=ge(),i===null&&(i=jt()),i!==null){for(e=[],g=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);l!==null;)e.push(l),g=s,l=oe(),l!==null?(u=ze(),u!==null?l=[l,u]:(l=null,s=g)):(l=null,s=g);e!==null?i=[i,e]:(i=null,s=p)}else i=null,s=p;return i!==null&&(i=function(v){try{I=new Rs(I.uri,I.display_name,I.params)}catch{I=-1}}()),i===null&&(s=f),i}function Gu(){var i,e,l,u,f,p;if(f=s,i=Yo(),i!==null){for(e=[],p=s,l=oe(),l!==null?(u=vr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);l!==null;)e.push(l),p=s,l=oe(),l!==null?(u=vr(),u!==null?l=[l,u]:(l=null,s=p)):(l=null,s=p);e!==null?i=[i,e]:(i=null,s=f)}else i=null,s=f;return i}function Yo(){var i,e,l,u,f,p;return u=s,f=s,i=je(),i!==null?(p=s,n.charCodeAt(s)===64?(e="@",s++):(e=null,d('"@"')),e!==null?(l=je(),l!==null?e=[e,l]:(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(g){I.call_id=n.substring(s,g)}(u)),i===null&&(s=u),i}function vr(){var i;return i=Sr(),i===null&&(i=_l(),i===null&&(i=pl(),i===null&&(i=ze()))),i}function Sr(){var i,e,l,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=B(),e!==null?(l=D(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.to_tag=g}(u,i[2])),i===null&&(s=u),i}function _l(){var i,e,l,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=B(),e!==null?(l=D(),l!==null?i=[i,e,l]:(i=null,s=f)):(i=null,s=f)):(i=null,s=f),i!==null&&(i=function(p,g){I.from_tag=g}(u,i[2])),i===null&&(s=u),i}function pl(){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(l){I.early_only=!0}()),i===null&&(s=e),i}function Jo(i){i.sort();for(var e=null,l=[],u=0;u<i.length;u++)i[u]!==e&&(l.push(i[u]),e=i[u]);return l}function Wu(){for(var i=1,e=1,l=!1,u=0;u<Math.max(s,r);u++){var f=n.charAt(u);f===`
75
+ `?(l||i++,e=1,l=!1):f==="\r"||f==="\u2028"||f==="\u2029"?(i++,e=1,l=!0):(e++,l=!1)}return{line:i,column:e}}var zo=ps(),Rs=Ba(),I={},w=a[o]();if(w===null||s!==n.length){var gl=Math.max(s,r),ml=gl<n.length?n.charAt(gl):null,Xo=Wu();return new this.SyntaxError(Jo(_),ml,gl,Xo.line,Xo.column),-1}return I},toSource:function(){return this._source}};return t.SyntaxError=function(n,o,a,s,r){function _(d,h){var m,T;switch(d.length){case 0:m="end of input";break;case 1:m=d[0];break;default:m=d.slice(0,d.length-1).join(", ")+" or "+d[d.length-1]}return T=h?c(h):"end of input","Expected "+m+" but "+T+" found."}this.name="SyntaxError",this.expected=n,this.found=o,this.message=_(n,o),this.offset=a,this.line=s,this.column=r},t.SyntaxError.prototype=Error.prototype,t}()),Ga}var Wa,If;function ps(){if(If)return Wa;If=1;const c=De,t=gt(),n=Yt();return Wa=class Hd{static parse(a){if(a=n.parse(a,"SIP_URI"),a!==-1)return a}constructor(a,s,r,_,d={},h={}){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=_;for(const m in d)Object.prototype.hasOwnProperty.call(d,m)&&this.setParam(m,d[m]);for(const m in h)Object.prototype.hasOwnProperty.call(h,m)&&this.setHeader(m,h[m])}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 _ of this._headers[r])a.push(`${r}=${_}`);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}},Wa}var wf;function gt(){if(wf)return et;wf=1;const c=De,t=ps(),n=Yt();et.str_utf8_length=r=>unescape(encodeURIComponent(r)).length;const o=et.isFunction=r=>r!==void 0?Object.prototype.toString.call(r)==="[object Function]":!1;et.isString=r=>r!==void 0?Object.prototype.toString.call(r)==="[object String]":!1,et.isDecimal=r=>!isNaN(r)&&parseFloat(r)===parseInt(r,10),et.isEmpty=r=>r===null||r===""||r===void 0||Array.isArray(r)&&r.length===0||typeof r=="number"&&isNaN(r),et.hasMethods=function(r,..._){for(const d of _)if(o(r[d]))return!1;return!0};const a=et.createRandomToken=(r,_=32)=>{let d,h,m="";for(d=0;d<r;d++)h=Math.random()*_|0,m+=h.toString(_);return m};et.newTag=()=>a(10),et.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,_=>{const d=Math.random()*16|0;return(_==="x"?d:d&3|8).toString(16)}),et.hostType=r=>{if(r){if(r=n.parse(r,"host"),r!==-1)return r.host_type}else return};const s=et.escapeUser=r=>encodeURIComponent(decodeURIComponent(r)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/");return et.normalizeTarget=(r,_)=>{if(r){if(r instanceof t)return r;if(typeof r=="string"){const d=r.split("@");let h,m;switch(d.length){case 1:if(!_)return;h=r,m=_;break;case 2:h=d[0],m=d[1];break;default:h=d.slice(0,d.length-1).join("@"),m=d[d.length-1]}h=h.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(h)&&(h=h.replace(/[-.()]/g,"")),r=`${c.SIP}:${s(h)}@${m}`;let T;return(T=t.parse(r))?T:void 0}else return}else return},et.headerize=r=>{const _={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},d=r.toLowerCase().replace(/_/g,"-").split("-");let h="";const m=d.length;let T;for(T=0;T<m;T++)T!==0&&(h+="-"),h+=d[T].charAt(0).toUpperCase()+d[T].substring(1);return _[h]&&(h=_[h]),h},et.sipErrorCause=r=>{for(const _ in c.SIP_ERROR_CAUSES)if(c.SIP_ERROR_CAUSES[_].indexOf(r)!==-1)return c.causes[_];return c.causes.SIP_FAILURE_CODE},et.getRandomTestNetIP=()=>{function r(_,d){return Math.floor(Math.random()*(d-_+1)+_)}return`192.0.2.${r(1,254)}`},et.calculateMD5=r=>{function _(Ee,Ce){return Ee<<Ce|Ee>>>32-Ce}function d(Ee,Ce){const be=Ee&2147483648,Oe=Ce&2147483648,me=Ee&1073741824,he=Ce&1073741824,ge=(Ee&1073741823)+(Ce&1073741823);return me&he?ge^2147483648^be^Oe:me|he?ge&1073741824?ge^3221225472^be^Oe:ge^1073741824^be^Oe:ge^be^Oe}function h(Ee,Ce,be){return Ee&Ce|~Ee&be}function m(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,me,he,ge){return Ee=d(Ee,d(d(h(Ce,be,Oe),me),ge)),d(_(Ee,he),Ce)}function A(Ee,Ce,be,Oe,me,he,ge){return Ee=d(Ee,d(d(m(Ce,be,Oe),me),ge)),d(_(Ee,he),Ce)}function R(Ee,Ce,be,Oe,me,he,ge){return Ee=d(Ee,d(d(T(Ce,be,Oe),me),ge)),d(_(Ee,he),Ce)}function C(Ee,Ce,be,Oe,me,he,ge){return Ee=d(Ee,d(d(S(Ce,be,Oe),me),ge)),d(_(Ee,he),Ce)}function H(Ee){let Ce;const be=Ee.length,Oe=be+8,he=((Oe-Oe%64)/64+1)*16,ge=new Array(he-1);let we=0,Ne=0;for(;Ne<be;)Ce=(Ne-Ne%4)/4,we=Ne%4*8,ge[Ce]=ge[Ce]|Ee.charCodeAt(Ne)<<we,Ne++;return Ce=(Ne-Ne%4)/4,we=Ne%4*8,ge[Ce]=ge[Ce]|128<<we,ge[he-2]=be<<3,ge[he-1]=be>>>29,ge}function k(Ee){let Ce="",be="",Oe,me;for(me=0;me<=3;me++)Oe=Ee>>>me*8&255,be=`0${Oe.toString(16)}`,Ce=Ce+be.substr(be.length-2,2);return Ce}function re(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=[],F,_e,pe,P,N,q,j,K,V;const z=7,D=12,U=17,X=22,je=5,Q=9,W=14,B=20,ie=4,ve=11,Ie=16,Pe=23,Re=6,oe=10,ye=15,lt=21;for(r=re(r),x=H(r),q=1732584193,j=4023233417,K=2562383102,V=271733878,F=0;F<x.length;F+=16)_e=q,pe=j,P=K,N=V,q=E(q,j,K,V,x[F+0],z,3614090360),V=E(V,q,j,K,x[F+1],D,3905402710),K=E(K,V,q,j,x[F+2],U,606105819),j=E(j,K,V,q,x[F+3],X,3250441966),q=E(q,j,K,V,x[F+4],z,4118548399),V=E(V,q,j,K,x[F+5],D,1200080426),K=E(K,V,q,j,x[F+6],U,2821735955),j=E(j,K,V,q,x[F+7],X,4249261313),q=E(q,j,K,V,x[F+8],z,1770035416),V=E(V,q,j,K,x[F+9],D,2336552879),K=E(K,V,q,j,x[F+10],U,4294925233),j=E(j,K,V,q,x[F+11],X,2304563134),q=E(q,j,K,V,x[F+12],z,1804603682),V=E(V,q,j,K,x[F+13],D,4254626195),K=E(K,V,q,j,x[F+14],U,2792965006),j=E(j,K,V,q,x[F+15],X,1236535329),q=A(q,j,K,V,x[F+1],je,4129170786),V=A(V,q,j,K,x[F+6],Q,3225465664),K=A(K,V,q,j,x[F+11],W,643717713),j=A(j,K,V,q,x[F+0],B,3921069994),q=A(q,j,K,V,x[F+5],je,3593408605),V=A(V,q,j,K,x[F+10],Q,38016083),K=A(K,V,q,j,x[F+15],W,3634488961),j=A(j,K,V,q,x[F+4],B,3889429448),q=A(q,j,K,V,x[F+9],je,568446438),V=A(V,q,j,K,x[F+14],Q,3275163606),K=A(K,V,q,j,x[F+3],W,4107603335),j=A(j,K,V,q,x[F+8],B,1163531501),q=A(q,j,K,V,x[F+13],je,2850285829),V=A(V,q,j,K,x[F+2],Q,4243563512),K=A(K,V,q,j,x[F+7],W,1735328473),j=A(j,K,V,q,x[F+12],B,2368359562),q=R(q,j,K,V,x[F+5],ie,4294588738),V=R(V,q,j,K,x[F+8],ve,2272392833),K=R(K,V,q,j,x[F+11],Ie,1839030562),j=R(j,K,V,q,x[F+14],Pe,4259657740),q=R(q,j,K,V,x[F+1],ie,2763975236),V=R(V,q,j,K,x[F+4],ve,1272893353),K=R(K,V,q,j,x[F+7],Ie,4139469664),j=R(j,K,V,q,x[F+10],Pe,3200236656),q=R(q,j,K,V,x[F+13],ie,681279174),V=R(V,q,j,K,x[F+0],ve,3936430074),K=R(K,V,q,j,x[F+3],Ie,3572445317),j=R(j,K,V,q,x[F+6],Pe,76029189),q=R(q,j,K,V,x[F+9],ie,3654602809),V=R(V,q,j,K,x[F+12],ve,3873151461),K=R(K,V,q,j,x[F+15],Ie,530742520),j=R(j,K,V,q,x[F+2],Pe,3299628645),q=C(q,j,K,V,x[F+0],Re,4096336452),V=C(V,q,j,K,x[F+7],oe,1126891415),K=C(K,V,q,j,x[F+14],ye,2878612391),j=C(j,K,V,q,x[F+5],lt,4237533241),q=C(q,j,K,V,x[F+12],Re,1700485571),V=C(V,q,j,K,x[F+3],oe,2399980690),K=C(K,V,q,j,x[F+10],ye,4293915773),j=C(j,K,V,q,x[F+1],lt,2240044497),q=C(q,j,K,V,x[F+8],Re,1873313359),V=C(V,q,j,K,x[F+15],oe,4264355552),K=C(K,V,q,j,x[F+6],ye,2734768916),j=C(j,K,V,q,x[F+13],lt,1309151649),q=C(q,j,K,V,x[F+4],Re,4149444226),V=C(V,q,j,K,x[F+11],oe,3174756917),K=C(K,V,q,j,x[F+2],ye,718787259),j=C(j,K,V,q,x[F+9],lt,3951481745),q=d(q,_e),j=d(j,pe),K=d(K,P),V=d(V,N);return(k(q)+k(j)+k(K)+k(V)).toLowerCase()},et.closeMediaStream=r=>{if(r)try{let _;if(r.getTracks){_=r.getTracks();for(const d of _)d.stop()}else{_=r.getAudioTracks();for(const d of _)d.stop();_=r.getVideoTracks();for(const d of _)d.stop()}}catch{(typeof r.stop=="function"||typeof r.stop=="object")&&r.stop()}},et.cloneArray=r=>r&&r.slice()||[],et.cloneObject=(r,_={})=>r&&Object.assign({},r)||_,et}const Of=Nt,Rg=ot,mt=De,it=gt(),Df=Ba(),bg=Yt(),Ka=new Rg("SIPMessage");class ro{constructor(t,n,o,a,s,r){if(!t||!n||!o)return null;a=a||{},this.ua=o,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):o.configuration.use_preloaded_route&&this.setHeader("route",`<${o.transport.sip_uri};lr>`),this.setHeader("via",""),this.setHeader("max-forwards",mt.MAX_FORWARDS);const _=a.to_uri||n,d=a.to_tag?{tag:a.to_tag}:null,h=typeof a.to_display_name<"u"?a.to_display_name:null;this.to=new Df(_,h,d),this.setHeader("to",this.to.toString());const m=a.from_uri||o.configuration.uri,T={tag:a.from_tag||it.newTag()};let S;typeof a.from_display_name<"u"?S=a.from_display_name:o.configuration.display_name?S=o.configuration.display_name:S=null,this.from=new Df(m,S,T),this.setHeader("from",this.from.toString());const E=a.call_id||o.configuration.jssip_id+it.createRandomToken(15);this.call_id=E,this.setHeader("call-id",E);const A=a.cseq||Math.floor(Math.random()*1e4);this.cseq=A,this.setHeader("cseq",`${A} ${t}`)}setHeader(t,n){const o=new RegExp(`^\\s*${t}\\s*:`,"i");for(let a=0;a<this.extraHeaders.length;a++)o.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 o=new RegExp(`^\\s*${t}\\s*:`,"i");for(const a of this.extraHeaders)if(o.test(a))return a.substring(a.indexOf(":")+1).trim()}}getHeaders(t){const n=this.headers[it.headerize(t)],o=[];if(n){for(const a of n)o.push(a);return o}else{const a=new RegExp(`^\\s*${t}\\s*:`,"i");for(const s of this.extraHeaders)a.test(s)&&o.push(s.substring(s.indexOf(":")+1).trim());return o}}hasHeader(t){if(this.headers[it.headerize(t)])return!0;{const n=new RegExp(`^\\s*${t}\\s*:`,"i");for(const o of this.extraHeaders)if(n.test(o))return!0}return!1}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=Of.parse(this.body||""),this.sdp)}toString(){let t=`${this.method} ${this.ruri} SIP/2.0\r
76
76
  `;for(const a in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,a))for(const s of this.headers[a])t+=`${a}: ${s}\r
77
77
  `;for(const a of this.extraHeaders)t+=`${a.trim()}\r
78
- `;const n=[];switch(this.method){case gt.REGISTER:n.push("path","gruu");break;case gt.INVITE:this.ua.configuration.session_timers&&n.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&n.push("gruu"),n.push("ice","replaces");break;case gt.UPDATE:this.ua.configuration.session_timers&&n.push("timer"),n.push("ice");break}n.push("outbound");const o=this.ua.configuration.user_agent||gt.USER_AGENT;if(t+=`Allow: ${gt.ALLOWED_METHODS}\r
78
+ `;const n=[];switch(this.method){case mt.REGISTER:n.push("path","gruu");break;case mt.INVITE:this.ua.configuration.session_timers&&n.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&n.push("gruu"),n.push("ice","replaces");break;case mt.UPDATE:this.ua.configuration.session_timers&&n.push("timer"),n.push("ice");break}n.push("outbound");const o=this.ua.configuration.user_agent||mt.USER_AGENT;if(t+=`Allow: ${mt.ALLOWED_METHODS}\r
79
79
  `,t+=`Supported: ${n}\r
80
80
  `,t+=`User-Agent: ${o}\r
81
81
  `,this.body){const a=it.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 ro(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(n){t.headers[n]=this.headers[n].slice()},this),t.body=this.body,t.extraHeaders=it.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t}}class Ya extends ro{constructor(t,n,o,a,s){super(gt.INVITE,t,n,o,a,s),this.transaction=null}cancel(t){this.transaction.cancel(t)}clone(){const t=new Ya(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(n){t.headers[n]=this.headers[n].slice()},this),t.body=this.body,t.extraHeaders=it.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 Nf{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,n){const o={raw:n};t=it.headerize(t),this.headers[t]?this.headers[t].push(o):this.headers[t]=[o]}getHeader(t){const n=this.headers[it.headerize(t)];if(n){if(n[0])return n[0].raw}else return}getHeaders(t){const n=this.headers[it.headerize(t)],o=[];if(!n)return[];for(const a of n)o.push(a.raw);return o}hasHeader(t){return!!this.headers[it.headerize(t)]}parseHeader(t,n=0){if(t=it.headerize(t),this.headers[t]){if(n>=this.headers[t].length){Ka.debug(`not so many "${t}" headers present`);return}}else{Ka.debug(`header "${t}" not present`);return}const o=this.headers[t][n],a=o.raw;if(o.parsed)return o.parsed;const s=bm.parse(a,t.replace(/-/g,"_"));if(s===-1){this.headers[t].splice(n,1),Ka.debug(`error parsing "${t}" header field with value "${a}"`);return}else return o.parsed=s,s}s(t,n){return this.parseHeader(t,n)}setHeader(t,n){const o={raw:n};this.headers[it.headerize(t)]=[o]}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=Of.parse(this.body||""),this.sdp)}toString(){return this.data}}class Im extends Nf{constructor(t){super(),this.ua=t,this.headers={},this.ruri=null,this.transport=null,this.server_transaction=null}reply(t,n,o,a,s,r){const _=[];let d=this.getHeader("To");if(t=t||null,n=n||null,!t||t<100||t>699)throw new TypeError(`Invalid status_code: ${t}`);if(n&&typeof n!="string"&&!(n instanceof String))throw new TypeError(`Invalid reason_phrase: ${n}`);n=n||gt.REASON_PHRASE[t]||"",o=it.cloneArray(o),this.ua.configuration.extra_headers&&(o=o.concat(this.ua.configuration.extra_headers));let h=`SIP/2.0 ${t} ${n}\r
86
- `;if(this.method===gt.INVITE&&t>100&&t<=200){const T=this.getHeaders("record-route");for(const S of T)h+=`Record-Route: ${S}\r
87
- `}const g=this.getHeaders("via");for(const T of g)h+=`Via: ${T}\r
85
+ `;return t}clone(){const t=new ro(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(n){t.headers[n]=this.headers[n].slice()},this),t.body=this.body,t.extraHeaders=it.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t}}class Ya extends ro{constructor(t,n,o,a,s){super(mt.INVITE,t,n,o,a,s),this.transaction=null}cancel(t){this.transaction.cancel(t)}clone(){const t=new Ya(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(n){t.headers[n]=this.headers[n].slice()},this),t.body=this.body,t.extraHeaders=it.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 Nf{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,n){const o={raw:n};t=it.headerize(t),this.headers[t]?this.headers[t].push(o):this.headers[t]=[o]}getHeader(t){const n=this.headers[it.headerize(t)];if(n){if(n[0])return n[0].raw}else return}getHeaders(t){const n=this.headers[it.headerize(t)],o=[];if(!n)return[];for(const a of n)o.push(a.raw);return o}hasHeader(t){return!!this.headers[it.headerize(t)]}parseHeader(t,n=0){if(t=it.headerize(t),this.headers[t]){if(n>=this.headers[t].length){Ka.debug(`not so many "${t}" headers present`);return}}else{Ka.debug(`header "${t}" not present`);return}const o=this.headers[t][n],a=o.raw;if(o.parsed)return o.parsed;const s=bg.parse(a,t.replace(/-/g,"_"));if(s===-1){this.headers[t].splice(n,1),Ka.debug(`error parsing "${t}" header field with value "${a}"`);return}else return o.parsed=s,s}s(t,n){return this.parseHeader(t,n)}setHeader(t,n){const o={raw:n};this.headers[it.headerize(t)]=[o]}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=Of.parse(this.body||""),this.sdp)}toString(){return this.data}}class Ig extends Nf{constructor(t){super(),this.ua=t,this.headers={},this.ruri=null,this.transport=null,this.server_transaction=null}reply(t,n,o,a,s,r){const _=[];let d=this.getHeader("To");if(t=t||null,n=n||null,!t||t<100||t>699)throw new TypeError(`Invalid status_code: ${t}`);if(n&&typeof n!="string"&&!(n instanceof String))throw new TypeError(`Invalid reason_phrase: ${n}`);n=n||mt.REASON_PHRASE[t]||"",o=it.cloneArray(o),this.ua.configuration.extra_headers&&(o=o.concat(this.ua.configuration.extra_headers));let h=`SIP/2.0 ${t} ${n}\r
86
+ `;if(this.method===mt.INVITE&&t>100&&t<=200){const T=this.getHeaders("record-route");for(const S of T)h+=`Record-Route: ${S}\r
87
+ `}const m=this.getHeaders("via");for(const T of m)h+=`Via: ${T}\r
88
88
  `;!this.to_tag&&t>100?d+=`;tag=${it.newTag()}`:this.to_tag&&!this.s("to").hasParam("tag")&&(d+=`;tag=${this.to_tag}`),h+=`To: ${d}\r
89
89
  `,h+=`From: ${this.getHeader("From")}\r
90
90
  `,h+=`Call-ID: ${this.call_id}\r
91
91
  `,h+=`CSeq: ${this.cseq} ${this.method}\r
92
92
  `;for(const T of o)h+=`${T.trim()}\r
93
- `;switch(this.method){case gt.INVITE:this.ua.configuration.session_timers&&_.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&_.push("gruu"),_.push("ice","replaces");break;case gt.UPDATE:this.ua.configuration.session_timers&&_.push("timer"),a&&_.push("ice"),_.push("replaces")}if(_.push("outbound"),this.method===gt.OPTIONS?(h+=`Allow: ${gt.ALLOWED_METHODS}\r
94
- `,h+=`Accept: ${gt.ACCEPTED_BODY_TYPES}\r
95
- `):t===405?h+=`Allow: ${gt.ALLOWED_METHODS}\r
96
- `:t===415&&(h+=`Accept: ${gt.ACCEPTED_BODY_TYPES}\r
93
+ `;switch(this.method){case mt.INVITE:this.ua.configuration.session_timers&&_.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&_.push("gruu"),_.push("ice","replaces");break;case mt.UPDATE:this.ua.configuration.session_timers&&_.push("timer"),a&&_.push("ice"),_.push("replaces")}if(_.push("outbound"),this.method===mt.OPTIONS?(h+=`Allow: ${mt.ALLOWED_METHODS}\r
94
+ `,h+=`Accept: ${mt.ACCEPTED_BODY_TYPES}\r
95
+ `):t===405?h+=`Allow: ${mt.ALLOWED_METHODS}\r
96
+ `:t===415&&(h+=`Accept: ${mt.ACCEPTED_BODY_TYPES}\r
97
97
  `),h+=`Supported: ${_}\r
98
98
  `,a){const T=it.str_utf8_length(a);h+=`Content-Type: application/sdp\r
99
99
  `,h+=`Content-Length: ${T}\r
100
100
  \r
101
101
  `,h+=a}else h+=`Content-Length: 0\r
102
102
  \r
103
- `;this.server_transaction.receiveResponse(t,h,s,r)}reply_sl(t=null,n=null){const o=this.getHeaders("via");if(!t||t<100||t>699)throw new TypeError(`Invalid status_code: ${t}`);if(n&&typeof n!="string"&&!(n instanceof String))throw new TypeError(`Invalid reason_phrase: ${n}`);n=n||gt.REASON_PHRASE[t]||"";let a=`SIP/2.0 ${t} ${n}\r
103
+ `;this.server_transaction.receiveResponse(t,h,s,r)}reply_sl(t=null,n=null){const o=this.getHeaders("via");if(!t||t<100||t>699)throw new TypeError(`Invalid status_code: ${t}`);if(n&&typeof n!="string"&&!(n instanceof String))throw new TypeError(`Invalid reason_phrase: ${n}`);n=n||mt.REASON_PHRASE[t]||"";let a=`SIP/2.0 ${t} ${n}\r
104
104
  `;for(const r of o)a+=`Via: ${r}\r
105
105
  `;let s=this.getHeader("To");if(!this.to_tag&&t>100?s+=`;tag=${it.newTag()}`:this.to_tag&&!this.s("to").hasParam("tag")&&(s+=`;tag=${this.to_tag}`),a+=`To: ${s}\r
106
106
  `,a+=`From: ${this.getHeader("From")}\r
@@ -109,10 +109,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
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 wm extends Nf{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var Tt={OutgoingRequest:ro,InitialOutgoingInviteRequest:Ya,IncomingRequest:Im,IncomingResponse:wm};const Ln=Me(Tt),Om=ot,ms=mt(),Jt=new Om("DigestAuthentication");var xf=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:o},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||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 _,d;return this._qop==="auth"?(_=`${this._method}:${this._uri}`,d=ms.calculateMD5(_),Jt.debug('authenticate() | using qop=auth [a2:"%s"]',_),this._response=ms.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${d}`)):this._qop==="auth-int"?(_=`${this._method}:${this._uri}:${ms.calculateMD5(o||"")}`,d=ms.calculateMD5(_),Jt.debug('authenticate() | using qop=auth-int [a2:"%s"]',_),this._response=ms.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${d}`)):this._qop===null&&(_=`${this._method}:${this._uri}`,d=ms.calculateMD5(_),Jt.debug('authenticate() | using qop=null [a2:"%s"]',_),this._response=ms.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 Dm=Me(xf),gs=500,Nm=4e3,Uf=5e3;var Ja={T1:gs,T2:Nm,T4:Uf,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*Uf,TIMER_L:64*gs,TIMER_M:64*gs,PROVISIONAL_RESPONSE_INTERVAL:6e4};const jr=Me(Ja),qr=ct.EventEmitter,Br=ot,Gr=De,kf=Tt,rs=Ja,Pf=new Br("NonInviteClientTransaction"),io=new Br("InviteClientTransaction"),xm=new Br("AckClientTransaction"),Mf=new Br("NonInviteServerTransaction"),lo=new Br("InviteServerTransaction"),fe={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 Um extends qr{constructor(t,n,o,a){super(),this.type=fe.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=n,this.request=o,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 fe}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(fe.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},rs.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){Pf.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){Pf.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(t){const n=t.status_code;if(n<200)switch(this.state){case fe.STATUS_TRYING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break}else switch(this.state){case fe.STATUS_TRYING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_COMPLETED),clearTimeout(this.F),n===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(t),this.K=setTimeout(()=>{this.timer_K()},rs.TIMER_K);break;case fe.STATUS_COMPLETED:break}}}class km extends qr{constructor(t,n,o,a){super(),this.type=fe.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=n,this.request=o,this.eventHandlers=a,o.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 fe}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(fe.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},rs.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==fe.STATUS_ACCEPTED&&(io.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){io.debug(`Timer M expired for transaction ${this.id}`),this.state===fe.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){io.debug(`Timer B expired for transaction ${this.id}`),this.state===fe.STATUS_CALLING&&(this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){io.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(t){const n=new kf.OutgoingRequest(Gr.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()},rs.TIMER_D),this.transport.send(n)}cancel(t){if(this.state!==fe.STATUS_PROCEEDING)return;const n=new kf.OutgoingRequest(Gr.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 fe.STATUS_CALLING:this.stateChanged(fe.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break;case fe.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(t);break}else if(n>=200&&n<=299)switch(this.state){case fe.STATUS_CALLING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},rs.TIMER_M),this.eventHandlers.onReceiveResponse(t);break;case fe.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(t);break}else if(n>=300&&n<=699)switch(this.state){case fe.STATUS_CALLING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_COMPLETED),this.sendACK(t),this.eventHandlers.onReceiveResponse(t);break;case fe.STATUS_COMPLETED:this.sendACK(t);break}}}class Pm extends qr{constructor(t,n,o,a){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=n,this.request=o,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 fe}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){xm.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class Mm extends qr{constructor(t,n,o){super(),this.type=fe.NON_INVITE_SERVER,this.id=o.via_branch,this.ua=t,this.transport=n,this.request=o,this.last_response="",o.server_transaction=this,this.state=fe.STATUS_TRYING,t.newTransaction(this)}get C(){return fe}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_J(){Mf.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,Mf.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(t,n,o,a){if(t===100)switch(this.state){case fe.STATUS_TRYING:this.stateChanged(fe.STATUS_PROCEEDING),this.transport.send(n)||this.onTransportError();break;case fe.STATUS_PROCEEDING:this.last_response=n,this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break}else if(t>=200&&t<=699)switch(this.state){case fe.STATUS_TRYING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_COMPLETED),this.last_response=n,this.J=setTimeout(()=>{this.timer_J()},rs.TIMER_J),this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break;case fe.STATUS_COMPLETED:break}}}class Lm extends qr{constructor(t,n,o){super(),this.type=fe.INVITE_SERVER,this.id=o.via_branch,this.ua=t,this.transport=n,this.request=o,this.last_response="",o.server_transaction=this,this.state=fe.STATUS_PROCEEDING,t.newTransaction(this),this.resendProvisionalTimer=null,o.reply(100)}get C(){return fe}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_H(){lo.debug(`Timer H expired for transaction ${this.id}`),this.state===fe.STATUS_COMPLETED&&lo.debug("ACK not received, dialog will be terminated"),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){lo.debug(`Timer L expired for transaction ${this.id}`),this.state===fe.STATUS_ACCEPTED&&(this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,lo.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(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(t,n,o,a){if(t>=100&&t<=199)switch(this.state){case fe.STATUS_PROCEEDING:this.transport.send(n)||this.onTransportError(),this.last_response=n;break}if(t>100&&t<=199&&this.state===fe.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},rs.PROVISIONAL_RESPONSE_INTERVAL));else if(t>=200&&t<=299)switch(this.state){case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_ACCEPTED),this.last_response=n,this.L=setTimeout(()=>{this.timer_L()},rs.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case fe.STATUS_ACCEPTED:this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break}else if(t>=300&&t<=699)switch(this.state){case fe.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(n)?(this.stateChanged(fe.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},rs.TIMER_H),o&&o()):(this.onTransportError(),a&&a());break}}}function $m({_transactions:c},t){let n;switch(t.method){case Gr.INVITE:if(n=c.ist[t.via_branch],n){switch(n.state){case fe.STATUS_PROCEEDING:n.transport.send(n.last_response);break;case fe.STATUS_ACCEPTED:break}return!0}break;case Gr.ACK:if(n=c.ist[t.via_branch],n){if(n.state===fe.STATUS_ACCEPTED)return!1;if(n.state===fe.STATUS_COMPLETED)return n.state=fe.STATUS_CONFIRMED,n.I=setTimeout(()=>{n.timer_I()},rs.TIMER_I),!0}else return!1;break;case Gr.CANCEL:return n=c.ist[t.via_branch],n?(t.reply_sl(200),n.state!==fe.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(n=c.nist[t.via_branch],n){switch(n.state){case fe.STATUS_TRYING:break;case fe.STATUS_PROCEEDING:case fe.STATUS_COMPLETED:n.transport.send(n.last_response);break}return!0}break}}var $n={C:fe,NonInviteClientTransaction:Um,InviteClientTransaction:km,AckClientTransaction:Pm,NonInviteServerTransaction:Mm,InviteServerTransaction:Lm,checkTransaction:$m};const Ht=Me($n),Hm=ot,Lf=De,Fm=xf,za=$n,Vm=new Hm("RequestSender"),Xa={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var Hn=class{constructor(t,n,o){this._ua=t,this._eventHandlers=o,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(const a in Xa)Object.prototype.hasOwnProperty.call(Xa,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Xa[a]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==Lf.BYE||this._method!==Lf.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 za.InviteClientTransaction(this._ua,this._ua.transport,this._request,t);break;case"ACK":this.clientTransaction=new za.AckClientTransaction(this._ua,this._ua.transport,this._request,t);break;default:this.clientTransaction=new za.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,o;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"),o="authorization"):(n=t.parseHeader("proxy-authenticate"),o="proxy-authorization"),!n){Vm.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 Fm({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(o,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(t)}else this._eventHandlers.onReceiveResponse(t)}};const Wr=Me(Hn),jm=ot,Qa=mt(),tn=De,$f=Tt,Hf=Hn,Kr=new jm("Registrator"),oo=10;var qm=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=Qa.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 o=t[n];this._extraContactParams+=`;${n}`,o&&(this._extraContactParams+=`=${o}`)}}register(){if(this._registering){Kr.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 $f.OutgoingRequest(tn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),o=new Hf(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")){Kr.debug("no Contact header in response to REGISTER, response ignored");break}const s=a.headers.Contact.reduce((h,g)=>h.concat(g.parsed),[]);let r=s.find(h=>this._sipInstance===h.getParam("+sip.instance")&&this._reg_id===parseInt(h.getParam("reg-id")));if(r||(r=s.find(h=>h.uri.user===this._ua.contact.uri.user)),!r){Kr.debug("no Contact header pointing to us, response ignored");break}let _=r.getParam("expires");!_&&a.hasHeader("expires")&&(_=a.getHeader("expires")),_||(_=this._expires),_=Number(_),_<oo&&(_=oo);const d=_>64?_*1e3/2+Math.floor((_/2-32)*1e3*Math.random()):_*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<oo&&(this._expires=oo),this.register()):(Kr.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,tn.causes.SIP_FAILURE_CODE));break}default:{const s=Qa.sipErrorCause(a.status_code);this._registrationFailure(a,s)}}}});this._registering=!0,o.send()}unregister(t={}){if(!this._registered){Kr.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 o=new $f.OutgoingRequest(tn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Hf(this._ua,o,{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=Qa.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 Bm 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 Gm extends Error{constructor(t){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=t,this.message=`Invalid status: ${t}`}}class Wm extends Error{constructor(t){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=t}}class Km extends Error{constructor(t){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=t}}var Ts={ConfigurationError:Bm,InvalidStateError:Gm,NotSupportedError:Wm,NotReadyError:Km};const Ns=Me(Ts),Za=De,ao=$n,Ym=Hn,eu={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var Ff=class{constructor(t,n,o){this._dialog=t,this._ua=t._ua,this._request=n,this._eventHandlers=o,this._reattempt=!1,this._reattemptTimer=null;for(const a in eu)Object.prototype.hasOwnProperty.call(eu,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=eu[a]))}get request(){return this._request}send(){const t=new Ym(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===Za.INVITE||this._request.method===Za.UPDATE&&this._request.body)&&t.clientTransaction.state!==ao.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;const n=()=>{(t.clientTransaction.state===ao.C.STATUS_ACCEPTED||t.clientTransaction.state===ao.C.STATUS_COMPLETED||t.clientTransaction.state===ao.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===Za.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 Jm=Me(Ff),zm=ot,Vf=Tt,xs=De,Yr=$n,Xm=Ff,tu=mt(),su=new zm("Dialog"),Us={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var jf=class{static get C(){return Us}constructor(t,n,o,a=Us.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 Vf.IncomingResponse&&(a=n.status_code<200?Us.STATUS_EARLY:Us.STATUS_CONFIRMED);const s=n.parseHeader("contact");o==="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):o==="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),su.debug(`new ${o} dialog created with status ${this._state===Us.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===Us.STATUS_TERMINATED}update(t,n){this._state=Us.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=Us.STATUS_TERMINATED}sendRequest(t,n={}){const o=tu.cloneArray(n.extraHeaders),a=tu.cloneObject(n.eventHandlers),s=n.body||null,r=this._createRequest(t,o,s);return a.onAuthenticated=()=>{this._local_seqnum+=1},new Xm(this,r,a).send(),r}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===xs.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===xs.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,n,o){n=tu.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=t===xs.CANCEL||t===xs.ACK?this._local_seqnum:this._local_seqnum+=1;return new Vf.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,o)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===xs.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===xs.INVITE||t.method===xs.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===Yr.C.STATUS_ACCEPTED||t.server_transaction.state===Yr.C.STATUS_COMPLETED||t.server_transaction.state===Yr.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===Yr.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===xs.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Yr.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}};const uo=Me(jf);var nu={exports:{}};const Qm=ct.EventEmitter,Zm=ot,eg=De,tg=Ts,qf=mt(),sg=new Zm("RTCSession:DTMF"),Bf={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};nu.exports=class extends Qm{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 tg.InvalidStateError(this._session.status);const o=qf.cloneArray(n.extraHeaders);if(this.eventHandlers=qf.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,o.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(eg.INFO,{extraHeaders:o,eventHandlers:{onSuccessResponse:s=>{this.emit("succeeded",{originator:"remote",response:s})},onErrorResponse:s=>{this.eventHandlers.onFailed&&this.eventHandlers.onFailed(),this.emit("failed",{originator:"remote",response:s})},onRequestTimeout:()=>{this._session.onRequestTimeout()},onTransportError:()=>{this._session.onTransportError()},onDialogError:()=>{this._session.onDialogError()}},body:a})}init_incoming(t){const n=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,o=/^(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&&n.test(a[0])&&(this._tone=a[0].replace(n,"$2")),a.length>=2&&o.test(a[1])&&(this._duration=parseInt(a[1].replace(o,"$2"),10))}this._duration||(this._duration=Bf.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:t}):sg.debug("invalid INFO DTMF received, discarded")}},nu.exports.C=Bf;var Gf=nu.exports;const ng=Me(Gf),rg=ct.EventEmitter,ig=De,lg=Ts,og=mt();var Wf=class extends rg{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,n,o={}){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 lg.InvalidStateError(this._session.status);this._contentType=t,this._body=n;const a=og.cloneArray(o.extraHeaders);a.push(`Content-Type: ${t}`),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(ig.INFO,{extraHeaders:a,eventHandlers:{onSuccessResponse:s=>{this.emit("succeeded",{originator:"remote",response:s})},onErrorResponse:s=>{this.emit("failed",{originator:"remote",response:s})},onTransportError:()=>{this._session.onTransportError()},onRequestTimeout:()=>{this._session.onRequestTimeout()},onDialogError:()=>{this._session.onDialogError()}},body:n})}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 ru=Me(Wf),ag=ot,Kf=De,ug=new ag("RTCSession:ReferNotifier"),iu={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300};var Yf=class{constructor(t,n,o){this._session=t,this._id=n,this._expires=o||iu.expires,this._active=!0,this.notify(100)}notify(t,n){if(ug.debug("notify()"),this._active===!1)return;n=n||Kf.REASON_PHRASE[t]||"";let o;t>=200?o="terminated;reason=noresource":o=`active;expires=${this._expires}`,this._session.sendRequest(Kf.NOTIFY,{extraHeaders:[`Event: ${iu.event_type};id=${this._id}`,`Subscription-State: ${o}`,`Content-Type: ${iu.body_type}`],body:`SIP/2.0 ${t} ${n}`,eventHandlers:{onErrorResponse(){this._active=!1}}})}};const cg=Me(Yf),fg=ct.EventEmitter,dg=ot,Jr=De,hg=Yt(),Jf=mt(),sn=new dg("RTCSession:ReferSubscriber");var zf=class extends fg{constructor(t){super(),this._id=null,this._session=t}get id(){return this._id}sendRefer(t,n={}){sn.debug("sendRefer()");const o=Jf.cloneArray(n.extraHeaders),a=Jf.cloneObject(n.eventHandlers);for(const d in a)Object.prototype.hasOwnProperty.call(a,d)&&this.on(d,a[d]);let s=null;n.replaces&&(s=n.replaces._request.call_id,s+=`;to-tag=${n.replaces._to_tag}`,s+=`;from-tag=${n.replaces._from_tag}`,s=encodeURIComponent(s));const r=`Refer-To: <${t}${s?`?Replaces=${s}`:""}>`;if(o.push(r),!o.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}>`;o.push(d)}o.push(`Contact: ${this._session.contact}`);const _=this._session.sendRequest(Jr.REFER,{extraHeaders:o,eventHandlers:{onSuccessResponse:d=>{this._requestSucceeded(d)},onErrorResponse:d=>{this._requestFailed(d,Jr.causes.REJECTED)},onTransportError:()=>{this._requestFailed(null,Jr.causes.CONNECTION_ERROR)},onRequestTimeout:()=>{this._requestFailed(null,Jr.causes.REQUEST_TIMEOUT)},onDialogError:()=>{this._requestFailed(null,Jr.causes.DIALOG_ERROR)}}});this._id=_.cseq}receiveNotify(t){if(sn.debug("receiveNotify()"),!t.body)return;const n=hg.parse(t.body.trim().split(`\r
115
- `,1)[0],"Status_Line");if(n===-1){sn.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){sn.debug("REFER succeeded"),sn.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:t})}_requestFailed(t,n){sn.debug("REFER failed"),sn.debug('emit "requestFailed"'),this.emit("requestFailed",{response:t||null,cause:n})}};const _g=Me(zf),pg=ct.EventEmitter,Xf=Nt,mg=ot,de=De,nn=Ts,Qf=$n,We=mt(),zr=Ja,gg=Tt,co=jf,Tg=Hn,Mt=Gf,Zf=Wf,vg=Yf,Sg=zf,ed=ps(),J=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},fo=["audio","video"];var td=class Ku extends pg{static get C(){return te}constructor(t){J.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:de.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return te}get causes(){return de.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={},o){J.debug("connect()");const a=t,s=We.cloneObject(n.eventHandlers),r=We.cloneArray(n.extraHeaders),_=We.cloneObject(n.mediaConstraints,{audio:!0,video:!0}),d=n.mediaStream||null,h=We.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 nn.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new nn.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);this._sessionTimers.enabled&&We.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=de.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=de.SESSION_EXPIRES);for(const A in s)Object.prototype.hasOwnProperty.call(s,A)&&this.on(A,s[A]);this._from_tag=We.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 ed("sip","anonymous","anonymous.invalid"),r.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),r.push("Privacy: id")):n.fromUserName&&(E.from_uri=new ed("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 gg.InitialOutgoingInviteRequest(t,this._ua,E,r),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(h,g),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,o&&o(this),this._newRTCSession("local",this._request),this._sendInitialRequest(_,T,d)}init_incoming(t,n){J.debug("init_incoming()");let o;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")&&(o=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,de.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,de.causes.EXPIRES))},o)),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={}){J.debug("answer()");const n=this._request,o=We.cloneArray(t.extraHeaders),a=We.cloneObject(t.mediaConstraints),s=t.mediaStream||null,r=We.cloneObject(t.pcConfig,{iceServers:[]}),_=t.rtcConstraints||null,d=t.rtcAnswerConstraints||null,h=We.cloneObject(t.rtcOfferConstraints);let g,T=!1,S=!1,E=!1,A=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new nn.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==te.STATUS_WAITING_FOR_ANSWER)throw new nn.InvalidStateError(this._status);if(this._sessionTimers.enabled&&We.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=de.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=de.SESSION_EXPIRES),this._status=te.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),o.unshift(`Contact: ${this._contact}`);const R=n.parseSDP();Array.isArray(R.media)||(R.media=[R.media]);for(const C of R.media)C.type==="audio"&&(T=!0,(!C.direction||C.direction==="sendrecv")&&(E=!0)),C.type==="video"&&(S=!0,(!C.direction||C.direction==="sendrecv")&&(A=!0));if(s&&a.audio===!1){g=s.getAudioTracks();for(const C of g)s.removeTrack(C)}if(s&&a.video===!1){g=s.getVideoTracks();for(const C of g)s.removeTrack(C)}!s&&a.audio===void 0&&(a.audio=E),!s&&a.video===void 0&&(a.video=A),!s&&!T&&!h.offerToReceiveAudio&&(a.audio=!1),!s&&!S&&!h.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(r,_),Promise.resolve().then(()=>{if(s)return s;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(C=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),this._failed("local",null,de.causes.USER_DENIED_MEDIA_ACCESS),J.warn('emit "getusermediafailed" [error:%o]',C),this.emit("getusermediafailed",C),new Error("getUserMedia() failed"))})}).then(C=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=C,C&&C.getTracks().forEach(H=>{this._connection.addTrack(H,C)})}).then(()=>{if(this._late_sdp)return;const C={originator:"remote",type:"offer",sdp:n.body};J.debug('emit "sdp"'),this.emit("sdp",C);const H=new RTCSessionDescription({type:"offer",sdp:C.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(H)).catch(k=>{throw n.reply(488),this._failed("system",null,de.causes.WEBRTC_ERROR),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',k),this.emit("peerconnection:setremotedescriptionfailed",k),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(C=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,o),n.reply(200,null,o,C,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,C),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,de.causes.CONNECTION_ERROR)})}).catch(C=>{this._status!==te.STATUS_TERMINATED&&J.warn(C)})}terminate(t={}){J.debug("terminate()");const n=t.cause||de.causes.BYE,o=We.cloneArray(t.extraHeaders),a=t.body;let s,r=t.status_code,_=t.reason_phrase;if(this._status===te.STATUS_TERMINATED)throw new nn.InvalidStateError(this._status);switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:if(J.debug("canceling session"),r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(_=_||de.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${_}"`),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,de.causes.CANCELED);break;case te.STATUS_WAITING_FOR_ANSWER:case te.STATUS_ANSWERED:if(J.debug("rejecting session"),r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,_,o,a),this._failed("local",null,de.causes.REJECTED);break;case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:if(J.debug("terminating session"),_=t.reason_phrase||de.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&o.push(`Reason: SIP ;cause=${r}; text="${_}"`),this._status===te.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Qf.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:h})=>{h===de.ACK&&(this.sendRequest(de.BYE,{extraHeaders:o,body:a}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Qf.C.STATUS_TERMINATED&&(this.sendRequest(de.BYE,{extraHeaders:o,body:a}),d.terminate())}),this._ended("local",null,n),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(de.BYE,{extraHeaders:o,body:a}),this._ended("local",null,n)}}sendDTMF(t,n={}){J.debug("sendDTMF() | tones: %s",t);let o=0,a=n.duration||null,s=n.interToneGap||null;const r=n.transportType||de.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 nn.InvalidStateError(this._status);if(r!==de.DTMF_TRANSPORT.INFO&&r!==de.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<Mt.C.MIN_DURATION?(J.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?(J.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&&!We.isDecimal(s))throw new TypeError(`Invalid interToneGap: ${s}`);if(s?s<Mt.C.MIN_INTER_TONE_GAP?(J.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===de.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,_.call(this);function _(){let d;if(this._status===te.STATUS_TERMINATED||!this._tones||o>=this._tones.length){this._tones=null;return}const h=this._tones[o];if(o+=1,h===",")d=2e3;else{const g=new Mt(this);n.eventHandlers={onFailed:()=>{this._tones=null}},g.send(h,n),d=a+s}setTimeout(_.bind(this),d)}}sendInfo(t,n,o={}){if(J.debug("sendInfo()"),this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new nn.InvalidStateError(this._status);new Zf(this).send(t,n,o)}mute(t={audio:!0,video:!1}){J.debug("mute()");let n=!1,o=!1;this._audioMuted===!1&&t.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(o=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||o===!0)&&this._onmute({audio:n,video:o})}unmute(t={audio:!0,video:!0}){J.debug("unmute()");let n=!1,o=!1;this._audioMuted===!0&&t.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(o=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||o===!0)&&this._onunmute({audio:n,video:o})}hold(t={},n){if(J.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 o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:de.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:t.extraHeaders}),!0}unhold(t={},n){if(J.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 o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:de.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},n){J.debug("renegotiate()");const o=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:de.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:o,extraHeaders:t.extraHeaders}),!0}refer(t,n){J.debug("refer()");const o=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: ${o}`);const a=new Sg(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 J.debug("sendRequest()"),this._dialog.sendRequest(t,n)}receiveRequest(t){if(J.debug("receiveRequest()"),t.method===de.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,de.causes.CANCELED));else switch(t.method){case de.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:de.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};J.debug('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(a=>{this.terminate({cause:de.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",t);break;case de.BYE:this._status===te.STATUS_CONFIRMED||this._status===te.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,de.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,de.causes.BYE)):t.reply(403,"Wrong Status");break;case de.INVITE:this._status===te.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case de.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 Zf(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case de.UPDATE:this._status===te.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case de.REFER:this._status===te.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case de.NOTIFY:this._status===te.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){J.warn("onTransportError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:de.causes.CONNECTION_ERROR,cause:de.causes.CONNECTION_ERROR})}onRequestTimeout(){J.warn("onRequestTimeout()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:de.causes.REQUEST_TIMEOUT,cause:de.causes.REQUEST_TIMEOUT})}onDialogError(){J.warn("onDialogError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:de.causes.DIALOG_ERROR,cause:de.causes.DIALOG_ERROR})}newDTMF(t){J.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){J.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){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)}_close(){if(J.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(J.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){J.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 o=zr.T1;function a(){this._status===te.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],n),o<zr.T2&&(o=o*2,o>zr.T2&&(o=zr.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),o))}this._timers.invite2xxTimer=setTimeout(a.bind(this),o)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ACK&&(J.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(de.BYE),this._ended("remote",null,de.causes.NO_ACK))},zr.TIMER_H)}_createRTCConnection(t,n){this._connection=new RTCPeerConnection(t,n),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:de.causes.RTP_TIMEOUT,status_code:408,reason_phrase:de.causes.RTP_TIMEOUT})}),J.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,n){if(J.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const o=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?o.createOffer(n).catch(a=>(J.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):o.createAnswer(n).catch(a=>(J.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>o.setLocalDescription(a).catch(s=>(this._rtcReady=!0,J.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s)))).then(()=>{const a=n&&n.iceRestart;if(o.iceGatheringState==="complete"&&!a||o.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:o.localDescription.sdp};return J.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let r=!1,_,d;this._iceReady=!1;const h=()=>{o.removeEventListener("icecandidate",_),o.removeEventListener("icegatheringstatechange",d),r=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:t,sdp:o.localDescription.sdp};J.debug('emit "sdp"'),this.emit("sdp",g),s(g.sdp)};o.addEventListener("icecandidate",_=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:h}):r||h()}),o.addEventListener("icegatheringstatechange",d=()=>{o.iceGatheringState==="complete"&&!r&&h()})})})}_createDialog(t,n,o){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 _=this._earlyDialogs[r];if(o)return _?!0:(_=new co(this,t,n,co.C.STATUS_EARLY),_.error?(J.debug(_.error),this._failed("remote",t,de.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=_,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,_)return _.update(t,n),this._dialog=_,delete this._earlyDialogs[r],!0;const d=new co(this,t,n);return d.error?(J.debug(d.error),this._failed("remote",t,de.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(t){J.debug("receiveReinvite()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,o={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(_={}){a=!0;const d=_.status_code||403,h=_.reason_phrase||"",g=We.cloneArray(_.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,h,g)}if(this.emit("reinvite",o),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(_=>{r.call(this,_)}).catch(()=>{t.reply(500)});return}if(n!=="application/sdp"){J.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(_=>{this._status!==te.STATUS_TERMINATED&&r.call(this,_)}).catch(_=>{J.warn(_)});function r(_){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),this._late_sdp&&(_=this._mangleOffer(_)),t.reply(200,null,d,_,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,_),this._setACKTimer()}),typeof o.callback=="function"&&o.callback()}}_receiveUpdate(t){J.debug("receiveUpdate()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,o={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(_={}){a=!0;const d=_.status_code||403,h=_.reason_phrase||"",g=We.cloneArray(_.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,h,g)}if(this.emit("update",o),a)return;if(!t.body){r.call(this,null);return}if(n!=="application/sdp"){J.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(_=>{this._status!==te.STATUS_TERMINATED&&r.call(this,_)}).catch(_=>{J.warn(_)});function r(_){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),t.reply(200,null,d,_),typeof o.callback=="function"&&o.callback()}}_processInDialogSdpOffer(t){J.debug("_processInDialogSdpOffer()");const n=t.parseSDP();let o=!1;for(const r of n.media){if(fo.indexOf(r.type)===-1)continue;const _=r.direction||n.direction||"sendrecv";if(_==="sendonly"||_==="inactive")o=!0;else{o=!1;break}}const a={originator:"remote",type:"offer",sdp:t.body};J.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),J.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&&o===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&o===!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),J.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',r),r})}).catch(r=>{J.warn("_processInDialogSdpOffer() failed [error: %o]",r)}),this._connectionPromiseQueue}_receiveRefer(t){if(J.debug("receiveRefer()"),!t.refer_to){J.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==de.SIP){J.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const n=new vg(this,t.cseq);J.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,r)=>{o.call(this,s,r)},reject:()=>{a.call(this)}});function o(s,r={}){if(s=typeof s=="function"?s:null,this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const _=new Ku(this._ua);if(_.on("progress",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),_.on("accepted",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),_.on("_failed",({message:d,cause:h})=>{d?n.notify(d.status_code,d.reason_phrase):n.notify(487,h)}),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}`)}_.connect(t.refer_to.uri.toAor(),r,s)}function a(){n.notify(603)}}_receiveNotify(t){switch(J.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let n,o;if(t.event.params&&t.event.params.id)n=t.event.params.id,o=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)o=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!o){t.reply(481,"Subscription does not exist");return}o.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){J.debug("receiveReplaces()");function n(a){if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const s=new Ku(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,a)}function o(){J.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:a=>{n.call(this,a)},reject:()=>{o.call(this)}})}_sendInitialRequest(t,n,o){const a=new Tg(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(o)return o;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,de.causes.USER_DENIED_MEDIA_ACCESS),J.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,de.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,J.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(s=>{this._status!==te.STATUS_TERMINATED&&J.warn(s)})}_getDTMFRTPSender(){const t=this._connection.getSenders().find(n=>n.track&&n.track.kind==="audio");if(!(t&&t.dtmf)){J.warn("sendDTMF() | no local audio track to send DTMF with");return}return t.dtmf}_receiveInviteResponse(t){if(J.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(de.ACK);return}else{const n=new co(this,t,"UAC");if(n.error!==void 0){J.debug(n.error);return}this.sendRequest(de.ACK),this.sendRequest(de.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){J.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};J.debug('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",t)).catch(a=>{J.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,de.causes.MISSING_SDP),this._failed("remote",t,de.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const n={originator:"remote",type:"answer",sdp:t.body};J.debug('emit "sdp"'),this.emit("sdp",n);const o=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,de.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(o).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(de.ACK),this._confirmed("local",null)}).catch(a=>{this._acceptAndTerminate(t,488,"Not Acceptable Here"),this._failed("remote",t,de.causes.BAD_MEDIA_DESCRIPTION),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})});break}default:{const n=We.sipErrorCause(t.status_code);this._failed("remote",t,n)}}}_sendReinvite(t={}){J.debug("sendReinvite()");const n=We.cloneArray(t.extraHeaders),o=We.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 h={originator:"local",type:"offer",sdp:d};J.debug('emit "sdp"'),this.emit("sdp",h),this.sendRequest(de.INVITE,{extraHeaders:n,body:d,eventHandlers:{onSuccessResponse:g=>{r.call(this,g),s=!0},onErrorResponse:g=>{_.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_()});function r(d){if(this._status===te.STATUS_TERMINATED||(this.sendRequest(de.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){_.call(this);return}}else{_.call(this);return}const h={originator:"remote",type:"answer",sdp:d.body};J.debug('emit "sdp"'),this.emit("sdp",h);const g=new RTCSessionDescription({type:"answer",sdp:h.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{o.succeeded&&o.succeeded(d)}).catch(T=>{_.call(this),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function _(d){o.failed&&o.failed(d)}}_sendUpdate(t={}){J.debug("sendUpdate()");const n=We.cloneArray(t.extraHeaders),o=We.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(h=>{h=this._mangleOffer(h);const g={originator:"local",type:"offer",sdp:h};J.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest(de.UPDATE,{extraHeaders:n,body:h,eventHandlers:{onSuccessResponse:T=>{_.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(de.UPDATE,{extraHeaders:n,eventHandlers:{onSuccessResponse:h=>{_.call(this,h)},onErrorResponse:h=>{d.call(this,h)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function _(h){if(this._status!==te.STATUS_TERMINATED&&!r)if(this._handleSessionTimersInIncomingResponse(h),s){if(h.body){if(!h.hasHeader("Content-Type")||h.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const g={originator:"remote",type:"answer",sdp:h.body};J.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(()=>{o.succeeded&&o.succeeded(h)}).catch(S=>{d.call(this),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),this.emit("peerconnection:setremotedescriptionfailed",S)})}else o.succeeded&&o.succeeded(h)}function d(h){o.failed&&o.failed(h)}}_acceptAndTerminate(t,n,o){J.debug("acceptAndTerminate()");const a=[];n&&(o=o||de.REASON_PHRASE[n]||"",a.push(`Reason: SIP ;cause=${n}; text="${o}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(de.ACK),this.sendRequest(de.BYE,{extraHeaders:a})),this._status=te.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=Xf.parse(t),this._localHold&&!this._remoteHold){J.debug("mangleOffer() | me on hold, mangling offer");for(const n of t.media)fo.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){J.debug("mangleOffer() | both on hold, mangling offer");for(const n of t.media)fo.indexOf(n.type)!==-1&&(n.direction="inactive")}else if(this._remoteHold){J.debug("mangleOffer() | remote on hold, mangling offer");for(const n of t.media)fo.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="recvonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="recvonly")}return Xf.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 o;t.session_expires&&t.session_expires>=de.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,o=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,o="uas"),n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${o}`),this._sessionTimers.refresher=o==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=de.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()&&(J.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===de.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&(J.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:de.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="audio");for(const o of n)o.track.enabled=!t}_toggleMuteVideo(t){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="video");for(const o of n)o.track.enabled=!t}_newRTCSession(t,n){J.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:t,session:this,request:n})}_connecting(t){J.debug("session connecting"),J.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,n){J.debug("session progress"),J.debug('emit "progress"'),this.emit("progress",{originator:t,response:n||null})}_accepted(t,n){J.debug("session accepted"),this._start_time=new Date,J.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){J.debug("session confirmed"),this._is_confirmed=!0,J.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,o){J.debug("session ended"),this._end_time=new Date,this._close(),J.debug('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:o})}_failed(t,n,o){J.debug("session failed"),J.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:n||null,cause:o}),this._close(),J.debug('emit "failed"'),this.emit("failed",{originator:t,message:n||null,cause:o})}_onhold(t){J.debug("session onhold"),this._setLocalMediaStatus(),J.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){J.debug("session onunhold"),this._setLocalMediaStatus(),J.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:n}){J.debug("session onmute"),this._setLocalMediaStatus(),J.debug('emit "muted"'),this.emit("muted",{audio:t,video:n})}_onunmute({audio:t,video:n}){J.debug("session onunmute"),this._setLocalMediaStatus(),J.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:n})}};const Eg=Me(td),yg=ct.EventEmitter,Cg=ot,lu=De,Ag=Tt,Xr=mt(),Rg=Hn,sd=Ts,bg=ps(),ho=new Cg("Message");var Ig=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,o={}){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=Xr.cloneArray(o.extraHeaders),r=Xr.cloneObject(o.eventHandlers),_=o.contentType||"text/plain",d={};o.fromUserName&&(d.from_uri=new bg("sip",o.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),o.fromDisplayName&&(d.from_display_name=o.fromDisplayName);for(const g in r)Object.prototype.hasOwnProperty.call(r,g)&&this.on(g,r[g]);s.push(`Content-Type: ${_}`),this._request=new Ag.OutgoingRequest(lu.MESSAGE,t,this._ua,d,s),n&&(this._request.body=n);const h=new Rg(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:g=>{this._receiveResponse(g)}});this._newMessage("local",this._request),h.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=Xr.cloneArray(t.extraHeaders),o=t.body;if(this._direction!=="incoming")throw new sd.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,o)}reject(t={}){const n=t.status_code||480,o=t.reason_phrase,a=Xr.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new sd.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,o,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=Xr.sipErrorCause(t.status_code);this._failed("remote",t,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,lu.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,lu.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,o){ho.debug("MESSAGE failed"),this._close(),ho.debug('emit "failed"'),this.emit("failed",{originator:t,response:n||null,cause:o})}_succeeded(t,n){ho.debug("MESSAGE succeeded"),this._close(),ho.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:n})}};const wg=ct.EventEmitter,Og=ot,ou=De,Dg=Tt,Qr=mt(),Ng=Hn,nd=Ts,_o=new Og("Options");var xg=class extends wg{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,o={}){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=Qr.cloneArray(o.extraHeaders),r=Qr.cloneObject(o.eventHandlers),_=o.contentType||"application/sdp";for(const h in r)Object.prototype.hasOwnProperty.call(r,h)&&this.on(h,r[h]);s.push(`Content-Type: ${_}`),this._request=new Dg.OutgoingRequest(ou.OPTIONS,t,this._ua,null,s),n&&(this._request.body=n);const d=new Ng(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:h=>{this._receiveResponse(h)}});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=Qr.cloneArray(t.extraHeaders),o=t.body;if(this._direction!=="incoming")throw new nd.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,o)}reject(t={}){const n=t.status_code||480,o=t.reason_phrase,a=Qr.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new nd.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,o,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=Qr.sipErrorCause(t.status_code);this._failed("remote",t,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,ou.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,ou.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,o){_o.debug("OPTIONS failed"),this._close(),_o.debug('emit "failed"'),this.emit("failed",{originator:t,response:n||null,cause:o})}_succeeded(t,n){_o.debug("OPTIONS succeeded"),this._close(),_o.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:n})}},au={};const Ug=ot,uu=mt(),kg=Yt(),Zr=new Ug("Socket");au.isSocket=c=>{if(Array.isArray(c))return!1;if(typeof c>"u")return Zr.warn("undefined JsSIP.Socket instance"),!1;try{if(!uu.isString(c.url))throw Zr.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!uu.isString(c.via_transport))throw Zr.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(kg.parse(c.sip_uri,"SIP_URI")===-1)throw Zr.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(!uu.isFunction(c[t]))throw Zr.warn(`missing or invalid JsSIP.Socket method: ${t}`),new Error(`Missing or invalid JsSIP.Socket method: ${t}`)})}catch{return!1}return!0};const Pg=ot,Mg=au,rd=De,Ut=new Pg("Transport"),Ft={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:rd.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:rd.CONNECTION_RECOVERY_MAX_INTERVAL}};var id=class{constructor(t,n=Ft.recovery_options){Ut.debug("new()"),this.status=Ft.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(o){Ut.warn(`cannot use TextDecoder: ${o}`)}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(o){if(!Mg.isSocket(o.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(o.weight&&!Number(o.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:o.socket,weight:o.weight||0,status:Ft.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=Ft.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=Ft.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 n=t.toString();return Ut.debug(`sending message:
112
+ `,this.transport.send(a)}}class wg extends Nf{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var Tt={OutgoingRequest:ro,InitialOutgoingInviteRequest:Ya,IncomingRequest:Ig,IncomingResponse:wg};const Ln=Me(Tt),Og=ot,gs=gt(),Jt=new Og("DigestAuthentication");var xf=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:o},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||gs.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=gs.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._ha1=this._credentials.ha1;let _,d;return this._qop==="auth"?(_=`${this._method}:${this._uri}`,d=gs.calculateMD5(_),Jt.debug('authenticate() | using qop=auth [a2:"%s"]',_),this._response=gs.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${d}`)):this._qop==="auth-int"?(_=`${this._method}:${this._uri}:${gs.calculateMD5(o||"")}`,d=gs.calculateMD5(_),Jt.debug('authenticate() | using qop=auth-int [a2:"%s"]',_),this._response=gs.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${d}`)):this._qop===null&&(_=`${this._method}:${this._uri}`,d=gs.calculateMD5(_),Jt.debug('authenticate() | using qop=null [a2:"%s"]',_),this._response=gs.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 Dg=Me(xf),ms=500,Ng=4e3,Uf=5e3;var Ja={T1:ms,T2:Ng,T4:Uf,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*Uf,TIMER_L:64*ms,TIMER_M:64*ms,PROVISIONAL_RESPONSE_INTERVAL:6e4};const jr=Me(Ja),qr=ct.EventEmitter,Br=ot,Gr=De,kf=Tt,rs=Ja,Pf=new Br("NonInviteClientTransaction"),io=new Br("InviteClientTransaction"),xg=new Br("AckClientTransaction"),Mf=new Br("NonInviteServerTransaction"),lo=new Br("InviteServerTransaction"),fe={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 Ug extends qr{constructor(t,n,o,a){super(),this.type=fe.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=n,this.request=o,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 fe}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(fe.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},rs.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){Pf.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){Pf.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(t){const n=t.status_code;if(n<200)switch(this.state){case fe.STATUS_TRYING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break}else switch(this.state){case fe.STATUS_TRYING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_COMPLETED),clearTimeout(this.F),n===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(t),this.K=setTimeout(()=>{this.timer_K()},rs.TIMER_K);break;case fe.STATUS_COMPLETED:break}}}class kg extends qr{constructor(t,n,o,a){super(),this.type=fe.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=n,this.request=o,this.eventHandlers=a,o.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 fe}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(fe.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},rs.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==fe.STATUS_ACCEPTED&&(io.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){io.debug(`Timer M expired for transaction ${this.id}`),this.state===fe.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){io.debug(`Timer B expired for transaction ${this.id}`),this.state===fe.STATUS_CALLING&&(this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){io.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(t){const n=new kf.OutgoingRequest(Gr.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()},rs.TIMER_D),this.transport.send(n)}cancel(t){if(this.state!==fe.STATUS_PROCEEDING)return;const n=new kf.OutgoingRequest(Gr.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 fe.STATUS_CALLING:this.stateChanged(fe.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break;case fe.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(t);break}else if(n>=200&&n<=299)switch(this.state){case fe.STATUS_CALLING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},rs.TIMER_M),this.eventHandlers.onReceiveResponse(t);break;case fe.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(t);break}else if(n>=300&&n<=699)switch(this.state){case fe.STATUS_CALLING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_COMPLETED),this.sendACK(t),this.eventHandlers.onReceiveResponse(t);break;case fe.STATUS_COMPLETED:this.sendACK(t);break}}}class Pg extends qr{constructor(t,n,o,a){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=n,this.request=o,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 fe}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){xg.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class Mg extends qr{constructor(t,n,o){super(),this.type=fe.NON_INVITE_SERVER,this.id=o.via_branch,this.ua=t,this.transport=n,this.request=o,this.last_response="",o.server_transaction=this,this.state=fe.STATUS_TRYING,t.newTransaction(this)}get C(){return fe}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_J(){Mf.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,Mf.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(t,n,o,a){if(t===100)switch(this.state){case fe.STATUS_TRYING:this.stateChanged(fe.STATUS_PROCEEDING),this.transport.send(n)||this.onTransportError();break;case fe.STATUS_PROCEEDING:this.last_response=n,this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break}else if(t>=200&&t<=699)switch(this.state){case fe.STATUS_TRYING:case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_COMPLETED),this.last_response=n,this.J=setTimeout(()=>{this.timer_J()},rs.TIMER_J),this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break;case fe.STATUS_COMPLETED:break}}}class Lg extends qr{constructor(t,n,o){super(),this.type=fe.INVITE_SERVER,this.id=o.via_branch,this.ua=t,this.transport=n,this.request=o,this.last_response="",o.server_transaction=this,this.state=fe.STATUS_PROCEEDING,t.newTransaction(this),this.resendProvisionalTimer=null,o.reply(100)}get C(){return fe}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_H(){lo.debug(`Timer H expired for transaction ${this.id}`),this.state===fe.STATUS_COMPLETED&&lo.debug("ACK not received, dialog will be terminated"),this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){lo.debug(`Timer L expired for transaction ${this.id}`),this.state===fe.STATUS_ACCEPTED&&(this.stateChanged(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,lo.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(fe.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(t,n,o,a){if(t>=100&&t<=199)switch(this.state){case fe.STATUS_PROCEEDING:this.transport.send(n)||this.onTransportError(),this.last_response=n;break}if(t>100&&t<=199&&this.state===fe.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},rs.PROVISIONAL_RESPONSE_INTERVAL));else if(t>=200&&t<=299)switch(this.state){case fe.STATUS_PROCEEDING:this.stateChanged(fe.STATUS_ACCEPTED),this.last_response=n,this.L=setTimeout(()=>{this.timer_L()},rs.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case fe.STATUS_ACCEPTED:this.transport.send(n)?o&&o():(this.onTransportError(),a&&a());break}else if(t>=300&&t<=699)switch(this.state){case fe.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(n)?(this.stateChanged(fe.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},rs.TIMER_H),o&&o()):(this.onTransportError(),a&&a());break}}}function $g({_transactions:c},t){let n;switch(t.method){case Gr.INVITE:if(n=c.ist[t.via_branch],n){switch(n.state){case fe.STATUS_PROCEEDING:n.transport.send(n.last_response);break;case fe.STATUS_ACCEPTED:break}return!0}break;case Gr.ACK:if(n=c.ist[t.via_branch],n){if(n.state===fe.STATUS_ACCEPTED)return!1;if(n.state===fe.STATUS_COMPLETED)return n.state=fe.STATUS_CONFIRMED,n.I=setTimeout(()=>{n.timer_I()},rs.TIMER_I),!0}else return!1;break;case Gr.CANCEL:return n=c.ist[t.via_branch],n?(t.reply_sl(200),n.state!==fe.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(n=c.nist[t.via_branch],n){switch(n.state){case fe.STATUS_TRYING:break;case fe.STATUS_PROCEEDING:case fe.STATUS_COMPLETED:n.transport.send(n.last_response);break}return!0}break}}var $n={C:fe,NonInviteClientTransaction:Ug,InviteClientTransaction:kg,AckClientTransaction:Pg,NonInviteServerTransaction:Mg,InviteServerTransaction:Lg,checkTransaction:$g};const Ht=Me($n),Hg=ot,Lf=De,Fg=xf,za=$n,Vg=new Hg("RequestSender"),Xa={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var Hn=class{constructor(t,n,o){this._ua=t,this._eventHandlers=o,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(const a in Xa)Object.prototype.hasOwnProperty.call(Xa,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=Xa[a]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==Lf.BYE||this._method!==Lf.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 za.InviteClientTransaction(this._ua,this._ua.transport,this._request,t);break;case"ACK":this.clientTransaction=new za.AckClientTransaction(this._ua,this._ua.transport,this._request,t);break;default:this.clientTransaction=new za.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,o;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"),o="authorization"):(n=t.parseHeader("proxy-authenticate"),o="proxy-authorization"),!n){Vg.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 Fg({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(o,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(t)}else this._eventHandlers.onReceiveResponse(t)}};const Wr=Me(Hn),jg=ot,Qa=gt(),tn=De,$f=Tt,Hf=Hn,Kr=new jg("Registrator"),oo=10;var qg=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=Qa.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 o=t[n];this._extraContactParams+=`;${n}`,o&&(this._extraContactParams+=`=${o}`)}}register(){if(this._registering){Kr.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 $f.OutgoingRequest(tn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),o=new Hf(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")){Kr.debug("no Contact header in response to REGISTER, response ignored");break}const s=a.headers.Contact.reduce((h,m)=>h.concat(m.parsed),[]);let r=s.find(h=>this._sipInstance===h.getParam("+sip.instance")&&this._reg_id===parseInt(h.getParam("reg-id")));if(r||(r=s.find(h=>h.uri.user===this._ua.contact.uri.user)),!r){Kr.debug("no Contact header pointing to us, response ignored");break}let _=r.getParam("expires");!_&&a.hasHeader("expires")&&(_=a.getHeader("expires")),_||(_=this._expires),_=Number(_),_<oo&&(_=oo);const d=_>64?_*1e3/2+Math.floor((_/2-32)*1e3*Math.random()):_*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<oo&&(this._expires=oo),this.register()):(Kr.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,tn.causes.SIP_FAILURE_CODE));break}default:{const s=Qa.sipErrorCause(a.status_code);this._registrationFailure(a,s)}}}});this._registering=!0,o.send()}unregister(t={}){if(!this._registered){Kr.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 o=new $f.OutgoingRequest(tn.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Hf(this._ua,o,{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=Qa.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 Bg 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 Gg extends Error{constructor(t){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=t,this.message=`Invalid status: ${t}`}}class Wg extends Error{constructor(t){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=t}}class Kg extends Error{constructor(t){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=t}}var Ts={ConfigurationError:Bg,InvalidStateError:Gg,NotSupportedError:Wg,NotReadyError:Kg};const Ns=Me(Ts),Za=De,ao=$n,Yg=Hn,eu={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var Ff=class{constructor(t,n,o){this._dialog=t,this._ua=t._ua,this._request=n,this._eventHandlers=o,this._reattempt=!1,this._reattemptTimer=null;for(const a in eu)Object.prototype.hasOwnProperty.call(eu,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=eu[a]))}get request(){return this._request}send(){const t=new Yg(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===Za.INVITE||this._request.method===Za.UPDATE&&this._request.body)&&t.clientTransaction.state!==ao.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;const n=()=>{(t.clientTransaction.state===ao.C.STATUS_ACCEPTED||t.clientTransaction.state===ao.C.STATUS_COMPLETED||t.clientTransaction.state===ao.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===Za.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 Jg=Me(Ff),zg=ot,Vf=Tt,xs=De,Yr=$n,Xg=Ff,tu=gt(),su=new zg("Dialog"),Us={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var jf=class{static get C(){return Us}constructor(t,n,o,a=Us.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 Vf.IncomingResponse&&(a=n.status_code<200?Us.STATUS_EARLY:Us.STATUS_CONFIRMED);const s=n.parseHeader("contact");o==="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):o==="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),su.debug(`new ${o} dialog created with status ${this._state===Us.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===Us.STATUS_TERMINATED}update(t,n){this._state=Us.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=Us.STATUS_TERMINATED}sendRequest(t,n={}){const o=tu.cloneArray(n.extraHeaders),a=tu.cloneObject(n.eventHandlers),s=n.body||null,r=this._createRequest(t,o,s);return a.onAuthenticated=()=>{this._local_seqnum+=1},new Xg(this,r,a).send(),r}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===xs.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===xs.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,n,o){n=tu.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=t===xs.CANCEL||t===xs.ACK?this._local_seqnum:this._local_seqnum+=1;return new Vf.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,o)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===xs.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===xs.INVITE||t.method===xs.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===Yr.C.STATUS_ACCEPTED||t.server_transaction.state===Yr.C.STATUS_COMPLETED||t.server_transaction.state===Yr.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===Yr.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===xs.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Yr.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}};const uo=Me(jf);var nu={exports:{}};const Qg=ct.EventEmitter,Zg=ot,em=De,tm=Ts,qf=gt(),sm=new Zg("RTCSession:DTMF"),Bf={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};nu.exports=class extends Qg{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 tm.InvalidStateError(this._session.status);const o=qf.cloneArray(n.extraHeaders);if(this.eventHandlers=qf.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,o.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(em.INFO,{extraHeaders:o,eventHandlers:{onSuccessResponse:s=>{this.emit("succeeded",{originator:"remote",response:s})},onErrorResponse:s=>{this.eventHandlers.onFailed&&this.eventHandlers.onFailed(),this.emit("failed",{originator:"remote",response:s})},onRequestTimeout:()=>{this._session.onRequestTimeout()},onTransportError:()=>{this._session.onTransportError()},onDialogError:()=>{this._session.onDialogError()}},body:a})}init_incoming(t){const n=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,o=/^(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&&n.test(a[0])&&(this._tone=a[0].replace(n,"$2")),a.length>=2&&o.test(a[1])&&(this._duration=parseInt(a[1].replace(o,"$2"),10))}this._duration||(this._duration=Bf.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:t}):sm.debug("invalid INFO DTMF received, discarded")}},nu.exports.C=Bf;var Gf=nu.exports;const nm=Me(Gf),rm=ct.EventEmitter,im=De,lm=Ts,om=gt();var Wf=class extends rm{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,n,o={}){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 lm.InvalidStateError(this._session.status);this._contentType=t,this._body=n;const a=om.cloneArray(o.extraHeaders);a.push(`Content-Type: ${t}`),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(im.INFO,{extraHeaders:a,eventHandlers:{onSuccessResponse:s=>{this.emit("succeeded",{originator:"remote",response:s})},onErrorResponse:s=>{this.emit("failed",{originator:"remote",response:s})},onTransportError:()=>{this._session.onTransportError()},onRequestTimeout:()=>{this._session.onRequestTimeout()},onDialogError:()=>{this._session.onDialogError()}},body:n})}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 ru=Me(Wf),am=ot,Kf=De,um=new am("RTCSession:ReferNotifier"),iu={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300};var Yf=class{constructor(t,n,o){this._session=t,this._id=n,this._expires=o||iu.expires,this._active=!0,this.notify(100)}notify(t,n){if(um.debug("notify()"),this._active===!1)return;n=n||Kf.REASON_PHRASE[t]||"";let o;t>=200?o="terminated;reason=noresource":o=`active;expires=${this._expires}`,this._session.sendRequest(Kf.NOTIFY,{extraHeaders:[`Event: ${iu.event_type};id=${this._id}`,`Subscription-State: ${o}`,`Content-Type: ${iu.body_type}`],body:`SIP/2.0 ${t} ${n}`,eventHandlers:{onErrorResponse(){this._active=!1}}})}};const cm=Me(Yf),fm=ct.EventEmitter,dm=ot,Jr=De,hm=Yt(),Jf=gt(),sn=new dm("RTCSession:ReferSubscriber");var zf=class extends fm{constructor(t){super(),this._id=null,this._session=t}get id(){return this._id}sendRefer(t,n={}){sn.debug("sendRefer()");const o=Jf.cloneArray(n.extraHeaders),a=Jf.cloneObject(n.eventHandlers);for(const d in a)Object.prototype.hasOwnProperty.call(a,d)&&this.on(d,a[d]);let s=null;n.replaces&&(s=n.replaces._request.call_id,s+=`;to-tag=${n.replaces._to_tag}`,s+=`;from-tag=${n.replaces._from_tag}`,s=encodeURIComponent(s));const r=`Refer-To: <${t}${s?`?Replaces=${s}`:""}>`;if(o.push(r),!o.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}>`;o.push(d)}o.push(`Contact: ${this._session.contact}`);const _=this._session.sendRequest(Jr.REFER,{extraHeaders:o,eventHandlers:{onSuccessResponse:d=>{this._requestSucceeded(d)},onErrorResponse:d=>{this._requestFailed(d,Jr.causes.REJECTED)},onTransportError:()=>{this._requestFailed(null,Jr.causes.CONNECTION_ERROR)},onRequestTimeout:()=>{this._requestFailed(null,Jr.causes.REQUEST_TIMEOUT)},onDialogError:()=>{this._requestFailed(null,Jr.causes.DIALOG_ERROR)}}});this._id=_.cseq}receiveNotify(t){if(sn.debug("receiveNotify()"),!t.body)return;const n=hm.parse(t.body.trim().split(`\r
115
+ `,1)[0],"Status_Line");if(n===-1){sn.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){sn.debug("REFER succeeded"),sn.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:t})}_requestFailed(t,n){sn.debug("REFER failed"),sn.debug('emit "requestFailed"'),this.emit("requestFailed",{response:t||null,cause:n})}};const _m=Me(zf),pm=ct.EventEmitter,Xf=Nt,gm=ot,de=De,nn=Ts,Qf=$n,We=gt(),zr=Ja,mm=Tt,co=jf,Tm=Hn,Mt=Gf,Zf=Wf,vm=Yf,Sm=zf,ed=ps(),J=new gm("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},fo=["audio","video"];var td=class Ku extends pm{static get C(){return te}constructor(t){J.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:de.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return te}get causes(){return de.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={},o){J.debug("connect()");const a=t,s=We.cloneObject(n.eventHandlers),r=We.cloneArray(n.extraHeaders),_=We.cloneObject(n.mediaConstraints,{audio:!0,video:!0}),d=n.mediaStream||null,h=We.cloneObject(n.pcConfig,{iceServers:[]}),m=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 nn.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new nn.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${a}`);this._sessionTimers.enabled&&We.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=de.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=de.SESSION_EXPIRES);for(const A in s)Object.prototype.hasOwnProperty.call(s,A)&&this.on(A,s[A]);this._from_tag=We.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 ed("sip","anonymous","anonymous.invalid"),r.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),r.push("Privacy: id")):n.fromUserName&&(E.from_uri=new ed("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 mm.InitialOutgoingInviteRequest(t,this._ua,E,r),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(h,m),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,o&&o(this),this._newRTCSession("local",this._request),this._sendInitialRequest(_,T,d)}init_incoming(t,n){J.debug("init_incoming()");let o;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")&&(o=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,de.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,de.causes.EXPIRES))},o)),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={}){J.debug("answer()");const n=this._request,o=We.cloneArray(t.extraHeaders),a=We.cloneObject(t.mediaConstraints),s=t.mediaStream||null,r=We.cloneObject(t.pcConfig,{iceServers:[]}),_=t.rtcConstraints||null,d=t.rtcAnswerConstraints||null,h=We.cloneObject(t.rtcOfferConstraints);let m,T=!1,S=!1,E=!1,A=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new nn.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==te.STATUS_WAITING_FOR_ANSWER)throw new nn.InvalidStateError(this._status);if(this._sessionTimers.enabled&&We.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=de.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=de.SESSION_EXPIRES),this._status=te.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),o.unshift(`Contact: ${this._contact}`);const R=n.parseSDP();Array.isArray(R.media)||(R.media=[R.media]);for(const C of R.media)C.type==="audio"&&(T=!0,(!C.direction||C.direction==="sendrecv")&&(E=!0)),C.type==="video"&&(S=!0,(!C.direction||C.direction==="sendrecv")&&(A=!0));if(s&&a.audio===!1){m=s.getAudioTracks();for(const C of m)s.removeTrack(C)}if(s&&a.video===!1){m=s.getVideoTracks();for(const C of m)s.removeTrack(C)}!s&&a.audio===void 0&&(a.audio=E),!s&&a.video===void 0&&(a.video=A),!s&&!T&&!h.offerToReceiveAudio&&(a.audio=!1),!s&&!S&&!h.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(r,_),Promise.resolve().then(()=>{if(s)return s;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(C=>{throw this._status===te.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),this._failed("local",null,de.causes.USER_DENIED_MEDIA_ACCESS),J.warn('emit "getusermediafailed" [error:%o]',C),this.emit("getusermediafailed",C),new Error("getUserMedia() failed"))})}).then(C=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=C,C&&C.getTracks().forEach(H=>{this._connection.addTrack(H,C)})}).then(()=>{if(this._late_sdp)return;const C={originator:"remote",type:"offer",sdp:n.body};J.debug('emit "sdp"'),this.emit("sdp",C);const H=new RTCSessionDescription({type:"offer",sdp:C.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(H)).catch(k=>{throw n.reply(488),this._failed("system",null,de.causes.WEBRTC_ERROR),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',k),this.emit("peerconnection:setremotedescriptionfailed",k),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(C=>{if(this._status===te.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,o),n.reply(200,null,o,C,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,C),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,de.causes.CONNECTION_ERROR)})}).catch(C=>{this._status!==te.STATUS_TERMINATED&&J.warn(C)})}terminate(t={}){J.debug("terminate()");const n=t.cause||de.causes.BYE,o=We.cloneArray(t.extraHeaders),a=t.body;let s,r=t.status_code,_=t.reason_phrase;if(this._status===te.STATUS_TERMINATED)throw new nn.InvalidStateError(this._status);switch(this._status){case te.STATUS_NULL:case te.STATUS_INVITE_SENT:case te.STATUS_1XX_RECEIVED:if(J.debug("canceling session"),r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(_=_||de.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${_}"`),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,de.causes.CANCELED);break;case te.STATUS_WAITING_FOR_ANSWER:case te.STATUS_ANSWERED:if(J.debug("rejecting session"),r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,_,o,a),this._failed("local",null,de.causes.REJECTED);break;case te.STATUS_WAITING_FOR_ACK:case te.STATUS_CONFIRMED:if(J.debug("terminating session"),_=t.reason_phrase||de.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&o.push(`Reason: SIP ;cause=${r}; text="${_}"`),this._status===te.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Qf.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:h})=>{h===de.ACK&&(this.sendRequest(de.BYE,{extraHeaders:o,body:a}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Qf.C.STATUS_TERMINATED&&(this.sendRequest(de.BYE,{extraHeaders:o,body:a}),d.terminate())}),this._ended("local",null,n),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(de.BYE,{extraHeaders:o,body:a}),this._ended("local",null,n)}}sendDTMF(t,n={}){J.debug("sendDTMF() | tones: %s",t);let o=0,a=n.duration||null,s=n.interToneGap||null;const r=n.transportType||de.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 nn.InvalidStateError(this._status);if(r!==de.DTMF_TRANSPORT.INFO&&r!==de.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<Mt.C.MIN_DURATION?(J.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?(J.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&&!We.isDecimal(s))throw new TypeError(`Invalid interToneGap: ${s}`);if(s?s<Mt.C.MIN_INTER_TONE_GAP?(J.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===de.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,_.call(this);function _(){let d;if(this._status===te.STATUS_TERMINATED||!this._tones||o>=this._tones.length){this._tones=null;return}const h=this._tones[o];if(o+=1,h===",")d=2e3;else{const m=new Mt(this);n.eventHandlers={onFailed:()=>{this._tones=null}},m.send(h,n),d=a+s}setTimeout(_.bind(this),d)}}sendInfo(t,n,o={}){if(J.debug("sendInfo()"),this._status!==te.STATUS_CONFIRMED&&this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_1XX_RECEIVED)throw new nn.InvalidStateError(this._status);new Zf(this).send(t,n,o)}mute(t={audio:!0,video:!1}){J.debug("mute()");let n=!1,o=!1;this._audioMuted===!1&&t.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(o=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||o===!0)&&this._onmute({audio:n,video:o})}unmute(t={audio:!0,video:!0}){J.debug("unmute()");let n=!1,o=!1;this._audioMuted===!0&&t.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(o=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||o===!0)&&this._onunmute({audio:n,video:o})}hold(t={},n){if(J.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 o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:de.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:t.extraHeaders}),!0}unhold(t={},n){if(J.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 o={succeeded:()=>{n&&n()},failed:()=>{this.terminate({cause:de.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},n){J.debug("renegotiate()");const o=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:de.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,rtcOfferConstraints:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:o,extraHeaders:t.extraHeaders}),!0}refer(t,n){J.debug("refer()");const o=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: ${o}`);const a=new Sm(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 J.debug("sendRequest()"),this._dialog.sendRequest(t,n)}receiveRequest(t){if(J.debug("receiveRequest()"),t.method===de.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,de.causes.CANCELED));else switch(t.method){case de.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:de.causes.MISSING_SDP,status_code:400});break}const n={originator:"remote",type:"answer",sdp:t.body};J.debug('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(a=>{this.terminate({cause:de.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",t);break;case de.BYE:this._status===te.STATUS_CONFIRMED||this._status===te.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,de.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,de.causes.BYE)):t.reply(403,"Wrong Status");break;case de.INVITE:this._status===te.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case de.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 Zf(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case de.UPDATE:this._status===te.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case de.REFER:this._status===te.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case de.NOTIFY:this._status===te.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){J.warn("onTransportError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:de.causes.CONNECTION_ERROR,cause:de.causes.CONNECTION_ERROR})}onRequestTimeout(){J.warn("onRequestTimeout()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:de.causes.REQUEST_TIMEOUT,cause:de.causes.REQUEST_TIMEOUT})}onDialogError(){J.warn("onDialogError()"),this._status!==te.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:de.causes.DIALOG_ERROR,cause:de.causes.DIALOG_ERROR})}newDTMF(t){J.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){J.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){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)}_close(){if(J.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(J.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){J.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 o=zr.T1;function a(){this._status===te.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],n),o<zr.T2&&(o=o*2,o>zr.T2&&(o=zr.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),o))}this._timers.invite2xxTimer=setTimeout(a.bind(this),o)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===te.STATUS_WAITING_FOR_ACK&&(J.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(de.BYE),this._ended("remote",null,de.causes.NO_ACK))},zr.TIMER_H)}_createRTCConnection(t,n){this._connection=new RTCPeerConnection(t,n),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:de.causes.RTP_TIMEOUT,status_code:408,reason_phrase:de.causes.RTP_TIMEOUT})}),J.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,n){if(J.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const o=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?o.createOffer(n).catch(a=>(J.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):o.createAnswer(n).catch(a=>(J.warn('emit "peerconnection:createanswerfailed" [error:%o]',a),this.emit("peerconnection:createanswerfailed",a),Promise.reject(a)))).then(a=>o.setLocalDescription(a).catch(s=>(this._rtcReady=!0,J.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s)))).then(()=>{const a=n&&n.iceRestart;if(o.iceGatheringState==="complete"&&!a||o.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:o.localDescription.sdp};return J.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let r=!1,_,d;this._iceReady=!1;const h=()=>{o.removeEventListener("icecandidate",_),o.removeEventListener("icegatheringstatechange",d),r=!0,this._rtcReady=!0,this._iceReady=!0;const m={originator:"local",type:t,sdp:o.localDescription.sdp};J.debug('emit "sdp"'),this.emit("sdp",m),s(m.sdp)};o.addEventListener("icecandidate",_=m=>{const T=m.candidate;T?this.emit("icecandidate",{candidate:T,ready:h}):r||h()}),o.addEventListener("icegatheringstatechange",d=()=>{o.iceGatheringState==="complete"&&!r&&h()})})})}_createDialog(t,n,o){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 _=this._earlyDialogs[r];if(o)return _?!0:(_=new co(this,t,n,co.C.STATUS_EARLY),_.error?(J.debug(_.error),this._failed("remote",t,de.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=_,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,_)return _.update(t,n),this._dialog=_,delete this._earlyDialogs[r],!0;const d=new co(this,t,n);return d.error?(J.debug(d.error),this._failed("remote",t,de.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(t){J.debug("receiveReinvite()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,o={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(_={}){a=!0;const d=_.status_code||403,h=_.reason_phrase||"",m=We.cloneArray(_.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,h,m)}if(this.emit("reinvite",o),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(_=>{r.call(this,_)}).catch(()=>{t.reply(500)});return}if(n!=="application/sdp"){J.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(_=>{this._status!==te.STATUS_TERMINATED&&r.call(this,_)}).catch(_=>{J.warn(_)});function r(_){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),this._late_sdp&&(_=this._mangleOffer(_)),t.reply(200,null,d,_,()=>{this._status=te.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,_),this._setACKTimer()}),typeof o.callback=="function"&&o.callback()}}_receiveUpdate(t){J.debug("receiveUpdate()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,o={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(_={}){a=!0;const d=_.status_code||403,h=_.reason_phrase||"",m=We.cloneArray(_.extraHeaders);if(this._status!==te.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,h,m)}if(this.emit("update",o),a)return;if(!t.body){r.call(this,null);return}if(n!=="application/sdp"){J.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(_=>{this._status!==te.STATUS_TERMINATED&&r.call(this,_)}).catch(_=>{J.warn(_)});function r(_){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),t.reply(200,null,d,_),typeof o.callback=="function"&&o.callback()}}_processInDialogSdpOffer(t){J.debug("_processInDialogSdpOffer()");const n=t.parseSDP();let o=!1;for(const r of n.media){if(fo.indexOf(r.type)===-1)continue;const _=r.direction||n.direction||"sendrecv";if(_==="sendonly"||_==="inactive")o=!0;else{o=!1;break}}const a={originator:"remote",type:"offer",sdp:t.body};J.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),J.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&&o===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&o===!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),J.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',r),r})}).catch(r=>{J.warn("_processInDialogSdpOffer() failed [error: %o]",r)}),this._connectionPromiseQueue}_receiveRefer(t){if(J.debug("receiveRefer()"),!t.refer_to){J.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==de.SIP){J.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const n=new vm(this,t.cseq);J.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,r)=>{o.call(this,s,r)},reject:()=>{a.call(this)}});function o(s,r={}){if(s=typeof s=="function"?s:null,this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const _=new Ku(this._ua);if(_.on("progress",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),_.on("accepted",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),_.on("_failed",({message:d,cause:h})=>{d?n.notify(d.status_code,d.reason_phrase):n.notify(487,h)}),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}`)}_.connect(t.refer_to.uri.toAor(),r,s)}function a(){n.notify(603)}}_receiveNotify(t){switch(J.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let n,o;if(t.event.params&&t.event.params.id)n=t.event.params.id,o=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)o=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!o){t.reply(481,"Subscription does not exist");return}o.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){J.debug("receiveReplaces()");function n(a){if(this._status!==te.STATUS_WAITING_FOR_ACK&&this._status!==te.STATUS_CONFIRMED)return!1;const s=new Ku(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,a)}function o(){J.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:a=>{n.call(this,a)},reject:()=>{o.call(this)}})}_sendInitialRequest(t,n,o){const a=new Tm(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(o)return o;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,de.causes.USER_DENIED_MEDIA_ACCESS),J.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,de.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,J.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),a.send()}).catch(s=>{this._status!==te.STATUS_TERMINATED&&J.warn(s)})}_getDTMFRTPSender(){const t=this._connection.getSenders().find(n=>n.track&&n.track.kind==="audio");if(!(t&&t.dtmf)){J.warn("sendDTMF() | no local audio track to send DTMF with");return}return t.dtmf}_receiveInviteResponse(t){if(J.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(de.ACK);return}else{const n=new co(this,t,"UAC");if(n.error!==void 0){J.debug(n.error);return}this.sendRequest(de.ACK),this.sendRequest(de.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){J.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};J.debug('emit "sdp"'),this.emit("sdp",n);const o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).then(()=>this._progress("remote",t)).catch(a=>{J.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,de.causes.MISSING_SDP),this._failed("remote",t,de.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const n={originator:"remote",type:"answer",sdp:t.body};J.debug('emit "sdp"'),this.emit("sdp",n);const o=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,de.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(o).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(de.ACK),this._confirmed("local",null)}).catch(a=>{this._acceptAndTerminate(t,488,"Not Acceptable Here"),this._failed("remote",t,de.causes.BAD_MEDIA_DESCRIPTION),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})});break}default:{const n=We.sipErrorCause(t.status_code);this._failed("remote",t,n)}}}_sendReinvite(t={}){J.debug("sendReinvite()");const n=We.cloneArray(t.extraHeaders),o=We.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 h={originator:"local",type:"offer",sdp:d};J.debug('emit "sdp"'),this.emit("sdp",h),this.sendRequest(de.INVITE,{extraHeaders:n,body:d,eventHandlers:{onSuccessResponse:m=>{r.call(this,m),s=!0},onErrorResponse:m=>{_.call(this,m)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_()});function r(d){if(this._status===te.STATUS_TERMINATED||(this.sendRequest(de.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){_.call(this);return}}else{_.call(this);return}const h={originator:"remote",type:"answer",sdp:d.body};J.debug('emit "sdp"'),this.emit("sdp",h);const m=new RTCSessionDescription({type:"answer",sdp:h.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(m)).then(()=>{o.succeeded&&o.succeeded(d)}).catch(T=>{_.call(this),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function _(d){o.failed&&o.failed(d)}}_sendUpdate(t={}){J.debug("sendUpdate()");const n=We.cloneArray(t.extraHeaders),o=We.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(h=>{h=this._mangleOffer(h);const m={originator:"local",type:"offer",sdp:h};J.debug('emit "sdp"'),this.emit("sdp",m),this.sendRequest(de.UPDATE,{extraHeaders:n,body:h,eventHandlers:{onSuccessResponse:T=>{_.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(de.UPDATE,{extraHeaders:n,eventHandlers:{onSuccessResponse:h=>{_.call(this,h)},onErrorResponse:h=>{d.call(this,h)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function _(h){if(this._status!==te.STATUS_TERMINATED&&!r)if(this._handleSessionTimersInIncomingResponse(h),s){if(h.body){if(!h.hasHeader("Content-Type")||h.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const m={originator:"remote",type:"answer",sdp:h.body};J.debug('emit "sdp"'),this.emit("sdp",m);const T=new RTCSessionDescription({type:"answer",sdp:m.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(T)).then(()=>{o.succeeded&&o.succeeded(h)}).catch(S=>{d.call(this),J.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),this.emit("peerconnection:setremotedescriptionfailed",S)})}else o.succeeded&&o.succeeded(h)}function d(h){o.failed&&o.failed(h)}}_acceptAndTerminate(t,n,o){J.debug("acceptAndTerminate()");const a=[];n&&(o=o||de.REASON_PHRASE[n]||"",a.push(`Reason: SIP ;cause=${n}; text="${o}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(de.ACK),this.sendRequest(de.BYE,{extraHeaders:a})),this._status=te.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=Xf.parse(t),this._localHold&&!this._remoteHold){J.debug("mangleOffer() | me on hold, mangling offer");for(const n of t.media)fo.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){J.debug("mangleOffer() | both on hold, mangling offer");for(const n of t.media)fo.indexOf(n.type)!==-1&&(n.direction="inactive")}else if(this._remoteHold){J.debug("mangleOffer() | remote on hold, mangling offer");for(const n of t.media)fo.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="recvonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="recvonly")}return Xf.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 o;t.session_expires&&t.session_expires>=de.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,o=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,o="uas"),n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${o}`),this._sessionTimers.refresher=o==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let n;t.session_expires&&t.session_expires>=de.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()&&(J.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===de.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==te.STATUS_TERMINATED&&(J.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:de.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="audio");for(const o of n)o.track.enabled=!t}_toggleMuteVideo(t){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="video");for(const o of n)o.track.enabled=!t}_newRTCSession(t,n){J.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:t,session:this,request:n})}_connecting(t){J.debug("session connecting"),J.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,n){J.debug("session progress"),J.debug('emit "progress"'),this.emit("progress",{originator:t,response:n||null})}_accepted(t,n){J.debug("session accepted"),this._start_time=new Date,J.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:n||null})}_confirmed(t,n){J.debug("session confirmed"),this._is_confirmed=!0,J.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:n||null})}_ended(t,n,o){J.debug("session ended"),this._end_time=new Date,this._close(),J.debug('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:o})}_failed(t,n,o){J.debug("session failed"),J.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:n||null,cause:o}),this._close(),J.debug('emit "failed"'),this.emit("failed",{originator:t,message:n||null,cause:o})}_onhold(t){J.debug("session onhold"),this._setLocalMediaStatus(),J.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){J.debug("session onunhold"),this._setLocalMediaStatus(),J.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:n}){J.debug("session onmute"),this._setLocalMediaStatus(),J.debug('emit "muted"'),this.emit("muted",{audio:t,video:n})}_onunmute({audio:t,video:n}){J.debug("session onunmute"),this._setLocalMediaStatus(),J.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:n})}};const Em=Me(td),ym=ct.EventEmitter,Cm=ot,lu=De,Am=Tt,Xr=gt(),Rm=Hn,sd=Ts,bm=ps(),ho=new Cm("Message");var Im=class extends ym{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,o={}){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=Xr.cloneArray(o.extraHeaders),r=Xr.cloneObject(o.eventHandlers),_=o.contentType||"text/plain",d={};o.fromUserName&&(d.from_uri=new bm("sip",o.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),o.fromDisplayName&&(d.from_display_name=o.fromDisplayName);for(const m in r)Object.prototype.hasOwnProperty.call(r,m)&&this.on(m,r[m]);s.push(`Content-Type: ${_}`),this._request=new Am.OutgoingRequest(lu.MESSAGE,t,this._ua,d,s),n&&(this._request.body=n);const h=new Rm(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:m=>{this._receiveResponse(m)}});this._newMessage("local",this._request),h.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=Xr.cloneArray(t.extraHeaders),o=t.body;if(this._direction!=="incoming")throw new sd.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,o)}reject(t={}){const n=t.status_code||480,o=t.reason_phrase,a=Xr.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new sd.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,o,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=Xr.sipErrorCause(t.status_code);this._failed("remote",t,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,lu.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,lu.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,o){ho.debug("MESSAGE failed"),this._close(),ho.debug('emit "failed"'),this.emit("failed",{originator:t,response:n||null,cause:o})}_succeeded(t,n){ho.debug("MESSAGE succeeded"),this._close(),ho.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:n})}};const wm=ct.EventEmitter,Om=ot,ou=De,Dm=Tt,Qr=gt(),Nm=Hn,nd=Ts,_o=new Om("Options");var xm=class extends wm{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,o={}){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=Qr.cloneArray(o.extraHeaders),r=Qr.cloneObject(o.eventHandlers),_=o.contentType||"application/sdp";for(const h in r)Object.prototype.hasOwnProperty.call(r,h)&&this.on(h,r[h]);s.push(`Content-Type: ${_}`),this._request=new Dm.OutgoingRequest(ou.OPTIONS,t,this._ua,null,s),n&&(this._request.body=n);const d=new Nm(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:h=>{this._receiveResponse(h)}});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=Qr.cloneArray(t.extraHeaders),o=t.body;if(this._direction!=="incoming")throw new nd.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,o)}reject(t={}){const n=t.status_code||480,o=t.reason_phrase,a=Qr.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new nd.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,o,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=Qr.sipErrorCause(t.status_code);this._failed("remote",t,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,ou.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,ou.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,o){_o.debug("OPTIONS failed"),this._close(),_o.debug('emit "failed"'),this.emit("failed",{originator:t,response:n||null,cause:o})}_succeeded(t,n){_o.debug("OPTIONS succeeded"),this._close(),_o.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:n})}},au={};const Um=ot,uu=gt(),km=Yt(),Zr=new Um("Socket");au.isSocket=c=>{if(Array.isArray(c))return!1;if(typeof c>"u")return Zr.warn("undefined JsSIP.Socket instance"),!1;try{if(!uu.isString(c.url))throw Zr.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!uu.isString(c.via_transport))throw Zr.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(km.parse(c.sip_uri,"SIP_URI")===-1)throw Zr.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(!uu.isFunction(c[t]))throw Zr.warn(`missing or invalid JsSIP.Socket method: ${t}`),new Error(`Missing or invalid JsSIP.Socket method: ${t}`)})}catch{return!1}return!0};const Pm=ot,Mm=au,rd=De,Ut=new Pm("Transport"),Ft={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:rd.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:rd.CONNECTION_RECOVERY_MAX_INTERVAL}};var id=class{constructor(t,n=Ft.recovery_options){Ut.debug("new()"),this.status=Ft.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(o){Ut.warn(`cannot use TextDecoder: ${o}`)}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(o){if(!Mm.isSocket(o.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(o.weight&&!Number(o.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:o.socket,weight:o.weight||0,status:Ft.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=Ft.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=Ft.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 n=t.toString();return Ut.debug(`sending message:
116
116
 
117
117
  ${n}
118
118
  `),this.socket.send(n)}isConnected(){return this.status===Ft.STATUS_CONNECTED}isConnecting(){return this.status===Ft.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(o=>{o.status!==Ft.SOCKET_STATUS_ERROR&&(t.length===0?t.push(o):o.weight>t[0].weight?t=[o]:o.weight===t[0].weight&&t.push(o))}),t.length===0){this.sockets.forEach(o=>{o.status=Ft.SOCKET_STATUS_READY}),this._getSocket();return}const n=Math.floor(Math.random()*t.length);this.socket=t[n].socket}_onConnect(){this.recover_attempts=0,this.status=Ft.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}_onDisconnect(t,n,o){this.status=Ft.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:t,code:n,reason:o}),!this.close_requested&&(this.sockets.forEach(function(a){this.socket===a.socket&&(a.status=Ft.SOCKET_STATUS_ERROR)},this),this._reconnect(t))}_onData(t){if(t===`\r
@@ -122,17 +122,17 @@ ${t}
122
122
  `)}else Ut.debug(`received text message:
123
123
 
124
124
  ${t}
125
- `);this.ondata({transport:this,message:t})}};const Lg=Me(id);var ld={};const $g=ot,cu=Yt(),fu=Tt,po=new $g("Parser");ld.parseMessage=(c,t)=>{let n,o,a=c.indexOf(`\r
126
- `);if(a===-1){po.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=c.substring(0,a);let r=cu.parse(s,"Request_Response");if(r===-1){po.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else r.status_code?(n=new fu.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new fu.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;let _=a+2;for(;;){if(a=Hg(c,_),a===-2){o=_+2;break}else if(a===-1){po.warn("parseMessage() | malformed message");return}if(r=Fg(n,c,_,a),r!==!0){po.warn("parseMessage() |",r.error);return}_=a+2}if(n.hasHeader("content-length")){const d=n.getHeader("content-length");n.body=c.substr(o,d)}else n.body=c.substring(o);return n};function Hg(c,t){let n=t,o=0,a=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;o===0;){if(a=c.indexOf(`\r
127
- `,n),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?n=a+2:o=a}return o}function Fg(c,t,n,o){let a;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),_=t.substring(s+1,o).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",_),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",_),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",_),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=cu.parse(_,"Record_Route"),a===-1)a=void 0;else for(const d of a)c.addHeader("record-route",_.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",_),a=c.parseHeader("call-id"),a&&(c.call_id=_);break;case"contact":case"m":if(a=cu.parse(_,"Contact"),a===-1)a=void 0;else for(const d of a)c.addHeader("contact",_.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",_),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",_),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",_),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof fu.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",_),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",_),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",_),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",_),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",_),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",_),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",_),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,_),a=0}return a===void 0?{error:`error parsing header "${r}"`}:!0}const Vg=ot,od=De,ad=Tt,du=mt(),hu=new Vg("sanityCheck"),jg=[Xg],qg=[Gg,Wg,Kg,Yg],Bg=[Jg,zg];let Ve,is,ud;var cd=(c,t,n)=>{Ve=c,is=t,ud=n;for(const o of jg)if(o()===!1)return!1;if(Ve instanceof ad.IncomingRequest){for(const o of qg)if(o()===!1)return!1}else if(Ve instanceof ad.IncomingResponse){for(const o of Bg)if(o()===!1)return!1}return!0};function Gg(){if(Ve.s("to").uri.scheme!=="sip")return ei(416),!1}function Wg(){if(!Ve.to_tag&&Ve.call_id.substr(0,5)===is.configuration.jssip_id)return ei(482),!1}function Kg(){const c=du.str_utf8_length(Ve.body),t=Ve.getHeader("content-length");if(c<t)return ei(400),!1}function Yg(){const c=Ve.from_tag,t=Ve.call_id,n=Ve.cseq;let o;if(!Ve.to_tag)if(Ve.method===od.INVITE){if(is._transactions.ist[Ve.via_branch])return!1;for(const a in is._transactions.ist)if(Object.prototype.hasOwnProperty.call(is._transactions.ist,a)&&(o=is._transactions.ist[a],o.request.from_tag===c&&o.request.call_id===t&&o.request.cseq===n))return ei(482),!1}else{if(is._transactions.nist[Ve.via_branch])return!1;for(const a in is._transactions.nist)if(Object.prototype.hasOwnProperty.call(is._transactions.nist,a)&&(o=is._transactions.nist[a],o.request.from_tag===c&&o.request.call_id===t&&o.request.cseq===n))return ei(482),!1}}function Jg(){if(Ve.getHeaders("via").length>1)return hu.debug("more than one Via header field present in the response, dropping the response"),!1}function zg(){const c=du.str_utf8_length(Ve.body),t=Ve.getHeader("content-length");if(c<t)return hu.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function Xg(){const c=["from","to","call_id","cseq","via"];for(const t of c)if(!Ve.hasHeader(t))return hu.debug(`missing mandatory header field : ${t}, dropping the response`),!1}function ei(c){const t=Ve.getHeaders("via");let n,o=`SIP/2.0 ${c} ${od.REASON_PHRASE[c]}\r
125
+ `);this.ondata({transport:this,message:t})}};const Lm=Me(id);var ld={};const $m=ot,cu=Yt(),fu=Tt,po=new $m("Parser");ld.parseMessage=(c,t)=>{let n,o,a=c.indexOf(`\r
126
+ `);if(a===-1){po.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=c.substring(0,a);let r=cu.parse(s,"Request_Response");if(r===-1){po.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else r.status_code?(n=new fu.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new fu.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;let _=a+2;for(;;){if(a=Hm(c,_),a===-2){o=_+2;break}else if(a===-1){po.warn("parseMessage() | malformed message");return}if(r=Fm(n,c,_,a),r!==!0){po.warn("parseMessage() |",r.error);return}_=a+2}if(n.hasHeader("content-length")){const d=n.getHeader("content-length");n.body=c.substr(o,d)}else n.body=c.substring(o);return n};function Hm(c,t){let n=t,o=0,a=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;o===0;){if(a=c.indexOf(`\r
127
+ `,n),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?n=a+2:o=a}return o}function Fm(c,t,n,o){let a;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),_=t.substring(s+1,o).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",_),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",_),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",_),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=cu.parse(_,"Record_Route"),a===-1)a=void 0;else for(const d of a)c.addHeader("record-route",_.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",_),a=c.parseHeader("call-id"),a&&(c.call_id=_);break;case"contact":case"m":if(a=cu.parse(_,"Contact"),a===-1)a=void 0;else for(const d of a)c.addHeader("contact",_.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",_),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",_),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",_),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof fu.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",_),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",_),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",_),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",_),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",_),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",_),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",_),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,_),a=0}return a===void 0?{error:`error parsing header "${r}"`}:!0}const Vm=ot,od=De,ad=Tt,du=gt(),hu=new Vm("sanityCheck"),jm=[Xm],qm=[Gm,Wm,Km,Ym],Bm=[Jm,zm];let Ve,is,ud;var cd=(c,t,n)=>{Ve=c,is=t,ud=n;for(const o of jm)if(o()===!1)return!1;if(Ve instanceof ad.IncomingRequest){for(const o of qm)if(o()===!1)return!1}else if(Ve instanceof ad.IncomingResponse){for(const o of Bm)if(o()===!1)return!1}return!0};function Gm(){if(Ve.s("to").uri.scheme!=="sip")return ei(416),!1}function Wm(){if(!Ve.to_tag&&Ve.call_id.substr(0,5)===is.configuration.jssip_id)return ei(482),!1}function Km(){const c=du.str_utf8_length(Ve.body),t=Ve.getHeader("content-length");if(c<t)return ei(400),!1}function Ym(){const c=Ve.from_tag,t=Ve.call_id,n=Ve.cseq;let o;if(!Ve.to_tag)if(Ve.method===od.INVITE){if(is._transactions.ist[Ve.via_branch])return!1;for(const a in is._transactions.ist)if(Object.prototype.hasOwnProperty.call(is._transactions.ist,a)&&(o=is._transactions.ist[a],o.request.from_tag===c&&o.request.call_id===t&&o.request.cseq===n))return ei(482),!1}else{if(is._transactions.nist[Ve.via_branch])return!1;for(const a in is._transactions.nist)if(Object.prototype.hasOwnProperty.call(is._transactions.nist,a)&&(o=is._transactions.nist[a],o.request.from_tag===c&&o.request.call_id===t&&o.request.cseq===n))return ei(482),!1}}function Jm(){if(Ve.getHeaders("via").length>1)return hu.debug("more than one Via header field present in the response, dropping the response"),!1}function zm(){const c=du.str_utf8_length(Ve.body),t=Ve.getHeader("content-length");if(c<t)return hu.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function Xm(){const c=["from","to","call_id","cseq","via"];for(const t of c)if(!Ve.hasHeader(t))return hu.debug(`missing mandatory header field : ${t}, dropping the response`),!1}function ei(c){const t=Ve.getHeaders("via");let n,o=`SIP/2.0 ${c} ${od.REASON_PHRASE[c]}\r
128
128
  `;for(const a of t)o+=`Via: ${a}\r
129
129
  `;n=Ve.getHeader("To"),Ve.to_tag||(n+=`;tag=${du.newTag()}`),o+=`To: ${n}\r
130
130
  `,o+=`From: ${Ve.getHeader("From")}\r
131
131
  `,o+=`Call-ID: ${Ve.call_id}\r
132
132
  `,o+=`CSeq: ${Ve.cseq} ${Ve.method}\r
133
133
  `,o+=`\r
134
- `,ud.send(o)}const Qg=Me(cd);var ti={};const Fn=mt(),rn=De,_u=Yt(),fd=ps(),pu=au,mu=Ts;ti.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:rn.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:rn.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:rn.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${Fn.createRandomToken(12)}.invalid`};const mo={mandatory:{sockets(c){const t=[];if(pu.isSocket(c))t.push({socket:c});else if(Array.isArray(c)&&c.length)for(const n of c)Object.prototype.hasOwnProperty.call(n,"socket")&&pu.isSocket(n.socket)?t.push(n):pu.isSocket(n)&&t.push({socket:n});else return;return t},uri(c){/^sip:/i.test(c)||(c=`${rn.SIP}:${c}`);const t=fd.parse(c);if(t)return t.user?t:void 0}},optional:{authorization_user(c){if(_u.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(Fn.isDecimal(c)){const t=Number(c);if(t>0)return t}},connection_recovery_min_interval(c){if(Fn.isDecimal(c)){const t=Number(c);if(t>0)return t}},contact_uri(c){if(typeof c=="string"){const t=_u.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)),_u.parse(c,"uuid")!==-1)return c},no_answer_timeout(c){if(Fn.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===rn.INVITE||c===rn.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(Fn.isDecimal(c)){const t=Number(c);if(t>0)return t}},registrar_server(c){/^sip:/i.test(c)||(c=`${rn.SIP}:${c}`);const t=fd.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}}};ti.load=(c,t)=>{for(const n in mo.mandatory)if(t.hasOwnProperty(n)){const o=t[n],a=mo.mandatory[n](o);if(a!==void 0)c[n]=a;else throw new mu.ConfigurationError(n,o)}else throw new mu.ConfigurationError(n);for(const n in mo.optional)if(t.hasOwnProperty(n)){const o=t[n];if(Fn.isEmpty(o))continue;const a=mo.optional[n](o);if(a!==void 0)c[n]=a;else throw new mu.ConfigurationError(n,o)}};const Zg=ct.EventEmitter,eT=ot,vt=De,tT=qm,dd=td,hd=Ig,_d=xg,gu=$n,sT=id,go=mt(),nT=Ts,rT=ps(),iT=ld,Tu=Tt,lT=cd,vu=ti,Be=new eT("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 Zg{static get C(){return St}constructor(t){if(Be.debug("new() [configuration:%o]",t),super(),this._cache={credentials:{}},this._configuration=Object.assign({},vu.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(n){throw this._status=St.STATUS_NOT_READY,this._error=St.CONFIGURATION_ERROR,n}this._registrator=new tT(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,n){Be.debug("call()");const o=new dd(this);return o.connect(t,n),o}sendMessage(t,n,o){Be.debug("sendMessage()");const a=new hd(this);return a.send(t,n,o),a}sendOptions(t,n,o){Be.debug("sendOptions()");const a=new _d(this);return a.send(t,n,o),a}terminateSessions(t){Be.debug("terminateSessions()");for(const n in this._sessions)this._sessions[n].isEnded()||this._sessions[n].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 o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){Be.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch{}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].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 go.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,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 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,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){Be.debug("Request-URI does not point to us"),t.method!==vt.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===vt.SIPS){t.reply_sl(416);return}if(gu.checkTransaction(this,t))return;if(n===vt.INVITE?new gu.InviteServerTransaction(this,this._transport,t):n!==vt.ACK&&n!==vt.CANCEL&&new gu.NonInviteServerTransaction(this,this._transport,t),n===vt.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new _d(this).init_incoming(t)}else if(n===vt.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new hd(this).init_incoming(t)}else if(n===vt.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let o,a;if(t.to_tag)o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?o.receiveRequest(t):n===vt.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"))):n!==vt.ACK&&t.reply(481);else switch(n){case vt.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const s=t.replaces;o=this._findDialog(s.call_id,s.from_tag,s.to_tag),o?(a=o.owner,a.isEnded()?t.reply(603):a.receiveRequest(t)):t.reply(481)}else a=new dd(this),a.init_incoming(t);else Be.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case vt.BYE:t.reply(481);break;case vt.CANCEL:a=this._findSession(t),a?a.receiveRequest(t):Be.debug("received CANCEL request for a non existent session");break;case vt.ACK:break;case vt.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:o}){const a=t+n,s=this._sessions[a],r=t+o,_=this._sessions[r];return s||_||null}_findDialog(t,n,o){let a=t+n+o,s=this._dialogs[a];return s||(a=t+o+n,s=this._dialogs[a],s||null)}_loadConfig(t){try{vu.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=go.newUUID()),this._configuration.jssip_id=go.createRandomToken(5);const n=this._configuration.uri.clone();n.user=null,this._configuration.hostport_params=n.toString().replace(/^sip:/i,"");try{this._transport=new sT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=oT.bind(this),this._transport.onconnect=aT.bind(this),this._transport.ondisconnect=uT.bind(this),this._transport.ondata=cT.bind(this)}catch(a){throw Be.warn(a),new nT.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 rT("sip",go.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 _="<";return s?_+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":_+=this.pub_gruu||this.uri.toString(),r&&(s?!this.temp_gruu:!this.pub_gruu)&&(_+=";ob"),_+=">",_}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(o.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(vu.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 oT(c){this.emit("connecting",c)}function aT(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 uT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const o in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],o)&&this._transactions[n][o].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 cT(c){const t=c.transport;let n=c.message;if(n=iT.parseMessage(n,this),!!n&&!(this._status===St.STATUS_USER_CLOSED&&n instanceof Tu.IncomingRequest)&&lT(n,this,t)){if(n instanceof Tu.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Tu.IncomingResponse){let o;switch(n.method){case vt.INVITE:o=this._transactions.ict[n.via_branch],o&&o.receiveResponse(n);break;case vt.ACK:break;default:o=this._transactions.nict[n.via_branch],o&&o.receiveResponse(n);break}}}}const fT=Me(pd);for(var Et=[],Su=0;Su<256;++Su)Et.push((Su+256).toString(16).slice(1));function dT(c,t=0){return(Et[c[t+0]]+Et[c[t+1]]+Et[c[t+2]]+Et[c[t+3]]+"-"+Et[c[t+4]]+Et[c[t+5]]+"-"+Et[c[t+6]]+Et[c[t+7]]+"-"+Et[c[t+8]]+Et[c[t+9]]+"-"+Et[c[t+10]]+Et[c[t+11]]+Et[c[t+12]]+Et[c[t+13]]+Et[c[t+14]]+Et[c[t+15]]).toLowerCase()}var To,hT=new Uint8Array(16);function _T(){if(!To&&(To=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!To))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return To(hT)}var pT=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const md={randomUUID:pT};function gd(c,t,n){if(md.randomUUID&&!t&&!c)return md.randomUUID();c=c||{};var o=c.random||(c.rng||_T)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,t){n=n||0;for(var a=0;a<16;++a)t[n+a]=o[a];return t}return dT(o)}var ke=mt();const vs=Me(ke),Eu=new no("Dialog"),ks={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class vo{static get C(){return ks}constructor(t,n,o,a=ks.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,n instanceof Tt.IncomingResponse&&(a=n.status_code<200?ks.STATUS_EARLY:ks.STATUS_CONFIRMED),o==="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(o==="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),Eu.debug(`new ${o} dialog created with status ${this._state===ks.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===ks.STATUS_TERMINATED}update(t,n){this._state=ks.STATUS_CONFIRMED,Eu.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){Eu.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=ks.STATUS_TERMINATED}sendRequest(t,n={}){const o=vs.cloneArray(n.extraHeaders),a=vs.cloneObject(n.eventHandlers),s=n.body||null,r=this._createRequest(t,o,s);return a.onAuthenticated=()=>{this._local_seqnum+=1},new Jm(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,o){n=vs.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 Tt.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,o)}_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===Ht.C.STATUS_ACCEPTED||t.server_transaction.state===Ht.C.STATUS_COMPLETED||t.server_transaction.state===Ht.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===Ht.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===Ht.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}}class mT{constructor(t,n){es(this,"plugin",null);es(this,"rtcpPeer",null);es(this,"handleId",0);es(this,"info",null);es(this,"joinResult",null);es(this,"state",{});es(this,"stream",null);es(this,"loaded",!1);es(this,"aTracks",[]);es(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,_,d;const n=(r=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:r.newStatePublisher,a=((d=(_=t==null?void 0:t.plugindata)==null?void 0:_.data)==null?void 0:d.publisher_state).find(h=>h.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 zt{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(t){return zt.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(o=>o.kind===t):[]}static async getMicrophoneList(){return(await zt.getDevices("audioinput")).map((n,o)=>({...n,deviceId:n.deviceId,label:n.label||`microphone ${o+1}`,kind:n.kind,groupId:n.groupId}))}static async getSpeakerList(){return(await zt.getDevices("audiooutput")).map((n,o)=>({...n,deviceId:n.deviceId,label:n.label||`speaker ${o+1}`,kind:n.kind,groupId:n.groupId}))}static async getCameraList(){return(await zt.getDevices("videoinput")).map((n,o)=>({...n,deviceId:n.deviceId,label:n.label||`camera ${o+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 o,a;t==="default"?o=!0:t&&t!=="default"&&(o={deviceId:{exact:t}}),n==="default"?a=!0:n&&n!=="default"&&(a={deviceId:{exact:n}});const s={audio:a,video:o};return zt.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(o){let a=o;o.name==="SecurityError"&&(a=`You need to use HTTPS for selecting audio output device: ${o}`),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(o=>{o.enabled=!o.enabled}),n[0].enabled}static toggleVideoMute(t){const n=t.getVideoTracks();if(n.length!==0)return n.forEach(o=>{o.enabled=!o.enabled}),n[0].enabled}static async getStream(t={video:!0,audio:!0}){try{const n=await navigator.mediaDevices.getUserMedia(t);let o=n.getTracks();return t.video?o=n.getVideoTracks():t.audio&&(o=n.getAudioTracks()),o.length===0?{stream:n,track:null}:{stream:n,track:o[0]}}catch(n){return console.warn(n),{stream:null,track:null}}}}var gT=ps();const ln=Me(gT),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 no("JanusSession"),TT="/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},So=["audio","video"];class Eo extends ct.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-${gd().replace(/-/g,"").slice(0,12)}`}connect(t,n,o={},a){Z.debug("connect()"),this.display_name=n;const s=t,r=ke.cloneObject(o.eventHandlers),_=ke.cloneArray(o.extraHeaders),d=ke.cloneObject(o.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={...d};const h=o.mediaStream||null,g=ke.cloneObject(o.pcConfig,{iceServers:[]}),T=o.rtcConstraints||null,S=o.rtcOfferConstraints||null;if(this._rtcOfferConstraints=S,this._rtcAnswerConstraints=o.rtcAnswerConstraints||null,this._data=o.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==se.STATUS_NULL)throw new Ns.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Ns.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&&ke.isDecimal(o.sessionTimersExpires)&&(o.sessionTimersExpires>=$.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=o.sessionTimersExpires:this._sessionTimers.defaultExpires=$.SESSION_EXPIRES);for(const R in r)Object.prototype.hasOwnProperty.call(r,R)&&this.on(R,r[R]);this._from_tag=ke.newTag();const E=o.anonymous||!1,A={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:E,outbound:!0}),E?(A.from_display_name="Anonymous",A.from_uri=new ln("sip","anonymous","anonymous.invalid"),_.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),_.push("Privacy: id")):o.fromUserName&&(A.from_uri=new ln("sip",o.fromUserName,this._ua.configuration.uri.host),_.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),o.fromDisplayName&&(A.from_display_name=o.fromDisplayName),_.push(`Contact: ${this._contact}`),_.push("Content-Type: application/json"),this._sessionTimers.enabled&&_.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Tt.InitialOutgoingInviteRequest(t,this._ua,A,_),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,h)}_overrideSenderTracks(t,n){t.getTracks().forEach(o=>{n.getSenders().forEach(async s=>{s.track.kind===o.kind&&(o.kind==="audio"&&!this.isAudioOn&&(o.enabled=!1),o.kind==="video"&&!this.isVideoOn&&(o.enabled=!1),await s.replaceTrack(o))})})}init_incoming(t,n){Z.debug("init_incoming()");let o;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")&&(o=t.getHeader("expires")*1e3),t.to_tag=ke.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),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===se.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,$.causes.EXPIRES))},o)),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,o=ke.cloneArray(t.extraHeaders),a=ke.cloneObject(t.mediaConstraints),s=t.mediaStream||null,r=ke.cloneObject(t.pcConfig,{iceServers:[]}),_=t.rtcConstraints||null,d=t.rtcAnswerConstraints||null,h=ke.cloneObject(t.rtcOfferConstraints);let g,T=!1,S=!1,E=!1,A=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new Ns.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==se.STATUS_WAITING_FOR_ANSWER)throw new Ns.InvalidStateError(this._status);if(this._sessionTimers.enabled&&ke.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),o.unshift(`Contact: ${this._contact}`);const R=n.parseSDP();Array.isArray(R.media)||(R.media=[R.media]);for(const C of R.media)C.type==="audio"&&(T=!0,(!C.direction||C.direction==="sendrecv")&&(E=!0)),C.type==="video"&&(S=!0,(!C.direction||C.direction==="sendrecv")&&(A=!0));if(s&&a.audio===!1){g=s.getAudioTracks();for(const C of g)s.removeTrack(C)}if(s&&a.video===!1){g=s.getVideoTracks();for(const C of g)s.removeTrack(C)}!s&&a.audio===void 0&&(a.audio=E),!s&&a.video===void 0&&(a.video=A),!s&&!T&&!h.offerToReceiveAudio&&(a.audio=!1),!s&&!S&&!h.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(r,_),Promise.resolve().then(()=>{if(s)return s;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(C=>{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]',C),this.emit("getusermediafailed",C),new Error("getUserMedia() failed"))})}).then(C=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=C,C&&C.getTracks().forEach(H=>{this._connection.addTrack(H,C)})}).then(()=>{if(this._late_sdp)return;const C={originator:"remote",type:"offer",sdp:n.body};Z.debug('emit "sdp"'),this.emit("sdp",C);const H=new RTCSessionDescription({type:"offer",sdp:C.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(H)).catch(k=>{throw n.reply(488),this._failed("system",null,$.causes.WEBRTC_ERROR),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',k),this.emit("peerconnection:setremotedescriptionfailed",k),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(C=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,o),n.reply(200,null,o,C,()=>{this._status=se.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,C),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,$.causes.CONNECTION_ERROR)})}).catch(C=>{this._status!==se.STATUS_TERMINATED&&Z.warn(C)})}terminate(t={}){Z.debug("terminate()");const n=t.cause||$.causes.BYE,o=ke.cloneArray(t.extraHeaders),a=t.body;let s,r=t.status_code,_=t.reason_phrase;if(this._status===se.STATUS_TERMINATED)throw new Ns.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&&(_=_||$.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${_}"`),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,_,o,a),this._failed("local",null,$.causes.REJECTED);break;case se.STATUS_WAITING_FOR_ACK:case se.STATUS_CONFIRMED:if(Z.debug("terminating session"),_=t.reason_phrase||$.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&o.push(`Reason: SIP ;cause=${r}; text="${_}"`),this._status===se.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ht.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:h})=>{h===$.ACK&&(this.sendRequest($.BYE,{extraHeaders:o,body:a}),d.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ht.C.STATUS_TERMINATED&&(this.sendRequest($.BYE,{extraHeaders:o,body:a}),d.terminate(),this.closeSession())}),this._ended("local",null,n),this._dialog=d,this._ua.newDialog(d)}else{const d={janus:"leave"},h=["Content-Type: application/json",this.getPTypeHeader(kt.LEAVE)];this.sendRequest($.BYE,{extraHeaders:h,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},o=["Content-Type: application/json",this.getPTypeHeader(kt.AUDIO_CHANGE)];this.sendRequest($.INFO,{extraHeaders:o,body:JSON.stringify(n),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 n={janus:"message",body:{video:t},handle_id:this.handle_id,session_id:this.session_id},o=["Content-Type: application/json",this.getPTypeHeader(kt.VIDEO_CHANGE)];this.sendRequest($.INFO,{extraHeaders:o,body:JSON.stringify(n),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 n={janus:"message",body:{request:"state",data:t},handle_id:this.handle_id,session_id:this.session_id},o=["Content-Type: application/json",this.getPTypeHeader(kt.STATE)];this.sendRequest($.INFO,{extraHeaders:o,body:JSON.stringify(n)})}sendInfo(t,n,o={}){if(Z.debug("sendInfo()"),this._status!==se.STATUS_CONFIRMED&&this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_1XX_RECEIVED)throw new Ns.InvalidStateError(this._status);new ru(this).send(t,n,o)}mute(t={audio:!0,video:!1}){Z.debug("mute()");let n=!1,o=!1;this._audioMuted===!1&&t.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(o=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||o===!0)&&this._onmute({audio:n,video:o})}unmute(t={audio:!0,video:!0}){Z.debug("unmute()");let n=!1,o=!1;this._audioMuted===!0&&t.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(o=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||o===!0)&&this._onunmute({audio:n,video:o})}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 o={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:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,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 o={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:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},n){Z.debug("renegotiate()");const o=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:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:o,extraHeaders:t.extraHeaders}),!0}refer(t,n){Z.debug("refer()");const o=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: ${o}`);const a=new _g(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 o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).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 ng(this).init_incoming(t):n!==void 0?new ru(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"),ke.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 o=jr.T1;function a(){this._status===se.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],n),o<jr.T2&&(o=o*2,o>jr.T2&&(o=jr.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),o))}this._timers.invite2xxTimer=setTimeout(a.bind(this),o)}_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))},jr.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 o;const a=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(o),o=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 o=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?o.createOffer(n).catch(a=>(Z.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):o.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,o.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(o.iceGatheringState==="complete"&&!a||o.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:o.localDescription.sdp};return Z.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let r=!1,_,d;this._iceReady=!1;const h=()=>{o.removeEventListener("icecandidate",_),o.removeEventListener("icegatheringstatechange",d),r=!0,this._rtcReady=!0,this._iceReady=!0;const g={originator:"local",type:t,sdp:o.localDescription.sdp};Z.debug('emit "sdp"'),this.emit("sdp",g),s(g.sdp)};o.addEventListener("icecandidate",_=g=>{const T=g.candidate;T?this.emit("icecandidate",{candidate:T,ready:h}):r||h()}),o.addEventListener("icegatheringstatechange",d=()=>{o.iceGatheringState==="complete"&&!r&&h()})})})}_createDialog(t,n,o){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 _=this._earlyDialogs[r];if(o)return _?!0:(_=new vo(this,t,n,vo.C.STATUS_EARLY),_.error?(Z.debug(_.error),this._failed("remote",t,$.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=_,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,_)return _.update(t,n),this._dialog=_,delete this._earlyDialogs[r],!0;const d=new vo(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,o={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(_={}){a=!0;const d=_.status_code||403,h=_.reason_phrase||"",g=ke.cloneArray(_.extraHeaders);if(this._status!==se.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,h,g)}if(this.emit("reinvite",o),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(_=>{r.call(this,_)}).catch(()=>{t.reply(500)});return}if(n!=="application/sdp"){Z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(_=>{this._status!==se.STATUS_TERMINATED&&r.call(this,_)}).catch(_=>{Z.warn(_)});function r(_){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),this._late_sdp&&(_=this._mangleOffer(_)),t.reply(200,null,d,_,()=>{this._status=se.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,_),this._setACKTimer()}),typeof o.callback=="function"&&o.callback()}}_receiveUpdate(t){Z.debug("receiveUpdate()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,o={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(_={}){a=!0;const d=_.status_code||403,h=_.reason_phrase||"",g=ke.cloneArray(_.extraHeaders);if(this._status!==se.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,h,g)}if(this.emit("update",o),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(_=>{this._status!==se.STATUS_TERMINATED&&r.call(this,_)}).catch(_=>{Z.warn(_)});function r(_){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),t.reply(200,null,d,_),typeof o.callback=="function"&&o.callback()}}_processInDialogSdpOffer(t){Z.debug("_processInDialogSdpOffer()");const n=t.parseSDP();let o=!1;for(const r of n.media){if(So.indexOf(r.type)===-1)continue;const _=r.direction||n.direction||"sendrecv";if(_==="sendonly"||_==="inactive")o=!0;else{o=!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&&o===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&o===!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 cg(this,t.cseq);Z.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,r)=>{o.call(this,s,r)},reject:()=>{a.call(this)}});function o(s,r={}){if(s=typeof s=="function"?s:null,this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED)return!1;const _=new Eo(this._ua);if(_.on("progress",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),_.on("accepted",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),_.on("_failed",({message:d,cause:h})=>{d?n.notify(d.status_code,d.reason_phrase):n.notify(487,h)}),t.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));r.extraHeaders=ke.cloneArray(r.extraHeaders),r.extraHeaders.push(`Replaces: ${d}`)}_.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,o;if(t.event.params&&t.event.params.id)n=t.event.params.id,o=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)o=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!o){t.reply(481,"Subscription does not exist");return}o.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 Eo(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,a)}function o(){Z.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:a=>{n.call(this,a)},reject:()=>{o.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(t,n,o){this.ackSent=!1,this.publisherSubscribeSent=!1;const a=new Wr(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(o)return o;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},_=JSON.stringify(r);this._request.body=_,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 TT+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(kt.ICE)];this.sendRequest($.INFO,{extraHeaders:s,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async r=>{this.isConfigureSent=!0;const d=r.data.split(`\r
135
- `),h=d[d.length-1],g=JSON.parse(h);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendMemberStartMessage(t,n){const o={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(kt.CONFIGURE)];this.sendRequest($.INFO,{extraHeaders:a,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async s=>{s.status_code===200&&await t.rtcpPeer.setLocalDescription(n)}}})}_sendTrickleMessage(t){const o={trickles:[...t.map(s=>({janus:"trickle",candidate:s,handle_id:this.handle_id,session_id:this.session_id}))]},a=[this.getPTypeHeader(kt.TRICKLE)];this.sendRequest($.INFO,{extraHeaders:a,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async s=>{}}})}async _answerAttachedStream(t,n){let o=null;const a=async d=>{if(!t.rtcpPeer||t.loaded)return;{t.loaded=!0;const E={audio:!0,video:!0};await new Promise(A=>{setTimeout(A,100)}),o=await t.rtcpPeer.createAnswer(E),this._sendMemberStartMessage(t,o)}const h=d.streams[0].getAudioTracks(),g=d.streams[0].getVideoTracks(),T=[];h[0]&&T.push(h[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 _=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=_,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},o=[this.getPTypeHeader(kt.SUBSCRIBER)];this.sendRequest($.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async a=>{var s,r;if(a.status_code===200){const _=JSON.parse(a.body);(r=(s=_==null?void 0:_.plugindata)==null?void 0:s.data)!=null&&r.id&&await this._answerAttachedStream(t,_)}}}})}_attachMember(t){const n={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},o=[this.getPTypeHeader(kt.SUBSCRIBER)];this.sendRequest($.INFO,{extraHeaders:o,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},o=[this.getPTypeHeader(kt.SUBSCRIBER)];this.sendRequest($.INFO,{extraHeaders:o,body:JSON.stringify(n)}),zt.stopStreamTracks(t.memberInfo.stream),this._ua.emit("memberHangup",t.memberInfo)}receivePublishers(t){var o,a,s,r,_,d,h,g;const n={...this.memberList};(a=(o=t==null?void 0:t.plugindata)==null?void 0:o.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=(_=t==null?void 0:t.plugindata)==null?void 0:_.data)==null?void 0:d.publishers,this.private_id=(g=(h=t==null?void 0:t.plugindata)==null?void 0:h.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 o of t)n=await o.process(n);this.stream.getTracks().forEach(o=>{this.stream.removeTrack(o),o.stop()}),n.getTracks().forEach(o=>{this.stream.addTrack(o)})}async resyncPlugins(t){const n=this._ua.processStreamPlugins.filter(o=>o.type===t);for(const o of n)o.running&&o.terminate();if(t==="video"){let o=await this.loadStream();for(const a of n)a.running&&(o=await a.start(o));this.stream.getTracks().forEach(a=>{this.stream.removeTrack(a),a.stop()}),o.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 o=this._ua.newStreamPlugins.find(_=>_.type===t);let s=o.getStream().clone();for(const _ of n)_.running&&(s=await _.start(s));const r=o.getConnection();this._overrideSenderTracks(s,r),this._ua.emit("changePluginStream",{type:t,stream:s})}}stopProcessPlugins(t){const n=this._ua.processStreamPlugins.filter(o=>o.type===t);for(const o of n)o.running&&o.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 vo(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=gd();const o={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($.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async s=>{var r,_,d,h;if(s.status_code===200){if(this.subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((_=(r=g.plugindata)==null?void 0:r.data)==null?void 0:_.videoroom)==="joined"&&this.myFeedList.push(g.plugindata.data.id),(h=(d=g.plugindata)==null?void 0:d.data)!=null&&h.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 o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).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=ke.sipErrorCause(t.status_code);this._failed("remote",t,n)}}}_sendReinvite(t={}){Z.debug("sendReinvite()");const n=ke.cloneArray(t.extraHeaders),o=ke.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 h={originator:"local",type:"offer",sdp:d};Z.debug('emit "sdp"'),this.emit("sdp",h),this.sendRequest($.INVITE,{extraHeaders:n,body:d,eventHandlers:{onSuccessResponse:g=>{r.call(this,g),s=!0},onErrorResponse:g=>{_.call(this,g)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_()});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"){_.call(this);return}}else{_.call(this);return}const h={originator:"remote",type:"answer",sdp:d.body};Z.debug('emit "sdp"'),this.emit("sdp",h);const g=new RTCSessionDescription({type:"answer",sdp:h.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(g)).then(()=>{o.succeeded&&o.succeeded(d)}).catch(T=>{_.call(this),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function _(d){o.failed&&o.failed(d)}}_sendUpdate(t={}){Z.debug("sendUpdate()");const n=ke.cloneArray(t.extraHeaders),o=ke.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(h=>{h=this._mangleOffer(h);const g={originator:"local",type:"offer",sdp:h};Z.debug('emit "sdp"'),this.emit("sdp",g),this.sendRequest($.UPDATE,{extraHeaders:n,body:h,eventHandlers:{onSuccessResponse:T=>{_.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,h)},onErrorResponse:h=>{d.call(this,h)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function _(h){if(this._status!==se.STATUS_TERMINATED&&!r)if(this._handleSessionTimersInIncomingResponse(h),s){if(h.body){if(!h.hasHeader("Content-Type")||h.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const g={originator:"remote",type:"answer",sdp:h.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(()=>{o.succeeded&&o.succeeded(h)}).catch(S=>{d.call(this),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),this.emit("peerconnection:setremotedescriptionfailed",S)})}else o.succeeded&&o.succeeded(h)}function d(h){o.failed&&o.failed(h)}}_acceptAndTerminate(t,n,o){Z.debug("acceptAndTerminate()");const a=[];n&&(o=o||$.REASON_PHRASE[n]||"",a.push(`Reason: SIP ;cause=${n}; text="${o}"`)),(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=Nt.parse(t),this._localHold&&!this._remoteHold){Z.debug("mangleOffer() | me on hold, mangling offer");for(const n of t.media)So.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)So.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)So.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="recvonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="recvonly")}return Nt.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 o;t.session_expires&&t.session_expires>=$.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,o=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,o="uas"),n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${o}`),this._sessionTimers.refresher=o==="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(o=>o.track&&o.track.kind==="audio");for(const o of n)o.track.enabled=!t}_toggleMuteVideo(t){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="video");for(const o of n)o.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,o){Z.debug("session ended"),this._end_time=new Date,this._close(),Z.debug('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:o})}_failed(t,n,o){Z.debug("session failed"),Z.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:n||null,cause:o}),this._close(),Z.debug('emit "failed"'),this.emit("failed",{originator:t,message:n||null,cause:o})}_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 Vn{constructor(t){if(this.headers={},t.length>0){let n=!1;const o=t.split(`\r
134
+ `,ud.send(o)}const Qm=Me(cd);var ti={};const Fn=gt(),rn=De,_u=Yt(),fd=ps(),pu=au,gu=Ts;ti.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:rn.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:rn.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:rn.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${Fn.createRandomToken(12)}.invalid`};const go={mandatory:{sockets(c){const t=[];if(pu.isSocket(c))t.push({socket:c});else if(Array.isArray(c)&&c.length)for(const n of c)Object.prototype.hasOwnProperty.call(n,"socket")&&pu.isSocket(n.socket)?t.push(n):pu.isSocket(n)&&t.push({socket:n});else return;return t},uri(c){/^sip:/i.test(c)||(c=`${rn.SIP}:${c}`);const t=fd.parse(c);if(t)return t.user?t:void 0}},optional:{authorization_user(c){if(_u.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(Fn.isDecimal(c)){const t=Number(c);if(t>0)return t}},connection_recovery_min_interval(c){if(Fn.isDecimal(c)){const t=Number(c);if(t>0)return t}},contact_uri(c){if(typeof c=="string"){const t=_u.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)),_u.parse(c,"uuid")!==-1)return c},no_answer_timeout(c){if(Fn.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===rn.INVITE||c===rn.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(Fn.isDecimal(c)){const t=Number(c);if(t>0)return t}},registrar_server(c){/^sip:/i.test(c)||(c=`${rn.SIP}:${c}`);const t=fd.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}}};ti.load=(c,t)=>{for(const n in go.mandatory)if(t.hasOwnProperty(n)){const o=t[n],a=go.mandatory[n](o);if(a!==void 0)c[n]=a;else throw new gu.ConfigurationError(n,o)}else throw new gu.ConfigurationError(n);for(const n in go.optional)if(t.hasOwnProperty(n)){const o=t[n];if(Fn.isEmpty(o))continue;const a=go.optional[n](o);if(a!==void 0)c[n]=a;else throw new gu.ConfigurationError(n,o)}};const Zm=ct.EventEmitter,eT=ot,vt=De,tT=qg,dd=td,hd=Im,_d=xm,mu=$n,sT=id,mo=gt(),nT=Ts,rT=ps(),iT=ld,Tu=Tt,lT=cd,vu=ti,Be=new eT("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 Zm{static get C(){return St}constructor(t){if(Be.debug("new() [configuration:%o]",t),super(),this._cache={credentials:{}},this._configuration=Object.assign({},vu.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(n){throw this._status=St.STATUS_NOT_READY,this._error=St.CONFIGURATION_ERROR,n}this._registrator=new tT(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,n){Be.debug("call()");const o=new dd(this);return o.connect(t,n),o}sendMessage(t,n,o){Be.debug("sendMessage()");const a=new hd(this);return a.send(t,n,o),a}sendOptions(t,n,o){Be.debug("sendOptions()");const a=new _d(this);return a.send(t,n,o),a}terminateSessions(t){Be.debug("terminateSessions()");for(const n in this._sessions)this._sessions[n].isEnded()||this._sessions[n].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 o in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,o)){Be.debug(`closing session ${o}`);try{this._sessions[o].terminate()}catch{}}for(const o in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,o))try{this._applicants[o].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 mo.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,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 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,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){Be.debug("Request-URI does not point to us"),t.method!==vt.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===vt.SIPS){t.reply_sl(416);return}if(mu.checkTransaction(this,t))return;if(n===vt.INVITE?new mu.InviteServerTransaction(this,this._transport,t):n!==vt.ACK&&n!==vt.CANCEL&&new mu.NonInviteServerTransaction(this,this._transport,t),n===vt.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new _d(this).init_incoming(t)}else if(n===vt.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new hd(this).init_incoming(t)}else if(n===vt.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let o,a;if(t.to_tag)o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o?o.receiveRequest(t):n===vt.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"))):n!==vt.ACK&&t.reply(481);else switch(n){case vt.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const s=t.replaces;o=this._findDialog(s.call_id,s.from_tag,s.to_tag),o?(a=o.owner,a.isEnded()?t.reply(603):a.receiveRequest(t)):t.reply(481)}else a=new dd(this),a.init_incoming(t);else Be.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case vt.BYE:t.reply(481);break;case vt.CANCEL:a=this._findSession(t),a?a.receiveRequest(t):Be.debug("received CANCEL request for a non existent session");break;case vt.ACK:break;case vt.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:o}){const a=t+n,s=this._sessions[a],r=t+o,_=this._sessions[r];return s||_||null}_findDialog(t,n,o){let a=t+n+o,s=this._dialogs[a];return s||(a=t+o+n,s=this._dialogs[a],s||null)}_loadConfig(t){try{vu.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=mo.newUUID()),this._configuration.jssip_id=mo.createRandomToken(5);const n=this._configuration.uri.clone();n.user=null,this._configuration.hostport_params=n.toString().replace(/^sip:/i,"");try{this._transport=new sT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=oT.bind(this),this._transport.onconnect=aT.bind(this),this._transport.ondisconnect=uT.bind(this),this._transport.ondata=cT.bind(this)}catch(a){throw Be.warn(a),new nT.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 rT("sip",mo.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 _="<";return s?_+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":_+=this.pub_gruu||this.uri.toString(),r&&(s?!this.temp_gruu:!this.pub_gruu)&&(_+=";ob"),_+=">",_}};const o=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(o.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(vu.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 oT(c){this.emit("connecting",c)}function aT(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 uT(c){const t=["nict","ict","nist","ist"];for(const n of t)for(const o in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],o)&&this._transactions[n][o].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 cT(c){const t=c.transport;let n=c.message;if(n=iT.parseMessage(n,this),!!n&&!(this._status===St.STATUS_USER_CLOSED&&n instanceof Tu.IncomingRequest)&&lT(n,this,t)){if(n instanceof Tu.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Tu.IncomingResponse){let o;switch(n.method){case vt.INVITE:o=this._transactions.ict[n.via_branch],o&&o.receiveResponse(n);break;case vt.ACK:break;default:o=this._transactions.nict[n.via_branch],o&&o.receiveResponse(n);break}}}}const fT=Me(pd);for(var Et=[],Su=0;Su<256;++Su)Et.push((Su+256).toString(16).slice(1));function dT(c,t=0){return(Et[c[t+0]]+Et[c[t+1]]+Et[c[t+2]]+Et[c[t+3]]+"-"+Et[c[t+4]]+Et[c[t+5]]+"-"+Et[c[t+6]]+Et[c[t+7]]+"-"+Et[c[t+8]]+Et[c[t+9]]+"-"+Et[c[t+10]]+Et[c[t+11]]+Et[c[t+12]]+Et[c[t+13]]+Et[c[t+14]]+Et[c[t+15]]).toLowerCase()}var To,hT=new Uint8Array(16);function _T(){if(!To&&(To=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!To))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return To(hT)}var pT=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const gd={randomUUID:pT};function md(c,t,n){if(gd.randomUUID&&!t&&!c)return gd.randomUUID();c=c||{};var o=c.random||(c.rng||_T)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,t){n=n||0;for(var a=0;a<16;++a)t[n+a]=o[a];return t}return dT(o)}var ke=gt();const vs=Me(ke),Eu=new no("Dialog"),ks={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class vo{static get C(){return ks}constructor(t,n,o,a=ks.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,n instanceof Tt.IncomingResponse&&(a=n.status_code<200?ks.STATUS_EARLY:ks.STATUS_CONFIRMED),o==="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(o==="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),Eu.debug(`new ${o} dialog created with status ${this._state===ks.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===ks.STATUS_TERMINATED}update(t,n){this._state=ks.STATUS_CONFIRMED,Eu.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){Eu.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=ks.STATUS_TERMINATED}sendRequest(t,n={}){const o=vs.cloneArray(n.extraHeaders),a=vs.cloneObject(n.eventHandlers),s=n.body||null,r=this._createRequest(t,o,s);return a.onAuthenticated=()=>{this._local_seqnum+=1},new Jg(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,o){n=vs.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 Tt.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,o)}_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===Ht.C.STATUS_ACCEPTED||t.server_transaction.state===Ht.C.STATUS_COMPLETED||t.server_transaction.state===Ht.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===Ht.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===Ht.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}}class gT{constructor(t,n){es(this,"plugin",null);es(this,"rtcpPeer",null);es(this,"handleId",0);es(this,"info",null);es(this,"joinResult",null);es(this,"state",{});es(this,"stream",null);es(this,"loaded",!1);es(this,"aTracks",[]);es(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,_,d;const n=(r=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:r.newStatePublisher,a=((d=(_=t==null?void 0:t.plugindata)==null?void 0:_.data)==null?void 0:d.publisher_state).find(h=>h.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 zt{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(t){return zt.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(o=>o.kind===t):[]}static async getMicrophoneList(){return(await zt.getDevices("audioinput")).map((n,o)=>({...n,deviceId:n.deviceId,label:n.label||`microphone ${o+1}`,kind:n.kind,groupId:n.groupId}))}static async getSpeakerList(){return(await zt.getDevices("audiooutput")).map((n,o)=>({...n,deviceId:n.deviceId,label:n.label||`speaker ${o+1}`,kind:n.kind,groupId:n.groupId}))}static async getCameraList(){return(await zt.getDevices("videoinput")).map((n,o)=>({...n,deviceId:n.deviceId,label:n.label||`camera ${o+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 o,a;t==="default"?o=!0:t&&t!=="default"&&(o={deviceId:{exact:t}}),n==="default"?a=!0:n&&n!=="default"&&(a={deviceId:{exact:n}});const s={audio:a,video:o};return zt.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(o){let a=o;o.name==="SecurityError"&&(a=`You need to use HTTPS for selecting audio output device: ${o}`),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(o=>{o.enabled=!o.enabled}),n[0].enabled}static toggleVideoMute(t){const n=t.getVideoTracks();if(n.length!==0)return n.forEach(o=>{o.enabled=!o.enabled}),n[0].enabled}static async getStream(t={video:!0,audio:!0}){try{const n=await navigator.mediaDevices.getUserMedia(t);let o=n.getTracks();return t.video?o=n.getVideoTracks():t.audio&&(o=n.getAudioTracks()),o.length===0?{stream:n,track:null}:{stream:n,track:o[0]}}catch(n){return console.warn(n),{stream:null,track:null}}}}var mT=ps();const ln=Me(mT),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 no("JanusSession"),TT="/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},So=["audio","video"];class Eo extends ct.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-${md().replace(/-/g,"").slice(0,12)}`}connect(t,n,o={},a){Z.debug("connect()"),this.display_name=n;const s=t,r=ke.cloneObject(o.eventHandlers),_=ke.cloneArray(o.extraHeaders),d=ke.cloneObject(o.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={...d};const h=o.mediaStream||null,m=ke.cloneObject(o.pcConfig,{iceServers:[]}),T=o.rtcConstraints||null,S=o.rtcOfferConstraints||null;if(this._rtcOfferConstraints=S,this._rtcAnswerConstraints=o.rtcAnswerConstraints||null,this._data=o.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==se.STATUS_NULL)throw new Ns.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Ns.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&&ke.isDecimal(o.sessionTimersExpires)&&(o.sessionTimersExpires>=$.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=o.sessionTimersExpires:this._sessionTimers.defaultExpires=$.SESSION_EXPIRES);for(const R in r)Object.prototype.hasOwnProperty.call(r,R)&&this.on(R,r[R]);this._from_tag=ke.newTag();const E=o.anonymous||!1,A={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:E,outbound:!0}),E?(A.from_display_name="Anonymous",A.from_uri=new ln("sip","anonymous","anonymous.invalid"),_.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),_.push("Privacy: id")):o.fromUserName&&(A.from_uri=new ln("sip",o.fromUserName,this._ua.configuration.uri.host),_.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),o.fromDisplayName&&(A.from_display_name=o.fromDisplayName),_.push(`Contact: ${this._contact}`),_.push("Content-Type: application/json"),this._sessionTimers.enabled&&_.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Tt.InitialOutgoingInviteRequest(t,this._ua,A,_),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(m,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,h)}_overrideSenderTracks(t,n){t.getTracks().forEach(o=>{n.getSenders().forEach(async s=>{s.track.kind===o.kind&&(o.kind==="audio"&&!this.isAudioOn&&(o.enabled=!1),o.kind==="video"&&!this.isVideoOn&&(o.enabled=!1),await s.replaceTrack(o))})})}init_incoming(t,n){Z.debug("init_incoming()");let o;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")&&(o=t.getHeader("expires")*1e3),t.to_tag=ke.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),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===se.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,$.causes.EXPIRES))},o)),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,o=ke.cloneArray(t.extraHeaders),a=ke.cloneObject(t.mediaConstraints),s=t.mediaStream||null,r=ke.cloneObject(t.pcConfig,{iceServers:[]}),_=t.rtcConstraints||null,d=t.rtcAnswerConstraints||null,h=ke.cloneObject(t.rtcOfferConstraints);let m,T=!1,S=!1,E=!1,A=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new Ns.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==se.STATUS_WAITING_FOR_ANSWER)throw new Ns.InvalidStateError(this._status);if(this._sessionTimers.enabled&&ke.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),o.unshift(`Contact: ${this._contact}`);const R=n.parseSDP();Array.isArray(R.media)||(R.media=[R.media]);for(const C of R.media)C.type==="audio"&&(T=!0,(!C.direction||C.direction==="sendrecv")&&(E=!0)),C.type==="video"&&(S=!0,(!C.direction||C.direction==="sendrecv")&&(A=!0));if(s&&a.audio===!1){m=s.getAudioTracks();for(const C of m)s.removeTrack(C)}if(s&&a.video===!1){m=s.getVideoTracks();for(const C of m)s.removeTrack(C)}!s&&a.audio===void 0&&(a.audio=E),!s&&a.video===void 0&&(a.video=A),!s&&!T&&!h.offerToReceiveAudio&&(a.audio=!1),!s&&!S&&!h.offerToReceiveVideo&&(a.video=!1),this._createRTCConnection(r,_),Promise.resolve().then(()=>{if(s)return s;if(a.audio||a.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(C=>{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]',C),this.emit("getusermediafailed",C),new Error("getUserMedia() failed"))})}).then(C=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=C,C&&C.getTracks().forEach(H=>{this._connection.addTrack(H,C)})}).then(()=>{if(this._late_sdp)return;const C={originator:"remote",type:"offer",sdp:n.body};Z.debug('emit "sdp"'),this.emit("sdp",C);const H=new RTCSessionDescription({type:"offer",sdp:C.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(H)).catch(k=>{throw n.reply(488),this._failed("system",null,$.causes.WEBRTC_ERROR),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',k),this.emit("peerconnection:setremotedescriptionfailed",k),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(C=>{if(this._status===se.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(n,o),n.reply(200,null,o,C,()=>{this._status=se.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,C),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,$.causes.CONNECTION_ERROR)})}).catch(C=>{this._status!==se.STATUS_TERMINATED&&Z.warn(C)})}terminate(t={}){Z.debug("terminate()");const n=t.cause||$.causes.BYE,o=ke.cloneArray(t.extraHeaders),a=t.body;let s,r=t.status_code,_=t.reason_phrase;if(this._status===se.STATUS_TERMINATED)throw new Ns.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&&(_=_||$.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${_}"`),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,_,o,a),this._failed("local",null,$.causes.REJECTED);break;case se.STATUS_WAITING_FOR_ACK:case se.STATUS_CONFIRMED:if(Z.debug("terminating session"),_=t.reason_phrase||$.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&o.push(`Reason: SIP ;cause=${r}; text="${_}"`),this._status===se.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ht.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:h})=>{h===$.ACK&&(this.sendRequest($.BYE,{extraHeaders:o,body:a}),d.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ht.C.STATUS_TERMINATED&&(this.sendRequest($.BYE,{extraHeaders:o,body:a}),d.terminate(),this.closeSession())}),this._ended("local",null,n),this._dialog=d,this._ua.newDialog(d)}else{const d={janus:"leave"},h=["Content-Type: application/json",this.getPTypeHeader(kt.LEAVE)];this.sendRequest($.BYE,{extraHeaders:h,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},o=["Content-Type: application/json",this.getPTypeHeader(kt.AUDIO_CHANGE)];this.sendRequest($.INFO,{extraHeaders:o,body:JSON.stringify(n),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 n={janus:"message",body:{video:t},handle_id:this.handle_id,session_id:this.session_id},o=["Content-Type: application/json",this.getPTypeHeader(kt.VIDEO_CHANGE)];this.sendRequest($.INFO,{extraHeaders:o,body:JSON.stringify(n),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 n={janus:"message",body:{request:"state",data:t},handle_id:this.handle_id,session_id:this.session_id},o=["Content-Type: application/json",this.getPTypeHeader(kt.STATE)];this.sendRequest($.INFO,{extraHeaders:o,body:JSON.stringify(n)})}sendInfo(t,n,o={}){if(Z.debug("sendInfo()"),this._status!==se.STATUS_CONFIRMED&&this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_1XX_RECEIVED)throw new Ns.InvalidStateError(this._status);new ru(this).send(t,n,o)}mute(t={audio:!0,video:!1}){Z.debug("mute()");let n=!1,o=!1;this._audioMuted===!1&&t.audio&&(n=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(o=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(n===!0||o===!0)&&this._onmute({audio:n,video:o})}unmute(t={audio:!0,video:!0}){Z.debug("unmute()");let n=!1,o=!1;this._audioMuted===!0&&t.audio&&(n=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(o=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(n===!0||o===!0)&&this._onunmute({audio:n,video:o})}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 o={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:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,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 o={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:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:o,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},n){Z.debug("renegotiate()");const o=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:o,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:a,rtcOfferConstraints:o,extraHeaders:t.extraHeaders}),!0}refer(t,n){Z.debug("refer()");const o=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: ${o}`);const a=new _m(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 o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).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 nm(this).init_incoming(t):n!==void 0?new ru(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"),ke.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 o=jr.T1;function a(){this._status===se.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],n),o<jr.T2&&(o=o*2,o>jr.T2&&(o=jr.T2)),this._timers.invite2xxTimer=setTimeout(a.bind(this),o))}this._timers.invite2xxTimer=setTimeout(a.bind(this),o)}_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))},jr.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 o;const a=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(o),o=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 o=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?o.createOffer(n).catch(a=>(Z.warn('emit "peerconnection:createofferfailed" [error:%o]',a),this.emit("peerconnection:createofferfailed",a),Promise.reject(a))):o.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,o.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(o.iceGatheringState==="complete"&&!a||o.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:o.localDescription.sdp};return Z.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let r=!1,_,d;this._iceReady=!1;const h=()=>{o.removeEventListener("icecandidate",_),o.removeEventListener("icegatheringstatechange",d),r=!0,this._rtcReady=!0,this._iceReady=!0;const m={originator:"local",type:t,sdp:o.localDescription.sdp};Z.debug('emit "sdp"'),this.emit("sdp",m),s(m.sdp)};o.addEventListener("icecandidate",_=m=>{const T=m.candidate;T?this.emit("icecandidate",{candidate:T,ready:h}):r||h()}),o.addEventListener("icegatheringstatechange",d=()=>{o.iceGatheringState==="complete"&&!r&&h()})})})}_createDialog(t,n,o){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 _=this._earlyDialogs[r];if(o)return _?!0:(_=new vo(this,t,n,vo.C.STATUS_EARLY),_.error?(Z.debug(_.error),this._failed("remote",t,$.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=_,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,_)return _.update(t,n),this._dialog=_,delete this._earlyDialogs[r],!0;const d=new vo(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,o={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(_={}){a=!0;const d=_.status_code||403,h=_.reason_phrase||"",m=ke.cloneArray(_.extraHeaders);if(this._status!==se.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,h,m)}if(this.emit("reinvite",o),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(_=>{r.call(this,_)}).catch(()=>{t.reply(500)});return}if(n!=="application/sdp"){Z.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(_=>{this._status!==se.STATUS_TERMINATED&&r.call(this,_)}).catch(_=>{Z.warn(_)});function r(_){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),this._late_sdp&&(_=this._mangleOffer(_)),t.reply(200,null,d,_,()=>{this._status=se.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,_),this._setACKTimer()}),typeof o.callback=="function"&&o.callback()}}_receiveUpdate(t){Z.debug("receiveUpdate()");const n=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,o={request:t,callback:void 0,reject:s.bind(this)};let a=!1;function s(_={}){a=!0;const d=_.status_code||403,h=_.reason_phrase||"",m=ke.cloneArray(_.extraHeaders);if(this._status!==se.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);t.reply(d,h,m)}if(this.emit("update",o),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(_=>{this._status!==se.STATUS_TERMINATED&&r.call(this,_)}).catch(_=>{Z.warn(_)});function r(_){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,d),t.reply(200,null,d,_),typeof o.callback=="function"&&o.callback()}}_processInDialogSdpOffer(t){Z.debug("_processInDialogSdpOffer()");const n=t.parseSDP();let o=!1;for(const r of n.media){if(So.indexOf(r.type)===-1)continue;const _=r.direction||n.direction||"sendrecv";if(_==="sendonly"||_==="inactive")o=!0;else{o=!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&&o===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&o===!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 cm(this,t.cseq);Z.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,r)=>{o.call(this,s,r)},reject:()=>{a.call(this)}});function o(s,r={}){if(s=typeof s=="function"?s:null,this._status!==se.STATUS_WAITING_FOR_ACK&&this._status!==se.STATUS_CONFIRMED)return!1;const _=new Eo(this._ua);if(_.on("progress",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),_.on("accepted",({response:d})=>{n.notify(d.status_code,d.reason_phrase)}),_.on("_failed",({message:d,cause:h})=>{d?n.notify(d.status_code,d.reason_phrase):n.notify(487,h)}),t.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));r.extraHeaders=ke.cloneArray(r.extraHeaders),r.extraHeaders.push(`Replaces: ${d}`)}_.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,o;if(t.event.params&&t.event.params.id)n=t.event.params.id,o=this._referSubscribers[n];else if(Object.keys(this._referSubscribers).length===1)o=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!o){t.reply(481,"Subscription does not exist");return}o.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 Eo(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,a)}function o(){Z.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:a=>{n.call(this,a)},reject:()=>{o.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(t,n,o){this.ackSent=!1,this.publisherSubscribeSent=!1;const a=new Wr(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(o)return o;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},_=JSON.stringify(r);this._request.body=_,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 TT+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(kt.ICE)];this.sendRequest($.INFO,{extraHeaders:s,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async r=>{this.isConfigureSent=!0;const d=r.data.split(`\r
135
+ `),h=d[d.length-1],m=JSON.parse(h);await this._connection.setRemoteDescription(m.jsep),this._candidates=[]}}})}_sendMemberStartMessage(t,n){const o={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(kt.CONFIGURE)];this.sendRequest($.INFO,{extraHeaders:a,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async s=>{s.status_code===200&&await t.rtcpPeer.setLocalDescription(n)}}})}_sendTrickleMessage(t){const o={trickles:[...t.map(s=>({janus:"trickle",candidate:s,handle_id:this.handle_id,session_id:this.session_id}))]},a=[this.getPTypeHeader(kt.TRICKLE)];this.sendRequest($.INFO,{extraHeaders:a,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async s=>{}}})}async _answerAttachedStream(t,n){let o=null;const a=async d=>{if(!t.rtcpPeer||t.loaded)return;{t.loaded=!0;const E={audio:!0,video:!0};await new Promise(A=>{setTimeout(A,100)}),o=await t.rtcpPeer.createAnswer(E),this._sendMemberStartMessage(t,o)}const h=d.streams[0].getAudioTracks(),m=d.streams[0].getVideoTracks(),T=[];h[0]&&T.push(h[0]),m[0]&&T.push(m[0]);const S=new MediaStream(T);t.stream=S,this._ua.emit("memberJoin",t.memberInfo)};let s,r=[];const _=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=_,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},o=[this.getPTypeHeader(kt.SUBSCRIBER)];this.sendRequest($.SUBSCRIBE,{extraHeaders:o,body:JSON.stringify(n),eventHandlers:{onSuccessResponse:async a=>{var s,r;if(a.status_code===200){const _=JSON.parse(a.body);(r=(s=_==null?void 0:_.plugindata)==null?void 0:s.data)!=null&&r.id&&await this._answerAttachedStream(t,_)}}}})}_attachMember(t){const n={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},o=[this.getPTypeHeader(kt.SUBSCRIBER)];this.sendRequest($.INFO,{extraHeaders:o,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},o=[this.getPTypeHeader(kt.SUBSCRIBER)];this.sendRequest($.INFO,{extraHeaders:o,body:JSON.stringify(n)}),zt.stopStreamTracks(t.memberInfo.stream),this._ua.emit("memberHangup",t.memberInfo)}receivePublishers(t){var o,a,s,r,_,d,h,m;const n={...this.memberList};(a=(o=t==null?void 0:t.plugindata)==null?void 0:o.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 gT(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=(_=t==null?void 0:t.plugindata)==null?void 0:_.data)==null?void 0:d.publishers,this.private_id=(m=(h=t==null?void 0:t.plugindata)==null?void 0:h.data)==null?void 0:m.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 o of t)n=await o.process(n);this.stream.getTracks().forEach(o=>{this.stream.removeTrack(o),o.stop()}),n.getTracks().forEach(o=>{this.stream.addTrack(o)})}async resyncPlugins(t){const n=this._ua.processStreamPlugins.filter(o=>o.type===t);for(const o of n)o.running&&o.terminate();if(t==="video"){let o=await this.loadStream();for(const a of n)a.running&&(o=await a.start(o));this.stream.getTracks().forEach(a=>{this.stream.removeTrack(a),a.stop()}),o.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 o=this._ua.newStreamPlugins.find(_=>_.type===t);let s=o.getStream().clone();for(const _ of n)_.running&&(s=await _.start(s));const r=o.getConnection();this._overrideSenderTracks(s,r),this._ua.emit("changePluginStream",{type:t,stream:s})}}stopProcessPlugins(t){const n=this._ua.processStreamPlugins.filter(o=>o.type===t);for(const o of n)o.running&&o.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 vo(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=md();const o={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($.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async s=>{var r,_,d,h;if(s.status_code===200){if(this.subscribeSent=!0,s.body)try{const m=JSON.parse(s.body)||{};((_=(r=m.plugindata)==null?void 0:r.data)==null?void 0:_.videoroom)==="joined"&&this.myFeedList.push(m.plugindata.data.id),(h=(d=m.plugindata)==null?void 0:d.data)!=null&&h.publishers&&this.receivePublishers(m)}catch(m){console.error(m)}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 o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).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=ke.sipErrorCause(t.status_code);this._failed("remote",t,n)}}}_sendReinvite(t={}){Z.debug("sendReinvite()");const n=ke.cloneArray(t.extraHeaders),o=ke.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 h={originator:"local",type:"offer",sdp:d};Z.debug('emit "sdp"'),this.emit("sdp",h),this.sendRequest($.INVITE,{extraHeaders:n,body:d,eventHandlers:{onSuccessResponse:m=>{r.call(this,m),s=!0},onErrorResponse:m=>{_.call(this,m)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_()});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"){_.call(this);return}}else{_.call(this);return}const h={originator:"remote",type:"answer",sdp:d.body};Z.debug('emit "sdp"'),this.emit("sdp",h);const m=new RTCSessionDescription({type:"answer",sdp:h.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(m)).then(()=>{o.succeeded&&o.succeeded(d)}).catch(T=>{_.call(this),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',T),this.emit("peerconnection:setremotedescriptionfailed",T)})}function _(d){o.failed&&o.failed(d)}}_sendUpdate(t={}){Z.debug("sendUpdate()");const n=ke.cloneArray(t.extraHeaders),o=ke.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(h=>{h=this._mangleOffer(h);const m={originator:"local",type:"offer",sdp:h};Z.debug('emit "sdp"'),this.emit("sdp",m),this.sendRequest($.UPDATE,{extraHeaders:n,body:h,eventHandlers:{onSuccessResponse:T=>{_.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,h)},onErrorResponse:h=>{d.call(this,h)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function _(h){if(this._status!==se.STATUS_TERMINATED&&!r)if(this._handleSessionTimersInIncomingResponse(h),s){if(h.body){if(!h.hasHeader("Content-Type")||h.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const m={originator:"remote",type:"answer",sdp:h.body};Z.debug('emit "sdp"'),this.emit("sdp",m);const T=new RTCSessionDescription({type:"answer",sdp:m.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(T)).then(()=>{o.succeeded&&o.succeeded(h)}).catch(S=>{d.call(this),Z.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',S),this.emit("peerconnection:setremotedescriptionfailed",S)})}else o.succeeded&&o.succeeded(h)}function d(h){o.failed&&o.failed(h)}}_acceptAndTerminate(t,n,o){Z.debug("acceptAndTerminate()");const a=[];n&&(o=o||$.REASON_PHRASE[n]||"",a.push(`Reason: SIP ;cause=${n}; text="${o}"`)),(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=Nt.parse(t),this._localHold&&!this._remoteHold){Z.debug("mangleOffer() | me on hold, mangling offer");for(const n of t.media)So.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)So.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)So.indexOf(n.type)!==-1&&(n.direction?n.direction==="sendrecv"?n.direction="recvonly":n.direction==="recvonly"&&(n.direction="inactive"):n.direction="recvonly")}return Nt.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 o;t.session_expires&&t.session_expires>=$.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,o=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,o="uas"),n.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${o}`),this._sessionTimers.refresher=o==="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(o=>o.track&&o.track.kind==="audio");for(const o of n)o.track.enabled=!t}_toggleMuteVideo(t){const n=this._connection.getSenders().filter(o=>o.track&&o.track.kind==="video");for(const o of n)o.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,o){Z.debug("session ended"),this._end_time=new Date,this._close(),Z.debug('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:o})}_failed(t,n,o){Z.debug("session failed"),Z.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:n||null,cause:o}),this._close(),Z.debug('emit "failed"'),this.emit("failed",{originator:t,message:n||null,cause:o})}_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 Vn{constructor(t){if(this.headers={},t.length>0){let n=!1;const o=t.split(`\r
136
136
  `),a=o.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 s of o){if(s==`-------${this.ident}$`)break;if(s===""){n=!0;continue}if(s&&n)this.body+=`${s}\r
137
137
  `;else{const r=s.split(": ");this.addHeader(r[0],r[1].trim())}}}else this.ident=ke.createRandomToken(12),this.protocol="MSRP"}addHeader(t,n){this.headers[t]=n}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
138
  `;for(const n in this.headers)t+=`${n}: ${this.headers[n]}\r
@@ -153,7 +153,7 @@ 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 Wr(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=Ae.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=Ae.STATUS_INVITE_SENT}terminate(t={}){const n=t.cause||$.causes.BYE,o=ke.cloneArray(t.extraHeaders),a=t.body;let s,r=t.status_code,_=t.reason_phrase;if(this._status===Ae.STATUS_TERMINATED)throw new Ns.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ae.STATUS_NULL:case Ae.STATUS_INVITE_SENT:case Ae.STATUS_1XX_RECEIVED:if(r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(_=_||$.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${_}"`),this._status===Ae.STATUS_NULL||this._status===Ae.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Ae.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Ae.STATUS_CANCELED,this._failed("local",null,$.causes.CANCELED);break;case Ae.STATUS_WAITING_FOR_ANSWER:case Ae.STATUS_ANSWERED:if(r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,_,o,a),this._failed("local",null,$.causes.REJECTED);break;case Ae.STATUS_WAITING_FOR_ACK:case Ae.STATUS_CONFIRMED:if(_=t.reason_phrase||$.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&o.push(`Reason: SIP ;cause=${r}; text="${_}"`),this._status===Ae.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ht.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:h})=>{h===$.ACK&&(this.sendRequest($.BYE,{extraHeaders:o,body:a}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ht.C.STATUS_TERMINATED&&(this.sendRequest($.BYE,{extraHeaders:o,body:a}),d.terminate())}),this._ended("local",null,n),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest($.BYE,{extraHeaders:o,body:a}),this._ended("local",null,n)}}sendRequest(t,n){return this._dialog.sendRequest(t,n)}authenticate(t){this.status="auth";let n=new Vn("");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 o=n.toString(),a=[];for(var s=0;s<o.length;s++)a.push(o.charCodeAt(s).toString(16));this._connection.send(n.toString())}onmessage(t){const n=new Vn(t.data);if(this.status==="auth"&&n.code===401){const o=this.parseAuth(n.getHeader("WWW-Authenticate")),a=new Dm(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,ke.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 o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=n.candidate.candidate.match(o);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 uo(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!==Ae.STATUS_INVITE_SENT&&this._status!==Ae.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=Ae.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=Ae.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 o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).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=Ae.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(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(t,500,o.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=ke.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,n)}}}sendMSRP(t){const n=new Vn("");let o="";this.my_addr[1]&&(o=this.my_addr[1]),this.target_addr[1]&&(o+=" "+this.target_addr[1]),this.target_addr[0]&&(o+=" "+this.target_addr[0]),n.method="SEND",n.addHeader("To-Path",o),n.addHeader("From-Path",`${this.my_addr[0]}`),n.addHeader("Message-ID",ke.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,o=t.getHeader("Message-ID"),a=new Vn("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=n;let s=a.toString();console.log(s);let r=[];for(var _=0;_<s.length;_++)r.push(s.charCodeAt(_).toString(16));console.log(r),this._connection.send(a.toString())}_sendReport(t){let n=t.ident,o=t.getHeader("Message-ID"),a=new Vn("");a.method="REPORT",a.addHeader("To-Path",`${t.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),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 _=0;_<s.length;_++)r.push(s.charCodeAt(_).toString(16));console.log(r),this._connection.send(a.toString())}parseAuth(t){const n={},o=t.replace("Digest","").split(",");for(const a of o){const s=a.trim().split("=");n[s[0]]=s[1].match('^"(.+)"$')[1]}return n}init_incoming(t,n){let o;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=Ae.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")&&(o=t.getHeader("expires")*1e3),t.to_tag=ke.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=Ae.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),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ae.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,$.causes.EXPIRES))},o)),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!==Ae.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,n,o){this.emit("_failed",{originator:t,message:n||null,cause:o}),this._close(),this.emit("failed",{originator:t,message:n||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ae.STATUS_TERMINATED){if(this._status=Ae.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,o){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 _=this._earlyDialogs[r];if(o)return _?!0:(_=new uo(this,t,n,uo.C.STATUS_EARLY),_.error?(console.log("failed 8"),this._failed("remote",t,$.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=_,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,_)return _.update(t,n),this._dialog=_,delete this._earlyDialogs[r],!0;const d=new uo(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 Ae.STATUS_CANCELED:case Ae.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,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:o})}_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===Ae.STATUS_WAITING_FOR_ANSWER||this._status===Ae.STATUS_ANSWERED)&&(this._status=Ae.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!==Ae.STATUS_WAITING_FOR_ACK)return;if(this._status=Ae.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 o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).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===Ae.STATUS_CONFIRMED||this._status===Ae.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,$.causes.BYE)):this._status===Ae.STATUS_INVITE_RECEIVED||this._status===Ae.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===Ae.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case $.INFO:this._status===Ae.STATUS_1XX_RECEIVED||this._status===Ae.STATUS_WAITING_FOR_ANSWER||this._status===Ae.STATUS_ANSWERED||this._status===Ae.STATUS_WAITING_FOR_ACK||this._status===Ae.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new ru(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case $.UPDATE:this._status===Ae.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case $.REFER:this._status===Ae.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case $.NOTIFY:this._status===Ae.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ae.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:$.causes.CONNECTION_ERROR,cause:$.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ae.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:$.causes.REQUEST_TIMEOUT,cause:$.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ae.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:$.causes.DIALOG_ERROR,cause:$.causes.DIALOG_ERROR})}}var vT=Yt();const Cu=Me(vT),yo=new no("Parser"),ST=(c,t)=>{let n,o,a=c.indexOf(`\r
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 Wr(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=Ae.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=Ae.STATUS_INVITE_SENT}terminate(t={}){const n=t.cause||$.causes.BYE,o=ke.cloneArray(t.extraHeaders),a=t.body;let s,r=t.status_code,_=t.reason_phrase;if(this._status===Ae.STATUS_TERMINATED)throw new Ns.InvalidStateError(this._status);switch(this.status="terminated",this._status){case Ae.STATUS_NULL:case Ae.STATUS_INVITE_SENT:case Ae.STATUS_1XX_RECEIVED:if(r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);r&&(_=_||$.REASON_PHRASE[r]||"",s=`SIP ;cause=${r} ;text="${_}"`),this._status===Ae.STATUS_NULL||this._status===Ae.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===Ae.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=Ae.STATUS_CANCELED,this._failed("local",null,$.causes.CANCELED);break;case Ae.STATUS_WAITING_FOR_ANSWER:case Ae.STATUS_ANSWERED:if(r=r||480,r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._request.reply(r,_,o,a),this._failed("local",null,$.causes.REJECTED);break;case Ae.STATUS_WAITING_FOR_ACK:case Ae.STATUS_CONFIRMED:if(_=t.reason_phrase||$.REASON_PHRASE[r]||"",r&&(r<200||r>=700))throw new TypeError(`Invalid status_code: ${r}`);if(r&&o.push(`Reason: SIP ;cause=${r}; text="${_}"`),this._status===Ae.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ht.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:h})=>{h===$.ACK&&(this.sendRequest($.BYE,{extraHeaders:o,body:a}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ht.C.STATUS_TERMINATED&&(this.sendRequest($.BYE,{extraHeaders:o,body:a}),d.terminate())}),this._ended("local",null,n),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest($.BYE,{extraHeaders:o,body:a}),this._ended("local",null,n)}}sendRequest(t,n){return this._dialog.sendRequest(t,n)}authenticate(t){this.status="auth";let n=new Vn("");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 o=n.toString(),a=[];for(var s=0;s<o.length;s++)a.push(o.charCodeAt(s).toString(16));this._connection.send(n.toString())}onmessage(t){const n=new Vn(t.data);if(this.status==="auth"&&n.code===401){const o=this.parseAuth(n.getHeader("WWW-Authenticate")),a=new Dg(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},o,ke.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 o=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=n.candidate.candidate.match(o);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 uo(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!==Ae.STATUS_INVITE_SENT&&this._status!==Ae.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=Ae.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=Ae.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 o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).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=Ae.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(o=>this._connection.setLocalDescription(o)).catch(o=>{this._acceptAndTerminate(t,500,o.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=ke.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,n)}}}sendMSRP(t){const n=new Vn("");let o="";this.my_addr[1]&&(o=this.my_addr[1]),this.target_addr[1]&&(o+=" "+this.target_addr[1]),this.target_addr[0]&&(o+=" "+this.target_addr[0]),n.method="SEND",n.addHeader("To-Path",o),n.addHeader("From-Path",`${this.my_addr[0]}`),n.addHeader("Message-ID",ke.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,o=t.getHeader("Message-ID"),a=new Vn("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),a.ident=n;let s=a.toString();console.log(s);let r=[];for(var _=0;_<s.length;_++)r.push(s.charCodeAt(_).toString(16));console.log(r),this._connection.send(a.toString())}_sendReport(t){let n=t.ident,o=t.getHeader("Message-ID"),a=new Vn("");a.method="REPORT",a.addHeader("To-Path",`${t.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",o),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 _=0;_<s.length;_++)r.push(s.charCodeAt(_).toString(16));console.log(r),this._connection.send(a.toString())}parseAuth(t){const n={},o=t.replace("Digest","").split(",");for(const a of o){const s=a.trim().split("=");n[s[0]]=s[1].match('^"(.+)"$')[1]}return n}init_incoming(t,n){let o;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=Ae.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")&&(o=t.getHeader("expires")*1e3),t.to_tag=ke.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=Ae.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),o&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ae.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,$.causes.EXPIRES))},o)),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!==Ae.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,n,o){this.emit("_failed",{originator:t,message:n||null,cause:o}),this._close(),this.emit("failed",{originator:t,message:n||null,cause:o})}_close(){if(console.log("CLOSE SESSION"),this._status!==Ae.STATUS_TERMINATED){if(this._status=Ae.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,o){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 _=this._earlyDialogs[r];if(o)return _?!0:(_=new uo(this,t,n,uo.C.STATUS_EARLY),_.error?(console.log("failed 8"),this._failed("remote",t,$.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[r]=_,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,_)return _.update(t,n),this._dialog=_,delete this._earlyDialogs[r],!0;const d=new uo(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 Ae.STATUS_CANCELED:case Ae.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,o){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:n||null,cause:o})}_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===Ae.STATUS_WAITING_FOR_ANSWER||this._status===Ae.STATUS_ANSWERED)&&(this._status=Ae.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!==Ae.STATUS_WAITING_FOR_ACK)return;if(this._status=Ae.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 o=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(o)).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===Ae.STATUS_CONFIRMED||this._status===Ae.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,$.causes.BYE)):this._status===Ae.STATUS_INVITE_RECEIVED||this._status===Ae.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===Ae.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case $.INFO:this._status===Ae.STATUS_1XX_RECEIVED||this._status===Ae.STATUS_WAITING_FOR_ANSWER||this._status===Ae.STATUS_ANSWERED||this._status===Ae.STATUS_WAITING_FOR_ACK||this._status===Ae.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new ru(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case $.UPDATE:this._status===Ae.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case $.REFER:this._status===Ae.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case $.NOTIFY:this._status===Ae.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==Ae.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:$.causes.CONNECTION_ERROR,cause:$.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==Ae.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:$.causes.REQUEST_TIMEOUT,cause:$.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==Ae.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:$.causes.DIALOG_ERROR,cause:$.causes.DIALOG_ERROR})}}var vT=Yt();const Cu=Me(vT),yo=new no("Parser"),ST=(c,t)=>{let n,o,a=c.indexOf(`\r
157
157
  `);if(a===-1){yo.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=c.substring(0,a);let r=Cu.parse(s,"Request_Response");if(r===-1){yo.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else r.status_code?(n=new Ln.IncomingResponse,n.status_code=r.status_code,n.reason_phrase=r.reason_phrase):(n=new Ln.IncomingRequest(t),n.method=r.method,n.ruri=r.uri);n.data=c;let _=a+2;for(;;){if(a=ET(c,_),a===-2){o=_+2;break}else if(a===-1){yo.warn("parseMessage() | malformed message");return}if(r=yT(n,c,_,a),r!==!0){yo.warn("parseMessage() |",r.error);return}_=a+2}if(n.hasHeader("content-length")){const d=n.getHeader("content-length");n.body=c.substr(o,d)}else n.body=c.substring(o);return n};function ET(c,t){let n=t,o=0,a=0;if(c.substring(n,n+2).match(/(^\r\n)/))return-2;for(;o===0;){if(a=c.indexOf(`\r
158
- `,n),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?n=a+2:o=a}return o}function yT(c,t,n,o){let a;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),_=t.substring(s+1,o).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",_),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",_),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",_),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=Cu.parse(_,"Record_Route"),a===-1)a=void 0;else for(const d of a)c.addHeader("record-route",_.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",_),a=c.parseHeader("call-id"),a&&(c.call_id=_);break;case"contact":case"m":if(a=Cu.parse(_,"Contact"),a===-1)a=void 0;else for(const d of a)c.addHeader("contact",_.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",_),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",_),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",_),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof Ln.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",_),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",_),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",_),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",_),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",_),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",_),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",_),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,_),a=0}return a===void 0?{error:`error parsing header "${r}"`}:!0}const CT={parseMessage:ST},si=new no("Registrator"),Co=10;class AT{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=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 o=this._contact.indexOf(">");if(o!==-1){const a=this._contact.slice(0,o)+this._contact.slice(o+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 o=t[n];this._extraContactParams+=`;${n}`,o&&(this._extraContactParams+=`=${o}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];this._extraContactParams+=`;${n}`,o&&(this._extraContactParams+=`=${o}`)}}register(){if(this._registering){si.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 Tt.OutgoingRequest($.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),o=new Wr(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")){si.debug("no Contact header in response to REGISTER, response ignored");break}const s=a.headers.Contact.reduce((h,g)=>h.concat(g.parsed),[]);let r=s.find(h=>this._sipInstance===h.getParam("+sip.instance")&&this._reg_id===parseInt(h.getParam("reg-id")));if(r||(r=s.find(h=>h.uri.user===this._ua.contact.uri.user)),!r){si.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let _=r.getParam("expires");!_&&a.hasHeader("expires")&&(_=a.getHeader("expires")),_||(_=this._expires),_=Number(_),_<Co&&(_=Co);const d=_>64?_*1e3/2+Math.floor((_/2-32)*1e3*Math.random()):Math.floor(_*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<Co&&(this._expires=Co),this.register()):(si.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,$.causes.SIP_FAILURE_CODE));break}default:{const s=vs.sipErrorCause(a.status_code);this._registrationFailure(a,s)}}}});this._registering=!0,o.send()}unregister(t={}){if(!this._registered){si.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 o=new Tt.OutgoingRequest($.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Wr(this._ua,o,{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=vs.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 tt=console,Ps={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},RT=fT;class bT extends RT{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 AT(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(t,n){return super.call(t,n)}joinVideoCall(t,n,o){tt.debug("call()");const a=new Eo(this);return a.configureMedia({audio:!0,video:!0}),a.connect(t,n,o),a}startScreenShare(){tt.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{ti.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=vs.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=vs.createRandomToken(5);const o=this._configuration.uri.clone();o.user=null,this._configuration.hostport_params=o.toString().replace(/^sip:/i,"");try{this._transport=new Lg(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=IT.bind(this),this._transport.onconnect=wT.bind(this),this._transport.ondisconnect=OT.bind(this),this._transport.ondata=DT.bind(this)}catch(s){throw tt.warn(s),new Ns.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 ln("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(s={}){const r=s.anonymous||null,_=s.outbound||null;let d="<";return r?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),_&&(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}));tt.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(ti.settings,s))switch(s){case"uri":case"registrar_server":tt.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":tt.debug(`- ${s}: NOT SHOWN`);break;default:tt.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(o=>{o.setSession(t)}),this.processStreamPlugins.forEach(o=>{o.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,_,d;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){tt.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(Ht.checkTransaction(this,t))return;if(n===De.INVITE?new Ht.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new Ht.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 Cf.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new Cf.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let o,a;if(t.to_tag)if(o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o)o.receiveRequest(t);else if(n===De.NOTIFY)if(a=this._findSession(t),a)a.receiveRequest(t);else{if(t.body)try{const h=JSON.parse(t.body)||{};(r=(s=h.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(h),(d=(_=h.plugindata)==null?void 0:_.data)!=null&&d.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(h.plugindata.data.unpublished)}catch(h){console.error(h)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const h=t.replaces;o=this._findDialog(h.call_id,h.from_tag,h.to_tag),o?(a=o.owner,a.isEnded()?t.reply(603):a.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(a=new yu(this),a.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(a=new Eg(this),a.init_incoming(t));else tt.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):tt.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){tt.debug("startMSRP()",n);const o=new yu(this);return o.connect(t),o}startJanus(t,n){tt.debug("startJanus()",n);const o=new yu(this);return o.connect(t),o}terminateMSRPSessions(t){tt.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){tt.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){tt.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){tt.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)){tt.debug(`closing session ${t}`);try{this._sessions[t].terminate()}catch(n){console.error(n)}}}stop(t=!0){if(tt.debug("stop()"),this._dynConfiguration={},this._status===Ps.STATUS_USER_CLOSED){tt.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)){tt.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)){tt.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=Ps.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 IT(c){this.emit("connecting",c)}function wT(c){this._status!==Ps.STATUS_USER_CLOSED&&(this._status=Ps.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 o in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],o)&&this._transactions[n][o].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Ps.STATUS_USER_CLOSED&&(this._status=Ps.STATUS_NOT_READY,this._error=Ps.NETWORK_ERROR)}function DT(c){const t=c.transport;let n=c.message;const o=n;if(n=CT.parseMessage(n,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(n,o),!!n&&!(this._status===Ps.STATUS_USER_CLOSED&&n instanceof Ln.IncomingRequest)&&Qg(n,this,t)){if(n instanceof Ln.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Ln.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(h=>h._id&&h._id.includes(n.call_id)||h.id&&h.id.includes(n.call_id)||h.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 NT=["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"],xT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Td(c){const t={};return NT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function vd(c){const t={};return xT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}async function Au(c,t,n){const o=c.createMediaStreamSource(t),a=c.createMediaStreamDestination(),s=c.createGain();return o.connect(s),s.connect(a),s.gain.value=n,a.stream}function UT(c,t,n,o){if(Sd())return;const a=document.createElement("audio");a.id=t._id,a.className="audioTag",a.srcObject=c,a.setSinkId(n),a.volume=o,a.play(),t.audioTag=a}function kT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function Sd(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const PT=ot,MT=Yt(),Ot=new PT("WebSocketInterface");var LT=class{constructor(t){Ot.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=MT.parse(t,"absoluteURI");if(n===-1)throw Ot.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ot.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(Ot.debug("connect()"),this.isConnected()){Ot.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ot.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ot.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(){Ot.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 Ot.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Ot.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(){Ot.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:o}){Ot.debug(`WebSocket ${this._url} closed`),t===!1&&Ot.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,o)}_onMessage({data:t}){Ot.debug("received WebSocket message"),this.ondata(t)}_onError(t){Ot.warn(`WebSocket ${this._url} error: `,t)}};const Ru=Tl,$T=De,HT=Ts,FT=mt(),VT=pd,jT=ps(),qT=Ba(),BT=Yt(),GT=LT;Nn("JsSIP")("version %s",Ru.version);var WT={C:$T,Exceptions:HT,Utils:FT,UA:VT,URI:jT,NameAddrHeader:qT,WebSocketInterface:GT,Grammar:BT,debug:Nn,get name(){return Ru.title},get version(){return Ru.version}};const KT=Me(WT);function bu(c){return c<10?`0${c}`:`${c}`}function YT(c){let t=c.hours||0,n=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,n++,n===60&&(n=0,t++));const a=`${bu(t)}:${bu(n)}:${bu(o)}`;return{seconds:o,minutes:n,hours:t,formatted:a}}function JT(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 zT(c,t,n=150){const o=t.createMediaStreamSource(c),a=t.createDelay();a.delayTime.value=n/1e3;const s=t.createGain();s.gain.value=0;const r=t.createMediaStreamDestination();return o.connect(a).connect(s).connect(r),{stream:r.stream,setSpeaking:_=>{s.gain.value=_?1:0}}}var yt={};yt.forEach=async(c,t,n)=>{const o=[];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));o.push(s)}await Promise.all(o)},yt.forEachSeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)o in c&&await t.call(n||globalThis,await c[o],o,c)},yt.map=async(c,t,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(s=>t.call(n||globalThis,s,a,c)));return Promise.all(o)},yt.mapSeries=async(c,t,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await t.call(n||globalThis,await c[a],a,c));return o},yt.find=(c,t,n)=>new Promise((o,a)=>{if(c.length===0)return o();let s=1;for(let r=0;r<c.length;r++){const _=d=>{d?o(c[r]):s===c.length&&o(),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(_).catch(a)}}),yt.findSeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)if(await t.call(n||globalThis,await c[o],o,c))return c[o]},yt.findIndex=(c,t,n)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let s=1;for(let r=0;r<c.length;r++){const _=d=>{d?o(r):s===c.length&&o(-1),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(_).catch(a)}}),yt.findIndexSeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)if(await t.call(n||globalThis,await c[o],o,c))return o},yt.some=(c,t,n)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const _=d=>{d?o(!0):s===c.length&&o(!1),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(_).catch(a)}}),yt.someSeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)if(o in c&&await t.call(n||globalThis,await c[o],o,c))return!0;return!1},yt.every=(c,t,n)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const _=d=>{d?s===c.length&&o(!0):o(!1),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(_).catch(a)}}),yt.everySeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)if(o in c&&!await t.call(n||globalThis,await c[o],o,c))return!1;return!0},yt.filter=(c,t,n)=>new Promise(async(o,a)=>{const s=[];for(let _=0;_<c.length;_++)_ in c&&(s[_]=Promise.resolve(c[_]).then(d=>t.call(n||globalThis,d,_,c)).catch(a));const r=[];for(let _=0;_<s.length;_++)await s[_]&&r.push(await c[_]);o(r)}),yt.filterSeries=async(c,t,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},yt.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(n!==void 0?(a=n,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await t(await a,await c[o],o,c));return a};var Ed={};(function(c){const t=yt;Object.keys(t).forEach(n=>{const o=n.charAt(0).toUpperCase()+n.slice(1);c[`async${o}`]=async function(...a){return t[n](this,...a)}})})(Ed);var XT=Object.assign(yt,{instanceMethods:Ed});const Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},Ao={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 QT={exports:{}};(function(c){var t=function(n){var o=Object.prototype,a=o.hasOwnProperty,s=Object.defineProperty||function(Q,W,B){Q[W]=B.value},r,_=typeof Symbol=="function"?Symbol:{},d=_.iterator||"@@iterator",h=_.asyncIterator||"@@asyncIterator",g=_.toStringTag||"@@toStringTag";function T(Q,W,B){return Object.defineProperty(Q,W,{value:B,enumerable:!0,configurable:!0,writable:!0}),Q[W]}try{T({},"")}catch{T=function(W,B,ie){return W[B]=ie}}function S(Q,W,B,ie){var ve=W&&W.prototype instanceof re?W:re,Ie=Object.create(ve.prototype),Pe=new U(ie||[]);return s(Ie,"_invoke",{value:K(Q,B,Pe)}),Ie}n.wrap=S;function E(Q,W,B){try{return{type:"normal",arg:Q.call(W,B)}}catch(ie){return{type:"throw",arg:ie}}}var A="suspendedStart",R="suspendedYield",C="executing",H="completed",k={};function re(){}function x(){}function F(){}var _e={};T(_e,d,function(){return this});var pe=Object.getPrototypeOf,P=pe&&pe(pe(X([])));P&&P!==o&&a.call(P,d)&&(_e=P);var N=F.prototype=re.prototype=Object.create(_e);x.prototype=F,s(N,"constructor",{value:F,configurable:!0}),s(F,"constructor",{value:x,configurable:!0}),x.displayName=T(F,g,"GeneratorFunction");function q(Q){["next","throw","return"].forEach(function(W){T(Q,W,function(B){return this._invoke(W,B)})})}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,F):(Q.__proto__=F,T(Q,g,"GeneratorFunction")),Q.prototype=Object.create(N),Q},n.awrap=function(Q){return{__await:Q}};function j(Q,W){function B(Ie,Pe,Re,oe){var ye=E(Q[Ie],Q,Pe);if(ye.type==="throw")oe(ye.arg);else{var lt=ye.arg,at=lt.value;return at&&typeof at=="object"&&a.call(at,"__await")?W.resolve(at.__await).then(function(Ee){B("next",Ee,Re,oe)},function(Ee){B("throw",Ee,Re,oe)}):W.resolve(at).then(function(Ee){lt.value=Ee,Re(lt)},function(Ee){return B("throw",Ee,Re,oe)})}}var ie;function ve(Ie,Pe){function Re(){return new W(function(oe,ye){B(Ie,Pe,oe,ye)})}return ie=ie?ie.then(Re,Re):Re()}s(this,"_invoke",{value:ve})}q(j.prototype),T(j.prototype,h,function(){return this}),n.AsyncIterator=j,n.async=function(Q,W,B,ie,ve){ve===void 0&&(ve=Promise);var Ie=new j(S(Q,W,B,ie),ve);return n.isGeneratorFunction(W)?Ie:Ie.next().then(function(Pe){return Pe.done?Pe.value:Ie.next()})};function K(Q,W,B){var ie=A;return function(Ie,Pe){if(ie===C)throw new Error("Generator is already running");if(ie===H){if(Ie==="throw")throw Pe;return je()}for(B.method=Ie,B.arg=Pe;;){var Re=B.delegate;if(Re){var oe=V(Re,B);if(oe){if(oe===k)continue;return oe}}if(B.method==="next")B.sent=B._sent=B.arg;else if(B.method==="throw"){if(ie===A)throw ie=H,B.arg;B.dispatchException(B.arg)}else B.method==="return"&&B.abrupt("return",B.arg);ie=C;var ye=E(Q,W,B);if(ye.type==="normal"){if(ie=B.done?H:R,ye.arg===k)continue;return{value:ye.arg,done:B.done}}else ye.type==="throw"&&(ie=H,B.method="throw",B.arg=ye.arg)}}}function V(Q,W){var B=W.method,ie=Q.iterator[B];if(ie===r)return W.delegate=null,B==="throw"&&Q.iterator.return&&(W.method="return",W.arg=r,V(Q,W),W.method==="throw")||B!=="return"&&(W.method="throw",W.arg=new TypeError("The iterator does not provide a '"+B+"' method")),k;var ve=E(ie,Q.iterator,W.arg);if(ve.type==="throw")return W.method="throw",W.arg=ve.arg,W.delegate=null,k;var Ie=ve.arg;if(!Ie)return W.method="throw",W.arg=new TypeError("iterator result is not an object"),W.delegate=null,k;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,k}q(N),T(N,g,"Generator"),T(N,d,function(){return this}),T(N,"toString",function(){return"[object Generator]"});function z(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 D(Q){var W=Q.completion||{};W.type="normal",delete W.arg,Q.completion=W}function U(Q){this.tryEntries=[{tryLoc:"root"}],Q.forEach(z,this),this.reset(!0)}n.keys=function(Q){var W=Object(Q),B=[];for(var ie in W)B.push(ie);return B.reverse(),function ve(){for(;B.length;){var Ie=B.pop();if(Ie in W)return ve.value=Ie,ve.done=!1,ve}return ve.done=!0,ve}};function X(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 B=-1,ie=function ve(){for(;++B<Q.length;)if(a.call(Q,B))return ve.value=Q[B],ve.done=!1,ve;return ve.value=r,ve.done=!0,ve};return ie.next=ie}}return{next:je}}n.values=X;function je(){return{value:r,done:!0}}return U.prototype={constructor:U,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(D),!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 B(oe,ye){return Ie.type="throw",Ie.arg=Q,W.next=oe,ye&&(W.method="next",W.arg=r),!!ye}for(var ie=this.tryEntries.length-1;ie>=0;--ie){var ve=this.tryEntries[ie],Ie=ve.completion;if(ve.tryLoc==="root")return B("end");if(ve.tryLoc<=this.prev){var Pe=a.call(ve,"catchLoc"),Re=a.call(ve,"finallyLoc");if(Pe&&Re){if(this.prev<ve.catchLoc)return B(ve.catchLoc,!0);if(this.prev<ve.finallyLoc)return B(ve.finallyLoc)}else if(Pe){if(this.prev<ve.catchLoc)return B(ve.catchLoc,!0)}else if(Re){if(this.prev<ve.finallyLoc)return B(ve.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Q,W){for(var B=this.tryEntries.length-1;B>=0;--B){var ie=this.tryEntries[B];if(ie.tryLoc<=this.prev&&a.call(ie,"finallyLoc")&&this.prev<ie.finallyLoc){var ve=ie;break}}ve&&(Q==="break"||Q==="continue")&&ve.tryLoc<=W&&W<=ve.finallyLoc&&(ve=null);var Ie=ve?ve.completion:{};return Ie.type=Q,Ie.arg=W,ve?(this.method="next",this.next=ve.finallyLoc,k):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),k},finish:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var B=this.tryEntries[W];if(B.finallyLoc===Q)return this.complete(B.completion,B.afterLoc),D(B),k}},catch:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var B=this.tryEntries[W];if(B.tryLoc===Q){var ie=B.completion;if(ie.type==="throw"){var ve=ie.arg;D(B)}return ve}}throw new Error("illegal catch attempt")},delegateYield:function(Q,W,B){return this.delegate={iterator:X(Q),resultName:W,nextLoc:B},this.method==="next"&&(this.arg=r),k}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(QT);var yd={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(cs,function(){var t=function(){},n="undefined",o=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function s(R,C){var H=R[C];if(typeof H.bind=="function")return H.bind(R);try{return Function.prototype.bind.call(H,R)}catch{return function(){return Function.prototype.apply.apply(H,[R,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 _(R){return R==="debug"&&(R="log"),typeof console===n?!1:R==="trace"&&o?r:console[R]!==void 0?s(console,R):console.log!==void 0?s(console,"log"):t}function d(R,C){for(var H=0;H<a.length;H++){var k=a[H];this[k]=H<R?t:this.methodFactory(k,R,C)}this.log=this.debug}function h(R,C,H){return function(){typeof console!==n&&(d.call(this,C,H),this[R].apply(this,arguments))}}function g(R,C,H){return _(R)||h.apply(this,arguments)}function T(R,C,H){var k=this,re;C=C??"WARN";var x="loglevel";typeof R=="string"?x+=":"+R:typeof R=="symbol"&&(x=void 0);function F(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 _e(){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 k.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{}}}k.name=R,k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.methodFactory=H||g,k.getLevel=function(){return re},k.setLevel=function(N,q){if(typeof N=="string"&&k.levels[N.toUpperCase()]!==void 0&&(N=k.levels[N.toUpperCase()]),typeof N=="number"&&N>=0&&N<=k.levels.SILENT){if(re=N,q!==!1&&F(N),d.call(k,N,R),typeof console===n&&N<k.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+N},k.setDefaultLevel=function(N){C=N,_e()||k.setLevel(N,!1)},k.resetLevel=function(){k.setLevel(C,!1),pe()},k.enableAll=function(N){k.setLevel(k.levels.TRACE,N)},k.disableAll=function(N){k.setLevel(k.levels.SILENT,N)};var P=_e();P==null&&(P=C),k.setLevel(P,!1)}var S=new T,E={};S.getLogger=function(C){if(typeof C!="symbol"&&typeof C!="string"||C==="")throw new TypeError("You must supply a name when creating a logger.");var H=E[C];return H||(H=E[C]=new T(C,S.getLevel(),S.methodFactory)),H};var A=typeof window!==n?window.log:void 0;return S.noConflict=function(){return typeof window!==n&&window.log===S&&(window.log=A),S},S.getLoggers=function(){return E},S.default=S,S})})(yd);var bt=yd.exports;const Ss=()=>`${new Date().toISOString()} | metrics`,Es=(c,t,n)=>`${c} | ${t} | ${n}`;bt.setDefaultLevel(bt.levels.TRACE);const ZT=c=>{bt.info(Es(Ss(),"log ",`set log level to ${c?"verbose":"info"}`)),bt.setLevel(c?bt.levels.TRACE:bt.levels.INFO)},ev=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,n)=>{n?bt.debug(Es(Ss(),c,t),n):bt.debug(Es(Ss(),c,t))},Iu=(c,t)=>{bt.info(Es(Ss(),c,t))},on=(c,t)=>{bt.info(Es(Ss(),c,t))},Ro=(c,t)=>{bt.warn(Es(Ss(),c,t))},jn=(c,t)=>{bt.error(Es(Ss(),c,t))};function tv(c){return Math.floor(Math.random()*c).toString()}function Cd(c,t){let n=t;return c.forEach(o=>{n=n.replace(o,"")}),n}function sv(c,t){let n="";for(let o=0;o<t;o+=1)n+=c[tv(c.length)];return n}function nv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",_=[],d=[],h=[];return t&&(a.length&&(s=Cd(a,s)),d=s.split("")),n&&(a.length&&(r=Cd(a,r)),h=r.split("")),_=[...d,...h,...o],sv(_,c)}var rv=nv;const ni=Me(rv),iv=()=>"WebRTCMetrics",lv=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},ys={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ri={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},ov=()=>({...{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:[]}}),Ad={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},Rd={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},bd={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},Id={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},av=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(o=>{n.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{n.video[o]={...c.video[o]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},uv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${ni()}`,cid:`c-${ni()}`,uid:`u-${ni()}`,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"},G={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"},ii={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},wu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Ou="config ",cv=(c,t={},n)=>{const o={...n,...t};return t.pname||Ro(Ou,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||Ro(Ou,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||Ro(Ou,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),o.pc=c,o},fv=(c={})=>{const t={...uv,...c};return t.name=iv(),t.version=lv(),t},li=(c,t,n,o=!1,a)=>{let s=c.map(r=>{if(!n)return r[t];if(!a)return r[t][n];const _=r[t][a];return _?_[n]:null});return s=s.filter(r=>o?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Ms=c=>c.reduce((t,n)=>t+n,0)/c.length,dv=()=>`probe-${ni()}`,hv=()=>`coltr-${ni()}`,wd=c=>new Promise(t=>setTimeout(t,c)),Du=(c,t,n)=>{t?c.call(t,n):c(n)},Ke=(c,t,n,o)=>{const a=li(c,t,n,!0,o);if(a.length===0)return null;const s=a.reduce((h,g)=>h+g,0)/a.length;return s===0?null:a.map(h=>Math.abs(s-h)).reduce((h,g)=>h+g,0)/a.length*100/s},Qe=(c,t,n,o=!1,a)=>{const s=li(c,t,n,o,a);return s.length===0?null:s.reduce((r,_)=>r+_,0)/s.length},an=(c,t,n)=>li(c,t,n).reduce((a,s)=>a+s,0),Ye=(c,t,n,o)=>{const a=li(c,t,n,!0,o);return a.length===0?null:Math.min(...a)},Je=(c,t,n,o)=>{const a=li(c,t,n,!1,o);return a.length===0?null:Math.max(...a)},Ct=(c,t,n,o)=>{const a=c.slice().pop();if(!a)return null;if(!n)return a[t];if(!o)return a[t][n];const s=a[t][o];return s?s[n]:null},_v=c=>c.slice().pop(),dt=(c,t,n)=>{if(!t)return null;const o={};let a=t[M.AUDIO][c];a||(a=n===$e.INBOUND?{...Ad}:{...Rd}),o[M.AUDIO]=a;let s=t[M.VIDEO][c];return s||(s=n===$e.INBOUND?{...bd}:{...Id}),o[M.VIDEO]=s,o},oi="exporter ",pv="2.0",Od=(c,t,n)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[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},mv=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const o=n[t].total_rtt_connectivity_ms,a=n[t].total_rtt_connectivity_measure;return!a||!o?Qe(c,t,"delta_rtt_connectivity_ms"):Number(o/a)},gv=c=>Ct(c,"network","local_candidate_type")!=="relay"?`direct/${Ct(c,"network","local_candidate_protocol")}`:`turn/${Ct(c,"network","local_candidate_relay_protocol")}`,Tv=c=>{const t=Ct(c,"network","remote_candidate_type"),n=Ct(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class vv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){Iu(oi,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){Iu(oi,"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(oi,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){Iu(oi,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ue(oi,"ticket() - generate ticket");const t=Ct(this._reports,"audio","total_packets_lost_in"),n=Ct(this._reports,"audio","total_packets_in"),o=Ct(this._reports,"video","total_packets_lost_in"),a=Ct(this._reports,"video","total_packets_in"),s={},r=_v(this._reports);return r&&(Object.keys(r[M.AUDIO]).forEach(_=>{const d=r[M.AUDIO][_];if(s[d.ssrc]={type:M.AUDIO,direction:d.direction},d.direction===$e.INBOUND){const h={avg:Qe(this._reports,M.AUDIO,"delta_jitter_ms_in",!1,_),min:Ye(this._reports,M.AUDIO,"delta_jitter_ms_in",_),max:Je(this._reports,M.AUDIO,"delta_jitter_ms_in",_),volatility:Ke(this._reports,M.AUDIO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Qe(this._reports,M.AUDIO,"delta_kbs_in",!1,_),min:Ye(this._reports,M.AUDIO,"delta_kbs_in",_),max:Je(this._reports,M.AUDIO,"delta_kbs_in",_),volatility:Ke(this._reports,M.AUDIO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.AUDIO,"delta_KBytes_in",!1,_),min:Ye(this._reports,M.AUDIO,"delta_KBytes_in",_),max:Je(this._reports,M.AUDIO,"delta_KBytes_in",_),volatility:Ke(this._reports,M.AUDIO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={emodel:{avg:Qe(this._reports,M.AUDIO,"mos_emodel_in",!1,_),min:Ye(this._reports,M.AUDIO,"mos_emodel_in",_),max:Je(this._reports,M.AUDIO,"mos_emodel_in",_),volatility:Ke(this._reports,M.AUDIO,"mos_emodel_in",_)},effective:{avg:Qe(this._reports,M.AUDIO,"mos_in",!1,_),min:Ye(this._reports,M.AUDIO,"mos_in",_),max:Je(this._reports,M.AUDIO,"mos_in",_),volatility:Ke(this._reports,M.AUDIO,"mos_in",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},E=Ct(this._reports,M.AUDIO,"total_packets_lost_in",_),A=Ct(this._reports,M.AUDIO,"total_packets_in",_),R={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[_].jitter=h,s[_].mos=S,s[_].traffic=T,s[_].bitrate=g,s[_].loss=R}else{const h={avg:Qe(this._reports,M.AUDIO,"delta_jitter_ms_out",!1,_),min:Ye(this._reports,M.AUDIO,"delta_jitter_ms_out",_),max:Je(this._reports,M.AUDIO,"delta_jitter_ms_out",_),volatility:Ke(this._reports,M.AUDIO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Qe(this._reports,M.AUDIO,"delta_kbs_out",!1,_),min:Ye(this._reports,M.AUDIO,"delta_kbs_out",_),max:Je(this._reports,M.AUDIO,"delta_kbs_out",_),volatility:Ke(this._reports,M.AUDIO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.AUDIO,"delta_KBytes_out",!1,_),min:Ye(this._reports,M.AUDIO,"delta_KBytes_out",_),max:Je(this._reports,M.AUDIO,"delta_KBytes_out",_),volatility:Ke(this._reports,M.AUDIO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},S={avg:Od(this._reports,M.AUDIO,_),min:Ye(this._reports,M.AUDIO,"delta_rtt_ms_out",_),max:Je(this._reports,M.AUDIO,"delta_rtt_ms_out",_),volatility:Ke(this._reports,M.AUDIO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=Ct(this._reports,M.AUDIO,"total_packets_lost_out",_),A=Ct(this._reports,M.AUDIO,"total_packets_out",_),R={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},C={emodel:{avg:Qe(this._reports,M.AUDIO,"mos_emodel_out",!1,_),min:Ye(this._reports,M.AUDIO,"mos_emodel_out",_),max:Je(this._reports,M.AUDIO,"mos_emodel_out",_),volatility:Ke(this._reports,M.AUDIO,"mos_emodel_out",_)},effective:{avg:Qe(this._reports,M.AUDIO,"mos_out",!1,_),min:Ye(this._reports,M.AUDIO,"mos_out",_),max:Je(this._reports,M.AUDIO,"mos_out",_),volatility:Ke(this._reports,M.AUDIO,"mos_out",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[_].jitter=h,s[_].rtt=S,s[_].traffic=T,s[_].bitrate=g,s[_].loss=R,s[_].mos=C}}),Object.keys(r[M.VIDEO]).forEach(_=>{const d=r[M.VIDEO][_];if(s[_]={type:M.VIDEO,direction:d.direction},d.direction===$e.INBOUND){const h={avg:Qe(this._reports,M.VIDEO,"delta_jitter_ms_in",!1,_),min:Ye(this._reports,M.VIDEO,"delta_jitter_ms_in",_),max:Je(this._reports,M.VIDEO,"delta_jitter_ms_in",_),volatility:Ke(this._reports,M.VIDEO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Qe(this._reports,M.VIDEO,"delta_kbs_in",!1,_),min:Ye(this._reports,M.VIDEO,"delta_kbs_in",_),max:Je(this._reports,M.VIDEO,"delta_kbs_in",_),volatility:Ke(this._reports,M.VIDEO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.VIDEO,"delta_KBytes_in",!1,_),min:Ye(this._reports,M.VIDEO,"delta_KBytes_in",_),max:Je(this._reports,M.VIDEO,"delta_KBytes_in",_),volatility:Ke(this._reports,M.VIDEO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S=Ct(this._reports,M.VIDEO,"total_packets_lost_in",_),E=Ct(this._reports,M.VIDEO,"total_packets_in",_),A={lost:S,avg:Math.round((S/(S+E)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[_].jitter=h,s[_].traffic=T,s[_].bitrate=g,s[_].loss=A}else{const h={avg:Qe(this._reports,M.VIDEO,"delta_jitter_ms_out",!1,_),min:Ye(this._reports,M.VIDEO,"delta_jitter_ms_out",_),max:Je(this._reports,M.VIDEO,"delta_jitter_ms_out",_),volatility:Ke(this._reports,M.VIDEO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},g={avg:Qe(this._reports,M.VIDEO,"delta_kbs_out",!1,_),min:Ye(this._reports,M.VIDEO,"delta_kbs_out",_),max:Je(this._reports,M.VIDEO,"delta_kbs_out",_),volatility:Ke(this._reports,M.VIDEO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.VIDEO,"delta_KBytes_out",!1,_),min:Ye(this._reports,M.VIDEO,"delta_KBytes_out",_),max:Je(this._reports,M.VIDEO,"delta_KBytes_out",_),volatility:Ke(this._reports,M.VIDEO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={avg:Od(this._reports,M.VIDEO,_),min:Ye(this._reports,M.VIDEO,"delta_rtt_ms_out",_),max:Je(this._reports,M.VIDEO,"delta_rtt_ms_out",_),volatility:Ke(this._reports,M.VIDEO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=Ct(this._reports,M.VIDEO,"total_packets_lost_out",_),A=Ct(this._reports,M.VIDEO,"total_packets_out",_),R={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[_].jitter=h,s[_].rtt=S,s[_].traffic=T,s[_].bitrate=g,s[_].loss=R}})),{version:pv,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:mv(this._reports,"data"),min:Ye(this._reports,"data","delta_rtt_connectivity_ms"),max:Je(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ke(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((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Qe(this._reports,"data","delta_kbs_in"),min:Ye(this._reports,"data","delta_kbs_in"),max:Je(this._reports,"data","delta_kbs_in"),volatility:Ke(this._reports,"data","delta_kbs_in")},out:{avg:Qe(this._reports,"data","delta_kbs_out"),min:Ye(this._reports,"data","delta_kbs_out"),max:Je(this._reports,"data","delta_kbs_out"),volatility:Ke(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:Ye(this._reports,"data","delta_KBytes_in"),max:Je(this._reports,"data","delta_KBytes_in"),volatility:Ke(this._reports,"data","delta_KBytes_in")},out:{avg:Qe(this._reports,"data","delta_KBytes_out"),min:Ye(this._reports,"data","delta_KBytes_out"),max:Je(this._reports,"data","delta_KBytes_out"),volatility:Ke(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:gv(this._reports),remoteConnection:Tv(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 Ls="extractor ",Dd=(c,t,n,o)=>{let a=!1;const s=o[t].total_rtt_ms_out,r=o[t].total_rtt_measure_out,_=n?n[t].total_rtt_ms_out:0,d=n?n[t].total_rtt_measure_out:0,h={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[G.TIMESTAMP]===o[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,G.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,G.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[G.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[G.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===r))return h;const g=1e3*Number(c[G.ROUND_TRIP_TIME]);let T=s+g,S=r+1;return a&&(T=1e3*Number(c[G.TOTAL_ROUND_TRIP_TIME])-_,S=Number(c[G.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:g,totalRTT:T,totalRTTMeasurements:S}},Sv=(c,t,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,G.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[t].total_rtt_connectivity_ms,totalRTTMeasurements:o[t].total_rtt_connectivity_measure};const a=1e3*Number(c[G.CURRENT_ROUND_TRIP_TIME]);let s=o[t].total_rtt_connectivity_ms+a,r=o[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,G.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[G.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,G.RESPONSES_RECEIVED)&&(r=Number(c[G.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:s,totalRTTMeasurements:r}},bo=(c,t,n)=>c[G.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,G.JITTER)?null:1e3*(Number(c[G.JITTER])||0),Ev=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,G.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,G.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[G.FRAMES_DECODED],o=c[G.TOTAL_DECODE_TIME],a=o-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:o}},yv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,G.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,G.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[G.FRAMES_ENCODED],o=c[G.TOTAL_ENCODE_TIME],a=o-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:o}},Nd=(c,t,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,G.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,G.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[G.PACKETS_SENT])||0-(o?o[t].total_packets_out:0),s=a-n[t].total_packets_out,r=Number(c[G.BYTES_SENT])/1024-(o?o[t].total_KBytes_out:0),_=r-n[t].total_KBytes_out,d=c[G.TIMESTAMP]||Date.now(),h=o?o.timestamp:null;let g=n.timestamp;!g&&h&&(g=h);const T=g?d-g:0,S=T>0?_*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:_,kbsSent:S}},xd=(c,t,n,o)=>{let a=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,G.PACKETS_LOST)&&(a=Number(c[G.PACKETS_LOST])||0-(o?o[t].total_packets_lost_out:0),s=a-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,G.FRACTION_LOST)&&(r=Number(100*c[G.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:s,fractionLost:r}},Ud=(c,t,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,G.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,G.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,G.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[G.PACKETS_RECEIVED])||0-(o?o[t].total_packets_in:0),s=Number(c[G.PACKETS_LOST])||0-(o?o[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,_=a-n[t].total_packets_in,d=a!==n[t].total_packets_in?r*100/(r+_):0,h=Number(c[G.BYTES_RECEIVED])/1024-(o?o[t].total_KBytes_in:0),g=h-n[t].total_KBytes_in,T=c[G.TIMESTAMP]||Date.now(),S=o?o.timestamp:null;let E=n.timestamp;!E&&S&&(E=S);const A=E?T-E:0,R=A>0?g*.008*1024/A*1e3:0;return{percentPacketsLost:d,packetsReceived:a,deltaPacketsReceived:_,packetsLost:s,deltaPacketsLost:r,KBytesReceived:h,deltaKBytesReceived:g,kbsReceived:R}},Cv=c=>c[G.CANDIDATE_TYPE]!=="relay"?"":c[G.RELAY_PROTOCOL]||"",Av=c=>{if(!Object.prototype.hasOwnProperty.call(c,G.NETWORK_TYPE))return ii.WIFI;switch(c[G.NETWORK_TYPE]){case wu.ETHERNET:return ii.ETHERNET;case wu.CELLULAR_4G:return ii.CELLULAR_4G;case wu.WIFI:return ii.WIFI;default:return ii.CELLULAR}},kd=c=>!Object.prototype.hasOwnProperty.call(c,G.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,G.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[G.FRAME_WIDTH]||null,height:c[G.FRAME_HEIGHT]||null,framerate:c[G.FRAMES_PER_SECOND]},Rv=c=>{const t=Object.prototype.hasOwnProperty.call(c,G.QUALITY_LIMITATION_REASON)?c[G.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,G.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[G.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,G.QUALITY_LIMITATION_DURATIONS)?c[G.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:t,durations:o,resolutionChanges:n}},bv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,G.PLI)||!Object.prototype.hasOwnProperty.call(c,G.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[G.PLI]||0)-(n?n[M.VIDEO].total_pli_sent_in:0),a=(c[G.NACK]||0)-(n?n[M.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-t[M.VIDEO].total_pli_sent_in,deltaNackCount:a-t[M.VIDEO].total_nack_sent_in}},Iv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,G.PLI)||!Object.prototype.hasOwnProperty.call(c,G.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[G.PLI]||0)-(n?n[M.VIDEO].total_pli_received_out:0),a=(c[G.NACK]||0)-(n?n[M.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-t[M.VIDEO].total_pli_received_out,deltaNackCount:a-t[M.VIDEO].total_nack_received_out}},wv=c=>({channels:c[G.CHANNELS]||null,clock_rate:c[G.CLOCK_RATE]||null,mime_type:c[G.MIME_TYPE]||null,sdp_fmtp_line:c[G.SDP_FMTP_LINE]||null}),Ov=c=>({clock_rate:c[G.CLOCK_RATE]||null,mime_type:c[G.MIME_TYPE]||null}),Dv=(c,t,n)=>{const o=(c[G.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),a=(c[G.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[G.TIMESTAMP]||Date.now(),r=o-t.data.total_KBytes_in,_=a-t.data.total_KBytes_out,d=n?n.timestamp:null;let h=t.timestamp;!h&&d&&(h=d);const g=h?s-h:0,T=g>0?r*.008*1024/g*1e3:0,S=g>0?_*.008*1024/g*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:r,delta_KBytes_sent:_,kbs_speed_received:T,kbs_speed_sent:S}},Nv=c=>{const t=c[G.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[G.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},xv=(c,t,n,o)=>{if(!c)return[];switch(c[G.TYPE]){case Qt.CANDIDATE_PAIR:let a=!1;if(c[G.NOMINATED]&&c[G.STATE]===M.SUCCEEDED&&(a=!0,Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c),G.SELECTED in c&&!c[G.SELECTED]&&(a=!1)),a){const r=c[G.LOCAL_CANDIDATE_ID],_=c[G.REMOTE_CANDIDATE_ID],d=Dv(c,t,o),h=Nv(c),g=Sv(c,"data",o,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:_}},{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:h.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:h.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[G.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:Av(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[G.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[G.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:Cv(c)}}];break;case Qt.REMOTE_CANDIDATE:if(c[G.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[G.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[G.PROTOCOL]||""}}];break;case Qt.INBOUND_RTP:{Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const r=c[G.SSRC],_=dt(r,t,$e.INBOUND);_&&(_.timestamp=t.timestamp);const d=dt(r,o,$e.INBOUND);if(d&&(d.timestamp=o.timestamp),c[G.MEDIA_TYPE]===M.AUDIO){const h=Ud(c,M.AUDIO,_,d),g=bo(c,M.AUDIO,_),T=c[G.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:h.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:h.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:h.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:h.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:h.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:h.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:h.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:h.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:g}}]}if(c[G.MEDIA_TYPE]===M.VIDEO){const h=Ev(c,_),g=Ud(c,M.VIDEO,_,d),T=bo(c,M.VIDEO,_),S=c[G.DECODER_IMPLEMENTATION]||null,E=c[G.CODEC_ID]||null,A=kd(c),R=bv(c,_,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:h.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:h.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:h.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:A}}]}break}case Qt.OUTBOUND_RTP:{Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const r=c[G.SSRC],_=dt(r,t,$e.OUTBOUND);_&&(_.timestamp=t.timestamp);const d=dt(r,o,$e.OUTBOUND);if(d&&(d.timestamp=o.timestamp),c[G.MEDIA_TYPE]===M.AUDIO){const h=c[G.CODEC_ID]||null,g=Nd(c,M.AUDIO,_,d);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:h}},{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[G.MEDIA_TYPE]===M.VIDEO){const h=c[G.ENCODER_IMPLEMENTATION]||null,g=c[G.CODEC_ID]||null,T=yv(c,_),S=kd(c),E=Rv(c),A=Iv(c,_,d),R=Nd(c,M.VIDEO,_,d);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:g}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:h}},{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:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:A.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(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);break}case Qt.TRACK:{Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);break}case Qt.CODEC:const s=[];return Object.keys(t[M.AUDIO]).forEach(r=>{const _=t[M.AUDIO][r];if(_.codec_id_in===c[G.ID]||_.codec_id_out===c[G.ID]){Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const d=wv(c);c[G.ID]===_.codec_id_in?s.push({ssrc:_.ssrc,type:ne.AUDIO,value:{codec_in:d}}):s.push({ssrc:_.ssrc,type:ne.AUDIO,value:{codec_out:d}})}}),Object.keys(t[M.VIDEO]).forEach(r=>{const _=t[M.VIDEO][r];if(_.codec_id_in===c[G.ID]||_.codec_id_out===c[G.ID]){Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const d=Ov(c);c[G.ID]===_.codec_id_in?s.push({ssrc:_.ssrc,type:ne.VIDEO,value:{codec_in:d}}):s.push({ssrc:_.ssrc,type:ne.VIDEO,value:{codec_out:d}})}}),s;case Qt.REMOTE_INBOUND_RTP:{Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const r=c[G.SSRC],_=dt(r,t,$e.OUTBOUND),d=dt(r,o,$e.OUTBOUND);if(c[G.KIND]===M.AUDIO){const h=Dd(c,M.AUDIO,d,_),g=bo(c,M.AUDIO,_),T=xd(c,M.AUDIO,_,d);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:h.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:h.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:h.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[G.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[G.KIND]===M.VIDEO){const h=Dd(c,M.VIDEO,d,_),g=bo(c,M.VIDEO,_),T=xd(c,M.VIDEO,_,d);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:h.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:h.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:h.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:g}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[G.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[]},Io=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Uv=(c,t=M.AUDIO,n,o,a)=>{const s=dt(a,c,$e.INBOUND),r=dt(a,n,$e.INBOUND),_=dt(a,o,$e.INBOUND),d=[],h=[],g=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=_&&_[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=n&&n.data.delta_rtt_connectivity_ms||null,C=o&&o.data.delta_rtt_connectivity_ms||null;A&&d.push(A),R&&d.push(R),C&&d.push(C),T&&h.push(T),n&&S&&h.push(S),o&&E&&h.push(E);const H=d.length>0?Ms(d):100,k=h.length>0?Ms(h):10,re=93.2-g,x=.18*re*re-27.9*re+1126.62,F=(H+k)/2,_e=F-177.3<0?0:1,pe=.024*F+.11*(F-177.3)*_e,P=x-pe;return Io(P)},kv=(c,t=M.AUDIO,n,o,a)=>{const s=dt(a,c,$e.OUTBOUND),r=dt(a,n,$e.OUTBOUND),_=dt(a,o,$e.OUTBOUND),d=[],h=[],g=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=_&&_[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,R=r&&r[t].delta_jitter_ms_out||null,C=_&&_[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,k=n&&n.data.delta_rtt_connectivity_ms||null,re=o&&o.data.delta_rtt_connectivity_ms||null;T?d.push(T):H&&d.push(H),S?d.push(S):k&&d.push(k),E?d.push(E):re&&d.push(re),A&&h.push(A),n&&R&&h.push(R),o&&C&&h.push(C);const x=d.length>0?Ms(d):100,F=h.length>0?Ms(h):10,_e=93.2-g,pe=.18*_e*_e-27.9*_e+1126.62,P=(x+F)/2,N=P-177.3<0?0:1,q=.024*P+.11*(P-177.3)*N,j=pe-q;return Io(j)},Pv=(c,t=M.AUDIO,n,o,a)=>{const s=dt(a,c,$e.INBOUND),r=dt(a,n,$e.INBOUND),_=dt(a,o,$e.INBOUND),d=[],h=[],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=_&&_[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=n&&n.data.delta_rtt_connectivity_ms||null,C=o&&o.data.delta_rtt_connectivity_ms||null;A&&d.push(A),R&&d.push(R),C&&d.push(C),T&&h.push(T),r&&S&&h.push(S),_&&E&&h.push(E);const H=d.length>0?Ms(d):100,k=h.length>0?Ms(h):10,re=0,x=19.8,F=29.7,_e=30,pe=(H+k)/2+_e,P=pe-177.3<0?0:1,N=.024*pe+.11*(pe-177.3)*P,j=93.2-(re+x*Math.log(1+F*g)+N);return Io(j)},Mv=(c,t=M.AUDIO,n,o,a)=>{const s=dt(a,c,$e.OUTBOUND),r=dt(a,n,$e.OUTBOUND),_=dt(a,o,$e.OUTBOUND),d=[],h=[],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=_&&_[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,R=r&&r[t].delta_jitter_ms_out||null,C=_&&_[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,k=n&&n.data.delta_rtt_connectivity_ms||null,re=o&&o.data.delta_rtt_connectivity_ms||null;T?d.push(T):H&&d.push(H),S?d.push(S):k&&d.push(k),E?d.push(E):re&&d.push(re),A&&h.push(A),r&&R&&h.push(R),_&&C&&h.push(C);const x=d.length>0?Ms(d):100,F=h.length>0?Ms(h):10,_e=0,pe=19.8,P=29.7,N=30,q=(x+F)/2+N,j=q-177.3<0?0:1,K=.024*q+.11*(q-177.3)*j,z=93.2-(_e+pe*Math.log(1+P*g)+K);return Io(z)};class Lv{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=hv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new vv(t),this._state=ys.IDLE,this.registerToPCEvents(),on(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,o,a){const s=(d,h)=>d===M.AUDIO?h===Qt.INBOUND_RTP?{...Ad}:{...Rd}:h===Qt.INBOUND_RTP?{...bd}:{...Id},r=av(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 _=null;return t.forEach(d=>{!_&&d.timestamp&&(_=d.timestamp),xv(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=_,Object.keys(r[M.AUDIO]).forEach(d=>{const h=r[M.AUDIO][d];h.direction===$e.INBOUND?(h.mos_emodel_in=Uv(r,M.AUDIO,n,o,h.ssrc),h.mos_in=Pv(r,M.AUDIO,n,o,h.ssrc)):(h.mos_emodel_out=kv(r,M.AUDIO,n,o,h.ssrc),h.mos_out=Mv(r,M.AUDIO,n,o,h.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,s=Date.now(),r=await this._config.pc.getStats(),_=this.analyze(r,null,null,null),d=Date.now();_.experimental.time_to_measure_ms=d-s,_.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(_),Ue(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(a){n(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ys.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(),o=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-t,this._exporter.addReport(o),Ue(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(t){return jn(this._moduleName,`got error ${t}`),null}}async start(){Ue(this._moduleName,"starting"),this.state=ys.RUNNING,this._startedTime=this._exporter.start(),Ue(this._moduleName,"started")}async mute(){this.state=ys.MUTED,Ue(this._moduleName,"muted")}async unmute(){this.state=ys.RUNNING,Ue(this._moduleName,"unmuted")}async stop(t){if(Ue(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ys.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Ue(this._moduleName,"stopped")}registerCallback(t,n,o){t in this._callbacks?(this._callbacks[t]={callback:n,context:o},Ue(this._moduleName,`registered callback '${t}'`)):jn(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}'`)):jn(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,o,a){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:o,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{jn(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const o=t.iceConnectionState;o===ri.CONNECTED||o===ri.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===ri.DISCONNECTED||o===ri.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===ri.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const o=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},t.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.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 o=n[0],{transport:a}=o;if(a){const{iceTransport:s}=a;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class $v{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||dv(),this._moduleName=this._id,on(this._moduleName,"probe created"),this._config=t,this._collector=new Lv(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,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,n,t,o)}get isRunning(){return this._collector.state===ys.RUNNING}get isIdle(){return this._collector.state===ys.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){Ro(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 Hv{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},on(It,`configured for probing every ${this._config.refreshEvery}ms`),on(It,`configured for starting after ${this._config.startAfter}ms`),on(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,n){if(!t)throw new Error("undefined peer connection");const o=cv(t,n,this._config),a=new $v(o);return this._probes.push(a),Ue(It,`${this._probes.length} probes registered`),a}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===ys.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())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const s=ov(),r=this._probes.filter(_=>_.isRunning);for(const _ of r){const d=await _.collectStats();d&&s.probes.push(d),Ue(It,`got probe ${_.id}`),await wd(0)}return s.delta_time_to_measure_probes_ms=an(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=an(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=an(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=an(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=an(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=an(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=an(s.probes,"video","total_time_encoded_out"),s};for(Ue(It,"starting to collect"),t(),Ue(It,"generating reference reports..."),await n(),Ue(It,"reference reports generated"),this._startedTime=Date.now();o();)if(Ue(It,`wait ${this._config.refreshEvery}ms before collecting`),await wd(this._config.refreshEvery),o()){Ue(It,"collecting...");const s=Date.now(),r=await a(),_=Date.now();r.delta_time_consumed_to_measure_ms=_-s,this.fireOnReports(r),Ue(It,"collected")}Ue(It,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=o=>{this._probes.forEach(a=>{a.stop(o)})};on(It,"stop collecting"),n(t)}registerCallback(t,n,o){t in this._callbacks?(this._callbacks[t]={callback:n,context:o},Ue(It,`registered callback '${t}'`)):jn(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}'`)):jn(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 Fv="interface ";class Vv{constructor(t){this._config=fv(t),on(Fv,`welcome to ${this._config.name} version ${this._config.version}`),ZT(this._config.verbose||!1),this._engine=new Hv(this._config)}setupLogLevel(t){ev(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 jv(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,o)=>{const a=o;return{...n,[a]:c[a]}},{})}const qv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],Bv={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class Gv{constructor(t){this.intervals={},this.analysers={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}async start(t,n,o){n&&n.getTracks().length&&await this.beginCalculation(t,n,o)}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,o){this.clearVolumeInterval(o);const a=t.createAnalyser(),s=t.createMediaStreamSource(n);a.smoothingTimeConstant=.8,a.fftSize=1024,s.connect(a),this.analysers[o]=a,this.intervals[o]=setInterval(()=>{const r=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(r);let _=0;const d=r.length;for(let g=0;g<d;g++)_+=r[g];const h=_/d;this.onChangeFunction(o,h)},this.emitInterval)}}class Wv{constructor(){this.resumePromise=null,this.context=new AudioContext,this.setupErrorHandling()}setupErrorHandling(){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 wo={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Kv=0;class Yv{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.vadSessions={},this.vadSessionsState={},this.vadIntervals={},this.vadMrsIntervals={},this.ringbackTimers={},this.ringbackAudioContexts={},this.ringbackSessionProgressReceived={},this.managedAudioContext=new Wv,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new Gv({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 o of n)this.noiseReduction[o]=t[o];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,o;const t=(o=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:o.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||{}}}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(o=>!o.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 Sd()?{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(wo.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(wo.SELECTED_OUTPUT_DEVICE)||"default";try{const o=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)}),o.getTracks().forEach(s=>s.stop())}catch(o){console.error(o)}}async cleanupConferenceNodes(t){const n=this.conferenceNodes[t];if(!n)return;let o=0;n.sources.forEach((r,_)=>{var d;try{r.disconnect(),o++}catch(h){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,_)=>{var d;try{r.disconnect(),a++}catch(h){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,_)=>{var d;try{r.disconnect(),s++}catch(h){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(o=>o.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:o}){const a=this.extendedCalls[t];if(!a)return;a._automaticHold=o??!1;const s=new Promise((r,_)=>{const d=setTimeout(()=>{_(new Error("Hold operation timeout"))},5e3),h=()=>{clearTimeout(d),a.putOnHoldTimestamp=n?Date.now():void 0,r()},g=T=>{clearTimeout(d),_(T)};try{n?(this.stopSessionVad(a._id),a.hold({},h)):a.unhold({},h)}catch(T){g(T)}});try{await s,this.updateCall(a);const r=Object.values(this.extendedCalls).filter(_=>_.roomId===a.roomId&&(n?t!==_._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===Kv).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",o=>{this.triggerAddStream(o,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]=Td(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const o={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...o}},this.context.emit("updateRoom",{room:o,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,a=t.request.getHeader("Call-Info");return a&&n.test(a)}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:Td(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 o={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(o.isMoving=t.isMoving),t.isTransferring!==void 0&&(o.isTransferring=t.isTransferring),t.isMerging!==void 0&&(o.isMerging=t.isMerging),t.isTransferred!==void 0&&(o.isTransferred=t.isTransferred),this.callStatus={...this.callStatus,[t.callId]:{...o}},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 Au(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 Au(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:o})=>o===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async o=>{await this.setupActiveStream();const a=this.activeStream;o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):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 o=n.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?n.forEach(a=>{var s;(s=a.audioTag)==null||s.setSinkId(t),this.updateCall(a)}):await this.doConference(o)}removeRoom(t){const n={...this.activeRooms},o={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:o,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({sessionId:t,stream:n,onNoiseDetected:o,onNoiseStop:a}){var g,T,S;let s;try{s=await this.managedAudioContext.getContext()}catch(E){console.error("[startNoiseMonitor] Failed to get AudioContext:",E),(g=this.context.logger)==null||g.error("[startNoiseMonitor] Failed to get AudioContext:",E);return}let r,_;try{r=s.createMediaStreamSource(n.clone()),_=s.createAnalyser()}catch(E){console.error("[startNoiseMonitor] Failed to create audio nodes:",E),console.error("[startNoiseMonitor] AudioContext state:",s.state),(T=this.context.logger)==null||T.error("[startNoiseMonitor] Failed to create audio nodes:",E),(S=this.context.logger)==null||S.error("[startNoiseMonitor] AudioContext state:",s.state);return}_.fftSize=1024;const d=new Float32Array(_.fftSize);r.connect(_);const h=[];this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),this.vadIntervals[t]=null),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),this.vadMrsIntervals[t]=null),this.vadMrsIntervals[t]=setInterval(()=>{_.getFloatTimeDomainData(d);const E=JT(d);h.push(E);const A=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);h.length>A&&h.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[t]=setInterval(()=>{var C;if(h.length===0)return;const E=h.reduce((H,k)=>H+k,0)/h.length,A=this.vadSessionsState[t];if(!A){console.warn(`[startNoiseMonitor] State not found for sessionId ${t}, stopping interval`),(C=this.context.logger)==null||C.warn(`[startNoiseMonitor] State not found for sessionId ${t}, stopping interval`),this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),delete this.vadIntervals[t]),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),delete this.vadMrsIntervals[t]);return}const R=E>this.noiseReduction.noiseThreshold;A.isSpeaking||(R&&A.currentMode==="clean"?(A.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!0}),o()):!R&&A.currentMode==="noisy"&&(A.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!1}),a()))},this.noiseReduction.noiseCheckInterval)}async processVAD(t,n){var d;const o=n.clone();this.stopSessionVad(t._id),this.vadSessionsState[t._id]={currentMode:"clean",isSpeaking:!1},console.log("[processVAD] Process for",t._id),(d=this.context.logger)==null||d.log("[processVAD] Process for",t._id);const a=await this.managedAudioContext.getContext(),s=await zT(o,a,150);let r=!1;const _=await this.MicVAD.new({getStream:()=>new Promise(h=>h(o)),...Bv,...this.noiseReduction.vadConfig,baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",onFrameProcessed:()=>{var h;if(!r){if(r=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){t.connection.getSenders()[0]&&t.connection.getSenders()[0].replaceTrack(s.stream.getAudioTracks()[0]);return}if(!this.vadSessionsState[t._id]){console.error(`[processVAD] CRITICAL: State not found for session ${t._id} after being set at line 988! This should not happen.`),(h=this.context.logger)==null||h.error(`[processVAD] CRITICAL: State not found for session ${t._id} after being set at line 988! This should not happen.`);return}this.startNoiseMonitor({sessionId:t._id,stream:o,onNoiseDetected:async()=>{var g,T;console.log("[processVad] - Replace track with Vad Controlled"),(g=this.context.logger)==null||g.log("[processVad] - Replace track with Vad Controlled"),await((T=t.connection.getSenders()[0])==null?void 0:T.replaceTrack(s.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const g=t.connection.getSenders()[0];g&&g.track&&g.transport&&g.transport.state!=="closed"&&g.transport.state!=="failed"&&(console.log("Replace track with Original"),await g.replaceTrack(o.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var h;console.log("🎤 Speech started"),s.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((h=t.connection.getSenders()[0])==null||h.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!0},onSpeechEnd:()=>{var h;console.log("🛑 Speech end"),s.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((h=t.connection.getSenders()[0])==null||h.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!1}});this.vadSessions[t._id]&&(this.vadSessions[t._id].pause(),delete this.vadSessions[t._id]),this.vadSessions[t._id]=_,_.start()}stopSessionVad(t){this.vadSessions[t]&&(this.vadSessions[t].pause(),delete this.vadSessions[t]),this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),delete this.vadIntervals[t]),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),delete this.vadMrsIntervals[t]),this.vadSessionsState[t]&&delete this.vadSessionsState[t]}async roomReconfigure(t){var a,s,r,_;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(d=>d.roomId===t),o=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,h)=>{if(d.audioTag){d.connection.getReceivers().forEach(T=>{T.track.enabled=!d.localMuted}),o&&this.muteReconfigure(d);const g=!o;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&&!o){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&&o){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"),(_=this.context.logger)==null||_.log("[roomReconfigure] - Call processVAD from roomReconfigure"),this.processVAD(n[0],E));const A=E.getTracks();await T.replaceTrack(A[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 h,g,T,S,E,A,R;if(console.log("[doConference] - In doConference, sessions:",t),(h=this.context.logger)==null||h.log("[doConference] - In doConference, sessions:",t),t.length===0)return;const n=t[0].roomId,o=this.currentActiveRoomId===n;if(t.find(C=>C.roomId!==n))return;let s;try{s=await this.managedAudioContext.getContext()}catch(C){console.error("[doConference] Failed to get AudioContext:",C),(g=this.context.logger)==null||g.error("[doConference] Failed to get AudioContext:",C);return}const r=s.state;if(r!=="running")if(console.error(`[doConference] ERROR: AudioContext is not running! State: ${r}`),(T=this.context.logger)==null||T.error(`[doConference] ERROR: AudioContext is not running! State: ${r}`),r==="suspended"||r==="interrupted")try{await s.resume();const C=s.state;if(C!=="running"){console.error(`[doConference] Failed to resume AudioContext, state: ${C}`),(S=this.context.logger)==null||S.error(`[doConference] Failed to resume AudioContext, state: ${C}`);return}}catch(C){console.error("[doConference] Error resuming AudioContext:",C),(E=this.context.logger)==null||E.error("[doConference] Error resuming AudioContext:",C);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 _=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((C,H)=>{var k,re,x;if(console.log("[doConference] - In sessions forEach, iteration for",C._id),(k=this.context.logger)==null||k.log("[doConference] - In sessions forEach, iteration for",C._id),C&&C.connection){const F=C.connection.getReceivers();console.log("[doConference] - Receivers list length for",C._id,F.length),(re=this.context.logger)==null||re.log("[doConference] - Receivers list length for",C._id,F.length),F.forEach((_e,pe)=>{var q,j,K,V,z,D;_e.track.enabled=!C.localMuted;const P=(q=_e.track)==null?void 0:q.id;(j=_e.track)==null||j.readyState,(K=_e.track)==null||K.kind;const N=`${C._id}-${P}`;console.log("[doConference] - Gathering receiver tracks",C._id),console.log("[doConference] - Receiver track readyState",_e.track.readyState),(V=this.context.logger)==null||V.log("[doConference] - Gathering receiver tracks",C._id),(z=this.context.logger)==null||z.log("[doConference] - Receiver track readyState",_e.track.readyState),_e.track&&_e.track.readyState==="live"&&(console.log("[doConference] - Gathered receiver track",C._id),(D=this.context.logger)==null||D.log("[doConference] - Gathered receiver track",C._id),d.set(N,_e.track))})}else console.log("[doConference] - No session or RTC connection, session:",C),(x=this.context.logger)==null||x.log("[doConference] - No session or RTC connection, session:",C)}),await this.setupActiveStream(),await XT.forEach(t,async(C,H)=>{var N,q,j,K,V,z;if(!C||!C.connection){console.log("[doConference] - Return because of no session or connection, session:",C),(N=this.context.logger)==null||N.log("[doConference] - Return because of no session or connection, session:",C);return}const k=s.createMediaStreamDestination();_.destinations.set(C._id,k);let re=0;const x=C.connection.getReceivers(),F=x.length>0;if(console.log(`[doConference] Session ${C._id} has ${x.length} receivers`),(q=this.context.logger)==null||q.log(`[doConference] Session ${C._id} has ${x.length} receivers`),F||(console.warn(`[doConference] Session ${C._id} has no receivers yet. Will re-configure when track arrives.`),(j=this.context.logger)==null||j.warn(`[doConference] Session ${C._id} has no receivers yet. Will re-configure when track arrives.`)),d.forEach((D,U)=>{var X,je,Q;if(console.log("[doConference] - In forEach receiverTracks for",C._id),(X=this.context.logger)==null||X.log("[doConference] - In forEach receiverTracks for",C._id),!U.startsWith(C._id)){if(!D||D.readyState!=="live"){console.warn(`[doConference] Skipping invalid track ${(D==null?void 0:D.id)||"unknown"} for session ${C._id}`),(je=this.context.logger)==null||je.warn(`[doConference] Skipping invalid track ${(D==null?void 0:D.id)||"unknown"} for session ${C._id}`);return}try{const W=s.createMediaStreamSource(new MediaStream([D])),B=s.createGain(),ie=`${C._id}-${U}`;W.connect(B),B.connect(k),console.log("[doConference] - In forEach connect track for",C._id),(Q=this.context.logger)==null||Q.log("[doConference] - In forEach connect track for",C._id),_.sources.set(ie,W),_.gains.set(ie,B),re++}catch(W){console.error(W)}}}),o&&this.activeStreamValue)try{const D=this.activeStream,U=s.createMediaStreamSource(D),X=s.createGain(),je=`${C._id}-local`;U.connect(X),X.connect(k),_.sources.set(je,U),_.gains.set(je,X)}catch(D){console.error(D)}else o&&(console.error(`Host room but no activeStreamValue - skipping host microphone for session ${C._id}`),(K=this.context.logger)==null||K.error(`Host room but no activeStreamValue - skipping host microphone for session ${C._id}`));const pe=C.connection.getSenders()[0],P=k.stream.getTracks();if(["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.processVAD(C,k.stream)),pe&&P[0])try{console.log("[doConference] - Final replaceTrack for",C._id),(z=this.context.logger)==null||z.log("[doConference] - Final replaceTrack for",C._id),await pe.replaceTrack(P[0]),this.muteReconfigure(C)}catch(D){console.error(D)}})}processCallerMute(t,n){const o=this.extendedCalls[t];o&&o.connection.getReceivers().length&&(o.localMuted=n,o.connection.getReceivers().forEach(a=>{a.track.enabled=!n}),this.updateCall(o))}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,_,d,h;let o=null;if(this.extendedCalls[t])o=t;else{const g=Object.values(this.extendedCalls).find(T=>T.id===t||T._id===t||T.id&&T.id.includes(t)||T._id&&T._id.includes(t));g&&(o=g.id)}if(!o){(s=this.context.logger)==null||s.warn(`[handleSipResponseForRingback] Could not find session for identifier ${t}, status ${n}`);return}const a=this.extendedCalls[o];if(!a){(r=this.context.logger)==null||r.warn(`[handleSipResponseForRingback] Call not found in extendedCalls for ${o}`);return}if(a.direction==="outgoing"){if(n===Ao.TRYING||n===Ao.RINGING){if(this.ringbackTimers[o])return;this.ringbackSessionProgressReceived[o]=!1,this.ringbackTimers[o]=setTimeout(()=>{var g;this.ringbackSessionProgressReceived[o]||(this.startLocalRingbackTone(o),(g=this.context.logger)==null||g.log(`[handleSipResponseForRingback] Started local ringback tone for call ${o} after 2 seconds without 183`)),delete this.ringbackTimers[o]},2e3),(_=this.context.logger)==null||_.log(`[handleSipResponseForRingback] Started 2-second timer for call ${o} after receiving ${n}`)}n===Ao.SESSION_PROGRESS&&(this.ringbackSessionProgressReceived[o]=!0,this.ringbackTimers[o]&&(clearTimeout(this.ringbackTimers[o]),delete this.ringbackTimers[o],(d=this.context.logger)==null||d.log(`[handleSipResponseForRingback] Cancelled ringback timer for call ${o} - 183 received`)),this.stopLocalRingbackTone(o),(h=this.context.logger)==null||h.log(`[handleSipResponseForRingback] Stopped local ringback tone for call ${o} - 183 received with SDP`))}}async startLocalRingbackTone(t){var n,o;if(!this.ringbackAudioContexts[t])try{const a=await this.managedAudioContext.getContext(),s=a.createOscillator(),r=a.createOscillator(),_=a.createGain();s.frequency.value=440,r.frequency.value=480,s.type="sine",r.type="sine",_.gain.value=0,s.connect(_),r.connect(_),_.connect(a.destination),s.start(),r.start();const d={context:a,oscillator1:s,oscillator2:r,gainNode:_,intervalId:null};this.ringbackAudioContexts[t]=d;const h=()=>{if(!this.ringbackAudioContexts[t])return;const T=a.currentTime;_.gain.cancelScheduledValues(T),_.gain.setValueAtTime(0,T),_.gain.linearRampToValueAtTime(.3,T+.05),_.gain.linearRampToValueAtTime(0,T+1)};h();const g=setInterval(()=>{if(!this.ringbackAudioContexts[t]){clearInterval(g);return}h()},4e3);d.intervalId=g,this.ringbackAudioContexts[t]=d,(n=this.context.logger)==null||n.log(`[startLocalRingbackTone] Started ringback tone for session ${t}`)}catch(a){(o=this.context.logger)==null||o.error(`[startLocalRingbackTone] Error starting ringback tone for session ${t}:`,a),console.error(`[startLocalRingbackTone] Error starting ringback tone for session ${t}:`,a)}}stopLocalRingbackTone(t){var o,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],(o=this.context.logger)==null||o.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]}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const o=this.extendedCalls[t];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${n}@${this.context.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:t,isTransferring:!0,isTransferred:!1}),o.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(o)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const o=n[0],a=n[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}mergeCallByIds(t,n){const o=Object.values(this.extendedCalls).find(s=>s._id===t),a=Object.values(this.extendedCalls).find(s=>s._id===n);if(!o||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o)}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 o=setInterval(()=>{const a={...this.callTime[t]},s=YT(a);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,o)}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 h,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};if(n.direction==="incoming")this.context.logger.log("New incoming call from",(g=(h=n._remote_identity)==null?void 0:h._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))});else if(n.direction==="outgoing"){const T=S=>{var C,H,k,re,x,F,_e,pe,P;const E=!!((C=S==null?void 0:S.response)!=null&&C.body),A=(k=(H=S==null?void 0:S.response)==null?void 0:H.getHeader)==null?void 0:k.call(H,"Content-Type"),R=(x=(re=S==null?void 0:S.response)==null?void 0:re.getHeader)==null?void 0:x.call(re,"Content-Length");console.log("PPP SDP Check:",{hasBody:E,contentType:A,contentLength:R,bodyLength:((_e=(F=S==null?void 0:S.response)==null?void 0:F.body)==null?void 0:_e.length)||0,bodyPreview:((P=(pe=S==null?void 0:S.response)==null?void 0:pe.body)==null?void 0:P.substring(0,100))||"N/A"}),S.response&&S.response.status_code===Ao.SESSION_PROGRESS&&(this.startCallTimer(n.id),n.off("progress",T))};n.on("progress",T),n.once("confirmed",()=>{this.startCallTimer(n.id)})}const r=n,_=this.hasAutoAnswerHeaders(t),d=r.direction==="incoming"&&!this.hasActiveCalls&&(_||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&&this.answerCall(r._id)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const o={...this.extendedCalls};delete o[t],this.extendedCalls={...o},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 o=n.roomId;this.removeCall(t._id),this.roomReconfigure(o).then(()=>{}).catch(a=>{console.error("Error reconfiguring room after call removal:",a)})}shouldTerminateNewSession(t){if(t.session.direction==="outgoing")return!1;const o=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||o}async newRTCSessionCallback(t){const n=t.session;if(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",a=>{var r,_,d;if(this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(_=(r=n._remote_identity)==null?void 0:r._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:n,event:a}),n.connection){const h=n.connection.connectionState;(h==="closed"||h==="disconnected")&&this.context.emit("connectionStateChange",{session:n,connectionState:h})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(n._id),this.cleanupRingbackTone(n.id);const s=this.getActiveCalls[n.id];s&&this.activeCallListRemove(s),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("progress",a=>{var s,r;this.context.logger.log("Session in progress for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:n,event:a})}),n.on("failed",a=>{var r,_,d;if(this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(_=(r=n._remote_identity)==null?void 0:r._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:n,event:a}),n.connection){const h=n.connection.connectionState;(h==="closed"||h==="disconnected")&&this.context.emit("connectionStateChange",{session:n,connectionState:h})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(n._id),this.cleanupRingbackTone(n.id),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const s=this.getActiveCalls[n.id];s&&this.activeCallListRemove(s),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("confirmed",a=>{var s,r;this.context.logger.log("Session confirmed for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateCall(n),this.cleanupRingbackTone(n.id),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)});const o=a=>{a&&a.addEventListener("connectionstatechange",s=>{this.context.emit("connectionStateChange",{session:n,connectionState:a.connectionState})})};if(n.connection&&o(n.connection),n.on("peerconnection",({peerconnection:a})=>{o(a)}),await this.setupCall(t),n.direction==="outgoing"){const a=this.getActiveCalls[n.id].roomId;await this.setActiveRoom(a)}}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(wo.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(wo.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 Vv(this.metricConfig),o=n.createProbe(t.connection,{cid:t._id}),a=[];let s;o.onreport=r=>{Object.entries(r.audio).forEach(([h,g])=>{g.direction==="inbound"&&!a.includes(h)&&(a.push(h),s=h)});const _=r.audio[s];if(!_)return;const d=jv(_,qv);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 o=this.muteWhenJoin||this.isMuted;this.setIsMuted(o),this.initialStreamValue||await this.setupStream();const a=await this.managedAudioContext.getContext(),s=await Au(a,this.initialStreamValue,this.microphoneInputLevel*2),r=this.isMuted||this.muteWhenJoin;s.getTracks().forEach(A=>{A.enabled=!r}),await this.setActiveStream(s),await n.connection.getSenders()[0].replaceTrack(s.getTracks()[0]);const h=new MediaStream([t.track]);!Object.values(this.extendedCalls).find(A=>A.audioTag&&A.audioTag.id===n._id)&&UT(h,n,this.selectedOutputDevice,this.speakerVolume);const T=n.roomId===this.currentActiveRoomId;n.audioTag&&(n.audioTag.muted=!T),await this.setupVUMeter(h,n._id),this.getCallQuality(n),this.updateCall(n),n.roomId!==void 0&&Object.values(this.extendedCalls).filter(R=>R.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.processVAD(n,s)}initCall(t,n,o=!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}),o)){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 o=this.extendedCalls[t];if(!o)return;const a=o.roomId;o.roomId=n,this.updateCall(o),await this.roomReconfigure(a),await this.roomReconfigure(n)}}class Jv{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 zv{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]=vd(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:vd(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const o=this.msrpHistory[n.id]||[];o.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...o]},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 o=t;this.addMMSRPSession(o)}triggerMSRPListener({listenerType:t,session:n,event:o}){const a=this.context.listenersList[t];!a||!a.length||a.forEach(s=>{s(n,o)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const o={...this.extendedMessages};delete o[t],this.extendedMessages={...o},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",o=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("failed",o=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("confirmed",o=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:o}),this.updateMSRPSession(n)}),n.on("newMessage",o=>{this.addMSRPMessage(o,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,o){if(t.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(t,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const o=this.extendedMessages[t];if(!o)throw new Error(`MSRP session with id ${t} doesn't exist!`);o.sendMSRP(n)}}const Oo={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Pd{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 Md extends Pd{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=ke.cloneArray(t.extraHeaders),o={from_tag:this.session._from_tag};t.fromUserName&&(o.from_uri=new ln("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(o.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 Tt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,o,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 Wr(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 o={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},a=JSON.stringify(o);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 o={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($.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async s=>{var r,_,d,h;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const g=JSON.parse(s.body)||{};((_=(r=g.plugindata)==null?void 0:r.data)==null?void 0:_.videoroom)==="joined"&&this.session.myFeedList.push(g.plugindata.data.id),(h=(d=g.plugindata)==null?void 0:d.data)!=null&&h.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(kt.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
- `),h=d[d.length-1],g=JSON.parse(h);await this._connection.setRemoteDescription(g.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(kt.DETACH)];this.session.sendRequest($.INFO,{extraHeaders:n,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(n=>{const o=n.track;o&&o.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Ld extends Pd{constructor(t,n,o={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=o.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}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 Xv extends bT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const o={...t.configuration,sockets:t.socketInterfaces.map(a=>new KT.WebSocketInterface(a))};super(o),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),n&&kT(n)&&(this.logger=n)}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(Oo.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Md)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Ld)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}reconnect(){if(this.reconnectionAttemptsCounter<this.reconnectionAttemptsLimit){const n=5e3*Math.pow(2,this.reconnectionAttemptsCounter);this.reconnectionAttemptsCounter++,setTimeout(this.start.bind(this),n)}else this.emit("reconnectionAttemptsLimitReached",void 0)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Oo.AUDIO)&&(this.audio=new Yv(this)),this.modules.includes(Oo.MSRP)&&(this.msrp=new zv(this)),this.modules.includes(Oo.VIDEO)&&(this.video=new Jv(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,n){const a=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:a}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:o}){const a=this.listenersList[t];!a||!a.length||a.forEach(s=>{s(n,o)})}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)}}return Wt.BaseNewStreamPlugin=Md,Wt.BaseProcessStreamPlugin=Ld,Wt.default=Xv,Object.defineProperties(Wt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),Wt}({});
158
+ `,n),a===-1)return a;!c.substring(a+2,a+4).match(/(^\r\n)/)&&c.charAt(a+2).match(/(^\s+)/)?n=a+2:o=a}return o}function yT(c,t,n,o){let a;const s=t.indexOf(":",n),r=t.substring(n,s).trim(),_=t.substring(s+1,o).trim();switch(r.toLowerCase()){case"via":case"v":c.addHeader("via",_),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",_),a=c.parseHeader("from"),a&&(c.from=a,c.from_tag=a.getParam("tag"));break;case"to":case"t":c.setHeader("to",_),a=c.parseHeader("to"),a&&(c.to=a,c.to_tag=a.getParam("tag"));break;case"record-route":if(a=Cu.parse(_,"Record_Route"),a===-1)a=void 0;else for(const d of a)c.addHeader("record-route",_.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",_),a=c.parseHeader("call-id"),a&&(c.call_id=_);break;case"contact":case"m":if(a=Cu.parse(_,"Contact"),a===-1)a=void 0;else for(const d of a)c.addHeader("contact",_.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",_),a=c.parseHeader("content-length");break;case"content-type":case"c":c.setHeader("content-type",_),a=c.parseHeader("content-type");break;case"cseq":c.setHeader("cseq",_),a=c.parseHeader("cseq"),a&&(c.cseq=a.value),c instanceof Ln.IncomingResponse&&(c.method=a.method);break;case"max-forwards":c.setHeader("max-forwards",_),a=c.parseHeader("max-forwards");break;case"www-authenticate":c.setHeader("www-authenticate",_),a=c.parseHeader("www-authenticate");break;case"proxy-authenticate":c.setHeader("proxy-authenticate",_),a=c.parseHeader("proxy-authenticate");break;case"session-expires":case"x":c.setHeader("session-expires",_),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",_),a=c.parseHeader("refer-to"),a&&(c.refer_to=a);break;case"replaces":c.setHeader("replaces",_),a=c.parseHeader("replaces"),a&&(c.replaces=a);break;case"event":case"o":c.setHeader("event",_),a=c.parseHeader("event"),a&&(c.event=a);break;default:c.addHeader(r,_),a=0}return a===void 0?{error:`error parsing header "${r}"`}:!0}const CT={parseMessage:ST},si=new no("Registrator"),Co=10;class AT{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=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 o=this._contact.indexOf(">");if(o!==-1){const a=this._contact.slice(0,o)+this._contact.slice(o+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 o=t[n];this._extraContactParams+=`;${n}`,o&&(this._extraContactParams+=`=${o}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];this._extraContactParams+=`;${n}`,o&&(this._extraContactParams+=`=${o}`)}}register(){if(this._registering){si.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 Tt.OutgoingRequest($.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),o=new Wr(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")){si.debug("no Contact header in response to REGISTER, response ignored");break}const s=a.headers.Contact.reduce((h,m)=>h.concat(m.parsed),[]);let r=s.find(h=>this._sipInstance===h.getParam("+sip.instance")&&this._reg_id===parseInt(h.getParam("reg-id")));if(r||(r=s.find(h=>h.uri.user===this._ua.contact.uri.user)),!r){si.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let _=r.getParam("expires");!_&&a.hasHeader("expires")&&(_=a.getHeader("expires")),_||(_=this._expires),_=Number(_),_<Co&&(_=Co);const d=_>64?_*1e3/2+Math.floor((_/2-32)*1e3*Math.random()):Math.floor(_*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<Co&&(this._expires=Co),this.register()):(si.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,$.causes.SIP_FAILURE_CODE));break}default:{const s=vs.sipErrorCause(a.status_code);this._registrationFailure(a,s)}}}});this._registering=!0,o.send()}unregister(t={}){if(!this._registered){si.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 o=new Tt.OutgoingRequest($.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new Wr(this._ua,o,{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=vs.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 tt=console,Ps={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},RT=fT;class bT extends RT{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 AT(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(t,n){return super.call(t,n)}joinVideoCall(t,n,o){tt.debug("call()");const a=new Eo(this);return a.configureMedia({audio:!0,video:!0}),a.connect(t,n,o),a}startScreenShare(){tt.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{ti.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=vs.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=vs.createRandomToken(5);const o=this._configuration.uri.clone();o.user=null,this._configuration.hostport_params=o.toString().replace(/^sip:/i,"");try{this._transport=new Lm(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=IT.bind(this),this._transport.onconnect=wT.bind(this),this._transport.ondisconnect=OT.bind(this),this._transport.ondata=DT.bind(this)}catch(s){throw tt.warn(s),new Ns.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 ln("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(s={}){const r=s.anonymous||null,_=s.outbound||null;let d="<";return r?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),_&&(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}));tt.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(ti.settings,s))switch(s){case"uri":case"registrar_server":tt.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":tt.debug(`- ${s}: NOT SHOWN`);break;default:tt.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,n){t.on("msgHistoryUpdate",o=>{console.log(o)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",n)}newJanusSession(t,n){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(o=>{o.setSession(t)}),this.processStreamPlugins.forEach(o=>{o.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,_,d;const n=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){tt.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(Ht.checkTransaction(this,t))return;if(n===De.INVITE?new Ht.InviteServerTransaction(this,this._transport,t):n!==De.ACK&&n!==De.CANCEL&&new Ht.NonInviteServerTransaction(this,this._transport,t),n===De.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const m=Date.now(),T=this.lastOptionsTimestamp>m-35e3,S=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>m;T&&S&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){t.reply(200);return}new Cf.Options(this).init_incoming(t)}else if(n===De.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new Cf.Message(this).init_incoming(t)}else if(n===De.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let o,a;if(t.to_tag)if(o=this._findDialog(t.call_id,t.from_tag,t.to_tag),o)o.receiveRequest(t);else if(n===De.NOTIFY)if(a=this._findSession(t),a)a.receiveRequest(t);else{if(t.body)try{const h=JSON.parse(t.body)||{};(r=(s=h.plugindata)==null?void 0:s.data)!=null&&r.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(h),(d=(_=h.plugindata)==null?void 0:_.data)!=null&&d.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(h.plugindata.data.unpublished)}catch(h){console.error(h)}t.reply(200)}else n!==De.ACK&&t.reply(481);else switch(n){case De.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const h=t.replaces;o=this._findDialog(h.call_id,h.from_tag,h.to_tag),o?(a=o.owner,a.isEnded()?t.reply(603):a.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(a=new yu(this),a.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(a=new Em(this),a.init_incoming(t));else tt.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):tt.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){tt.debug("startMSRP()",n);const o=new yu(this);return o.connect(t),o}startJanus(t,n){tt.debug("startJanus()",n);const o=new yu(this);return o.connect(t),o}terminateMSRPSessions(t){tt.debug("terminateSessions()");for(const n in this._msrp_sessions)this._msrp_sessions[n].isEnded()||this._msrp_sessions[n].terminate(t)}terminateJanusSessions(t){tt.debug("terminateSessions()");for(const n in this._janus_sessions)this._janus_sessions[n].isEnded()||this._janus_sessions[n].terminate(t)}enableJanusAudio(t){tt.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){tt.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)){tt.debug(`closing session ${t}`);try{this._sessions[t].terminate()}catch(n){console.error(n)}}}stop(t=!0){if(tt.debug("stop()"),this._dynConfiguration={},this._status===Ps.STATUS_USER_CLOSED){tt.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)){tt.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)){tt.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=Ps.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 IT(c){this.emit("connecting",c)}function wT(c){this._status!==Ps.STATUS_USER_CLOSED&&(this._status=Ps.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 o in this._transactions[n])Object.prototype.hasOwnProperty.call(this._transactions[n],o)&&this._transactions[n][o].onTransportError();this.emit("disconnected",c),this._registrator.onTransportClosed(),this._status!==Ps.STATUS_USER_CLOSED&&(this._status=Ps.STATUS_NOT_READY,this._error=Ps.NETWORK_ERROR)}function DT(c){const t=c.transport;let n=c.message;const o=n;if(n=CT.parseMessage(n,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(n,o),!!n&&!(this._status===Ps.STATUS_USER_CLOSED&&n instanceof Ln.IncomingRequest)&&Qm(n,this,t)){if(n instanceof Ln.IncomingRequest)n.transport=t,this.receiveRequest(n);else if(n instanceof Ln.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(h=>h._id&&h._id.includes(n.call_id)||h.id&&h.id.includes(n.call_id)||h.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 NT=["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"],xT=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Td(c){const t={};return NT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t.localHold=c._localHold,t}function vd(c){const t={};return xT.forEach(n=>{c[n]!==void 0&&(t[n]=c[n])}),t}async function Au(c,t,n){const o=c.createMediaStreamSource(t),a=c.createMediaStreamDestination(),s=c.createGain();return o.connect(s),s.connect(a),s.gain.value=n,a.stream}function UT(c,t,n,o){if(Sd())return;const a=document.createElement("audio");a.id=t._id,a.className="audioTag",a.srcObject=c,a.setSinkId(n),a.volume=o,a.play(),t.audioTag=a}function kT(c){if(c&&typeof c.log=="function"&&typeof c.warn=="function"&&typeof c.error=="function")return!0}function Sd(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const PT=ot,MT=Yt(),Ot=new PT("WebSocketInterface");var LT=class{constructor(t){Ot.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=MT.parse(t,"absoluteURI");if(n===-1)throw Ot.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Ot.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(Ot.debug("connect()"),this.isConnected()){Ot.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ot.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ot.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(){Ot.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 Ot.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Ot.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(){Ot.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:n,reason:o}){Ot.debug(`WebSocket ${this._url} closed`),t===!1&&Ot.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,n,o)}_onMessage({data:t}){Ot.debug("received WebSocket message"),this.ondata(t)}_onError(t){Ot.warn(`WebSocket ${this._url} error: `,t)}};const Ru=Tl,$T=De,HT=Ts,FT=gt(),VT=pd,jT=ps(),qT=Ba(),BT=Yt(),GT=LT;Nn("JsSIP")("version %s",Ru.version);var WT={C:$T,Exceptions:HT,Utils:FT,UA:VT,URI:jT,NameAddrHeader:qT,WebSocketInterface:GT,Grammar:BT,debug:Nn,get name(){return Ru.title},get version(){return Ru.version}};const KT=Me(WT);function bu(c){return c<10?`0${c}`:`${c}`}function YT(c){let t=c.hours||0,n=c.minutes||0,o=c.seconds||0;o++,o===60&&(o=0,n++,n===60&&(n=0,t++));const a=`${bu(t)}:${bu(n)}:${bu(o)}`;return{seconds:o,minutes:n,hours:t,formatted:a}}function JT(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 zT(c,t,n=150){const o=t.createMediaStreamSource(c),a=t.createDelay();a.delayTime.value=n/1e3;const s=t.createGain();s.gain.value=0;const r=t.createMediaStreamDestination();return o.connect(a).connect(s).connect(r),{stream:r.stream,setSpeaking:_=>{s.gain.value=_?1:0}}}var yt={};yt.forEach=async(c,t,n)=>{const o=[];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));o.push(s)}await Promise.all(o)},yt.forEachSeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)o in c&&await t.call(n||globalThis,await c[o],o,c)},yt.map=async(c,t,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=Promise.resolve(c[a]).then(s=>t.call(n||globalThis,s,a,c)));return Promise.all(o)},yt.mapSeries=async(c,t,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&(o[a]=await t.call(n||globalThis,await c[a],a,c));return o},yt.find=(c,t,n)=>new Promise((o,a)=>{if(c.length===0)return o();let s=1;for(let r=0;r<c.length;r++){const _=d=>{d?o(c[r]):s===c.length&&o(),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(_).catch(a)}}),yt.findSeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)if(await t.call(n||globalThis,await c[o],o,c))return c[o]},yt.findIndex=(c,t,n)=>new Promise((o,a)=>{if(c.length===0)return o(-1);let s=1;for(let r=0;r<c.length;r++){const _=d=>{d?o(r):s===c.length&&o(-1),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(_).catch(a)}}),yt.findIndexSeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)if(await t.call(n||globalThis,await c[o],o,c))return o},yt.some=(c,t,n)=>new Promise((o,a)=>{if(c.length===0)return o(!1);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const _=d=>{d?o(!0):s===c.length&&o(!1),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(_).catch(a)}}),yt.someSeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)if(o in c&&await t.call(n||globalThis,await c[o],o,c))return!0;return!1},yt.every=(c,t,n)=>new Promise((o,a)=>{if(c.length===0)return o(!0);let s=1;for(let r=0;r<c.length;r++){if(!(r in c)){s++;continue}const _=d=>{d?s===c.length&&o(!0):o(!1),s++};Promise.resolve(c[r]).then(d=>t.call(n||globalThis,d,r,c)).then(_).catch(a)}}),yt.everySeries=async(c,t,n)=>{for(let o=0;o<c.length;o++)if(o in c&&!await t.call(n||globalThis,await c[o],o,c))return!1;return!0},yt.filter=(c,t,n)=>new Promise(async(o,a)=>{const s=[];for(let _=0;_<c.length;_++)_ in c&&(s[_]=Promise.resolve(c[_]).then(d=>t.call(n||globalThis,d,_,c)).catch(a));const r=[];for(let _=0;_<s.length;_++)await s[_]&&r.push(await c[_]);o(r)}),yt.filterSeries=async(c,t,n)=>{const o=[];for(let a=0;a<c.length;a++)a in c&&await t.call(n||globalThis,await c[a],a,c)&&o.push(await c[a]);return o},yt.reduce=async(c,t,n)=>{if(c.length===0&&n===void 0)throw TypeError("Reduce of empty array with no initial value");let o,a;for(n!==void 0?(a=n,o=0):(a=c[0],o=1),o;o<c.length;o++)o in c&&(a=await t(await a,await c[o],o,c));return a};var Ed={};(function(c){const t=yt;Object.keys(t).forEach(n=>{const o=n.charAt(0).toUpperCase()+n.slice(1);c[`async${o}`]=async function(...a){return t[n](this,...a)}})})(Ed);var XT=Object.assign(yt,{instanceMethods:Ed});const Xt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},Ao={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 QT={exports:{}};(function(c){var t=function(n){var o=Object.prototype,a=o.hasOwnProperty,s=Object.defineProperty||function(Q,W,B){Q[W]=B.value},r,_=typeof Symbol=="function"?Symbol:{},d=_.iterator||"@@iterator",h=_.asyncIterator||"@@asyncIterator",m=_.toStringTag||"@@toStringTag";function T(Q,W,B){return Object.defineProperty(Q,W,{value:B,enumerable:!0,configurable:!0,writable:!0}),Q[W]}try{T({},"")}catch{T=function(W,B,ie){return W[B]=ie}}function S(Q,W,B,ie){var ve=W&&W.prototype instanceof re?W:re,Ie=Object.create(ve.prototype),Pe=new U(ie||[]);return s(Ie,"_invoke",{value:K(Q,B,Pe)}),Ie}n.wrap=S;function E(Q,W,B){try{return{type:"normal",arg:Q.call(W,B)}}catch(ie){return{type:"throw",arg:ie}}}var A="suspendedStart",R="suspendedYield",C="executing",H="completed",k={};function re(){}function x(){}function F(){}var _e={};T(_e,d,function(){return this});var pe=Object.getPrototypeOf,P=pe&&pe(pe(X([])));P&&P!==o&&a.call(P,d)&&(_e=P);var N=F.prototype=re.prototype=Object.create(_e);x.prototype=F,s(N,"constructor",{value:F,configurable:!0}),s(F,"constructor",{value:x,configurable:!0}),x.displayName=T(F,m,"GeneratorFunction");function q(Q){["next","throw","return"].forEach(function(W){T(Q,W,function(B){return this._invoke(W,B)})})}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,F):(Q.__proto__=F,T(Q,m,"GeneratorFunction")),Q.prototype=Object.create(N),Q},n.awrap=function(Q){return{__await:Q}};function j(Q,W){function B(Ie,Pe,Re,oe){var ye=E(Q[Ie],Q,Pe);if(ye.type==="throw")oe(ye.arg);else{var lt=ye.arg,at=lt.value;return at&&typeof at=="object"&&a.call(at,"__await")?W.resolve(at.__await).then(function(Ee){B("next",Ee,Re,oe)},function(Ee){B("throw",Ee,Re,oe)}):W.resolve(at).then(function(Ee){lt.value=Ee,Re(lt)},function(Ee){return B("throw",Ee,Re,oe)})}}var ie;function ve(Ie,Pe){function Re(){return new W(function(oe,ye){B(Ie,Pe,oe,ye)})}return ie=ie?ie.then(Re,Re):Re()}s(this,"_invoke",{value:ve})}q(j.prototype),T(j.prototype,h,function(){return this}),n.AsyncIterator=j,n.async=function(Q,W,B,ie,ve){ve===void 0&&(ve=Promise);var Ie=new j(S(Q,W,B,ie),ve);return n.isGeneratorFunction(W)?Ie:Ie.next().then(function(Pe){return Pe.done?Pe.value:Ie.next()})};function K(Q,W,B){var ie=A;return function(Ie,Pe){if(ie===C)throw new Error("Generator is already running");if(ie===H){if(Ie==="throw")throw Pe;return je()}for(B.method=Ie,B.arg=Pe;;){var Re=B.delegate;if(Re){var oe=V(Re,B);if(oe){if(oe===k)continue;return oe}}if(B.method==="next")B.sent=B._sent=B.arg;else if(B.method==="throw"){if(ie===A)throw ie=H,B.arg;B.dispatchException(B.arg)}else B.method==="return"&&B.abrupt("return",B.arg);ie=C;var ye=E(Q,W,B);if(ye.type==="normal"){if(ie=B.done?H:R,ye.arg===k)continue;return{value:ye.arg,done:B.done}}else ye.type==="throw"&&(ie=H,B.method="throw",B.arg=ye.arg)}}}function V(Q,W){var B=W.method,ie=Q.iterator[B];if(ie===r)return W.delegate=null,B==="throw"&&Q.iterator.return&&(W.method="return",W.arg=r,V(Q,W),W.method==="throw")||B!=="return"&&(W.method="throw",W.arg=new TypeError("The iterator does not provide a '"+B+"' method")),k;var ve=E(ie,Q.iterator,W.arg);if(ve.type==="throw")return W.method="throw",W.arg=ve.arg,W.delegate=null,k;var Ie=ve.arg;if(!Ie)return W.method="throw",W.arg=new TypeError("iterator result is not an object"),W.delegate=null,k;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,k}q(N),T(N,m,"Generator"),T(N,d,function(){return this}),T(N,"toString",function(){return"[object Generator]"});function z(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 D(Q){var W=Q.completion||{};W.type="normal",delete W.arg,Q.completion=W}function U(Q){this.tryEntries=[{tryLoc:"root"}],Q.forEach(z,this),this.reset(!0)}n.keys=function(Q){var W=Object(Q),B=[];for(var ie in W)B.push(ie);return B.reverse(),function ve(){for(;B.length;){var Ie=B.pop();if(Ie in W)return ve.value=Ie,ve.done=!1,ve}return ve.done=!0,ve}};function X(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 B=-1,ie=function ve(){for(;++B<Q.length;)if(a.call(Q,B))return ve.value=Q[B],ve.done=!1,ve;return ve.value=r,ve.done=!0,ve};return ie.next=ie}}return{next:je}}n.values=X;function je(){return{value:r,done:!0}}return U.prototype={constructor:U,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(D),!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 B(oe,ye){return Ie.type="throw",Ie.arg=Q,W.next=oe,ye&&(W.method="next",W.arg=r),!!ye}for(var ie=this.tryEntries.length-1;ie>=0;--ie){var ve=this.tryEntries[ie],Ie=ve.completion;if(ve.tryLoc==="root")return B("end");if(ve.tryLoc<=this.prev){var Pe=a.call(ve,"catchLoc"),Re=a.call(ve,"finallyLoc");if(Pe&&Re){if(this.prev<ve.catchLoc)return B(ve.catchLoc,!0);if(this.prev<ve.finallyLoc)return B(ve.finallyLoc)}else if(Pe){if(this.prev<ve.catchLoc)return B(ve.catchLoc,!0)}else if(Re){if(this.prev<ve.finallyLoc)return B(ve.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Q,W){for(var B=this.tryEntries.length-1;B>=0;--B){var ie=this.tryEntries[B];if(ie.tryLoc<=this.prev&&a.call(ie,"finallyLoc")&&this.prev<ie.finallyLoc){var ve=ie;break}}ve&&(Q==="break"||Q==="continue")&&ve.tryLoc<=W&&W<=ve.finallyLoc&&(ve=null);var Ie=ve?ve.completion:{};return Ie.type=Q,Ie.arg=W,ve?(this.method="next",this.next=ve.finallyLoc,k):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),k},finish:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var B=this.tryEntries[W];if(B.finallyLoc===Q)return this.complete(B.completion,B.afterLoc),D(B),k}},catch:function(Q){for(var W=this.tryEntries.length-1;W>=0;--W){var B=this.tryEntries[W];if(B.tryLoc===Q){var ie=B.completion;if(ie.type==="throw"){var ve=ie.arg;D(B)}return ve}}throw new Error("illegal catch attempt")},delegateYield:function(Q,W,B){return this.delegate={iterator:X(Q),resultName:W,nextLoc:B},this.method==="next"&&(this.arg=r),k}},n}(c.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(QT);var yd={exports:{}};(function(c){(function(t,n){c.exports?c.exports=n():t.log=n()})(cs,function(){var t=function(){},n="undefined",o=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function s(R,C){var H=R[C];if(typeof H.bind=="function")return H.bind(R);try{return Function.prototype.bind.call(H,R)}catch{return function(){return Function.prototype.apply.apply(H,[R,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 _(R){return R==="debug"&&(R="log"),typeof console===n?!1:R==="trace"&&o?r:console[R]!==void 0?s(console,R):console.log!==void 0?s(console,"log"):t}function d(R,C){for(var H=0;H<a.length;H++){var k=a[H];this[k]=H<R?t:this.methodFactory(k,R,C)}this.log=this.debug}function h(R,C,H){return function(){typeof console!==n&&(d.call(this,C,H),this[R].apply(this,arguments))}}function m(R,C,H){return _(R)||h.apply(this,arguments)}function T(R,C,H){var k=this,re;C=C??"WARN";var x="loglevel";typeof R=="string"?x+=":"+R:typeof R=="symbol"&&(x=void 0);function F(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 _e(){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 k.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{}}}k.name=R,k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.methodFactory=H||m,k.getLevel=function(){return re},k.setLevel=function(N,q){if(typeof N=="string"&&k.levels[N.toUpperCase()]!==void 0&&(N=k.levels[N.toUpperCase()]),typeof N=="number"&&N>=0&&N<=k.levels.SILENT){if(re=N,q!==!1&&F(N),d.call(k,N,R),typeof console===n&&N<k.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+N},k.setDefaultLevel=function(N){C=N,_e()||k.setLevel(N,!1)},k.resetLevel=function(){k.setLevel(C,!1),pe()},k.enableAll=function(N){k.setLevel(k.levels.TRACE,N)},k.disableAll=function(N){k.setLevel(k.levels.SILENT,N)};var P=_e();P==null&&(P=C),k.setLevel(P,!1)}var S=new T,E={};S.getLogger=function(C){if(typeof C!="symbol"&&typeof C!="string"||C==="")throw new TypeError("You must supply a name when creating a logger.");var H=E[C];return H||(H=E[C]=new T(C,S.getLevel(),S.methodFactory)),H};var A=typeof window!==n?window.log:void 0;return S.noConflict=function(){return typeof window!==n&&window.log===S&&(window.log=A),S},S.getLoggers=function(){return E},S.default=S,S})})(yd);var bt=yd.exports;const Ss=()=>`${new Date().toISOString()} | metrics`,Es=(c,t,n)=>`${c} | ${t} | ${n}`;bt.setDefaultLevel(bt.levels.TRACE);const ZT=c=>{bt.info(Es(Ss(),"log ",`set log level to ${c?"verbose":"info"}`)),bt.setLevel(c?bt.levels.TRACE:bt.levels.INFO)},ev=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,n)=>{n?bt.debug(Es(Ss(),c,t),n):bt.debug(Es(Ss(),c,t))},Iu=(c,t)=>{bt.info(Es(Ss(),c,t))},on=(c,t)=>{bt.info(Es(Ss(),c,t))},Ro=(c,t)=>{bt.warn(Es(Ss(),c,t))},jn=(c,t)=>{bt.error(Es(Ss(),c,t))};function tv(c){return Math.floor(Math.random()*c).toString()}function Cd(c,t){let n=t;return c.forEach(o=>{n=n.replace(o,"")}),n}function sv(c,t){let n="";for(let o=0;o<t;o+=1)n+=c[tv(c.length)];return n}function nv({length:c=20,useLetters:t=!0,useNumbers:n=!0,includeSymbols:o=[],excludeSymbols:a=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",r="0123456789",_=[],d=[],h=[];return t&&(a.length&&(s=Cd(a,s)),d=s.split("")),n&&(a.length&&(r=Cd(a,r)),h=r.split("")),_=[...d,...h,...o],sv(_,c)}var rv=nv;const ni=Me(rv),iv=()=>"WebRTCMetrics",lv=()=>"5.0.3",$e={INBOUND:"inbound",OUTBOUND:"outbound"},ys={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ri={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},ov=()=>({...{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:[]}}),Ad={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},Rd={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},bd={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},Id={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},av=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(o=>{n.audio[o]={...c.audio[o]}}),Object.keys(c.video).forEach(o=>{n.video[o]={...c.video[o]}}),n}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},uv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${ni()}`,cid:`c-${ni()}`,uid:`u-${ni()}`,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"},G={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"},ii={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},wu={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},ne={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Ou="config ",cv=(c,t={},n)=>{const o={...n,...t};return t.pname||Ro(Ou,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${n.pname}'`),t.cid||Ro(Ou,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${n.cid}'`),t.uid||Ro(Ou,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${n.uid}'`),o.pc=c,o},fv=(c={})=>{const t={...uv,...c};return t.name=iv(),t.version=lv(),t},li=(c,t,n,o=!1,a)=>{let s=c.map(r=>{if(!n)return r[t];if(!a)return r[t][n];const _=r[t][a];return _?_[n]:null});return s=s.filter(r=>o?Number.isFinite(r)&&r>0:Number.isFinite(r)),s.length===0?[]:s},Ms=c=>c.reduce((t,n)=>t+n,0)/c.length,dv=()=>`probe-${ni()}`,hv=()=>`coltr-${ni()}`,wd=c=>new Promise(t=>setTimeout(t,c)),Du=(c,t,n)=>{t?c.call(t,n):c(n)},Ke=(c,t,n,o)=>{const a=li(c,t,n,!0,o);if(a.length===0)return null;const s=a.reduce((h,m)=>h+m,0)/a.length;return s===0?null:a.map(h=>Math.abs(s-h)).reduce((h,m)=>h+m,0)/a.length*100/s},Qe=(c,t,n,o=!1,a)=>{const s=li(c,t,n,o,a);return s.length===0?null:s.reduce((r,_)=>r+_,0)/s.length},an=(c,t,n)=>li(c,t,n).reduce((a,s)=>a+s,0),Ye=(c,t,n,o)=>{const a=li(c,t,n,!0,o);return a.length===0?null:Math.min(...a)},Je=(c,t,n,o)=>{const a=li(c,t,n,!1,o);return a.length===0?null:Math.max(...a)},Ct=(c,t,n,o)=>{const a=c.slice().pop();if(!a)return null;if(!n)return a[t];if(!o)return a[t][n];const s=a[t][o];return s?s[n]:null},_v=c=>c.slice().pop(),dt=(c,t,n)=>{if(!t)return null;const o={};let a=t[M.AUDIO][c];a||(a=n===$e.INBOUND?{...Ad}:{...Rd}),o[M.AUDIO]=a;let s=t[M.VIDEO][c];return s||(s=n===$e.INBOUND?{...bd}:{...Id}),o[M.VIDEO]=s,o},oi="exporter ",pv="2.0",Od=(c,t,n)=>{if(!c||c.length===0)return 0;const o=c[c.length-1];if(!o)return 0;const a=o[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},gv=(c,t)=>{if(!c||c.length===0)return 0;const n=c[c.length-1];if(!n)return 0;const o=n[t].total_rtt_connectivity_ms,a=n[t].total_rtt_connectivity_measure;return!a||!o?Qe(c,t,"delta_rtt_connectivity_ms"):Number(o/a)},mv=c=>Ct(c,"network","local_candidate_type")!=="relay"?`direct/${Ct(c,"network","local_candidate_protocol")}`:`turn/${Ct(c,"network","local_candidate_relay_protocol")}`,Tv=c=>{const t=Ct(c,"network","remote_candidate_type"),n=Ct(c,"network","remote_candidate_protocol");return t!=="relay"?`direct/${n}`:`turn/${n}`};class vv{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){Iu(oi,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){Iu(oi,"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(oi,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){Iu(oi,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ue(oi,"ticket() - generate ticket");const t=Ct(this._reports,"audio","total_packets_lost_in"),n=Ct(this._reports,"audio","total_packets_in"),o=Ct(this._reports,"video","total_packets_lost_in"),a=Ct(this._reports,"video","total_packets_in"),s={},r=_v(this._reports);return r&&(Object.keys(r[M.AUDIO]).forEach(_=>{const d=r[M.AUDIO][_];if(s[d.ssrc]={type:M.AUDIO,direction:d.direction},d.direction===$e.INBOUND){const h={avg:Qe(this._reports,M.AUDIO,"delta_jitter_ms_in",!1,_),min:Ye(this._reports,M.AUDIO,"delta_jitter_ms_in",_),max:Je(this._reports,M.AUDIO,"delta_jitter_ms_in",_),volatility:Ke(this._reports,M.AUDIO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},m={avg:Qe(this._reports,M.AUDIO,"delta_kbs_in",!1,_),min:Ye(this._reports,M.AUDIO,"delta_kbs_in",_),max:Je(this._reports,M.AUDIO,"delta_kbs_in",_),volatility:Ke(this._reports,M.AUDIO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.AUDIO,"delta_KBytes_in",!1,_),min:Ye(this._reports,M.AUDIO,"delta_KBytes_in",_),max:Je(this._reports,M.AUDIO,"delta_KBytes_in",_),volatility:Ke(this._reports,M.AUDIO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={emodel:{avg:Qe(this._reports,M.AUDIO,"mos_emodel_in",!1,_),min:Ye(this._reports,M.AUDIO,"mos_emodel_in",_),max:Je(this._reports,M.AUDIO,"mos_emodel_in",_),volatility:Ke(this._reports,M.AUDIO,"mos_emodel_in",_)},effective:{avg:Qe(this._reports,M.AUDIO,"mos_in",!1,_),min:Ye(this._reports,M.AUDIO,"mos_in",_),max:Je(this._reports,M.AUDIO,"mos_in",_),volatility:Ke(this._reports,M.AUDIO,"mos_in",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},E=Ct(this._reports,M.AUDIO,"total_packets_lost_in",_),A=Ct(this._reports,M.AUDIO,"total_packets_in",_),R={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[_].jitter=h,s[_].mos=S,s[_].traffic=T,s[_].bitrate=m,s[_].loss=R}else{const h={avg:Qe(this._reports,M.AUDIO,"delta_jitter_ms_out",!1,_),min:Ye(this._reports,M.AUDIO,"delta_jitter_ms_out",_),max:Je(this._reports,M.AUDIO,"delta_jitter_ms_out",_),volatility:Ke(this._reports,M.AUDIO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},m={avg:Qe(this._reports,M.AUDIO,"delta_kbs_out",!1,_),min:Ye(this._reports,M.AUDIO,"delta_kbs_out",_),max:Je(this._reports,M.AUDIO,"delta_kbs_out",_),volatility:Ke(this._reports,M.AUDIO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.AUDIO,"delta_KBytes_out",!1,_),min:Ye(this._reports,M.AUDIO,"delta_KBytes_out",_),max:Je(this._reports,M.AUDIO,"delta_KBytes_out",_),volatility:Ke(this._reports,M.AUDIO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},S={avg:Od(this._reports,M.AUDIO,_),min:Ye(this._reports,M.AUDIO,"delta_rtt_ms_out",_),max:Je(this._reports,M.AUDIO,"delta_rtt_ms_out",_),volatility:Ke(this._reports,M.AUDIO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=Ct(this._reports,M.AUDIO,"total_packets_lost_out",_),A=Ct(this._reports,M.AUDIO,"total_packets_out",_),R={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},C={emodel:{avg:Qe(this._reports,M.AUDIO,"mos_emodel_out",!1,_),min:Ye(this._reports,M.AUDIO,"mos_emodel_out",_),max:Je(this._reports,M.AUDIO,"mos_emodel_out",_),volatility:Ke(this._reports,M.AUDIO,"mos_emodel_out",_)},effective:{avg:Qe(this._reports,M.AUDIO,"mos_out",!1,_),min:Ye(this._reports,M.AUDIO,"mos_out",_),max:Je(this._reports,M.AUDIO,"mos_out",_),volatility:Ke(this._reports,M.AUDIO,"mos_out",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[_].jitter=h,s[_].rtt=S,s[_].traffic=T,s[_].bitrate=m,s[_].loss=R,s[_].mos=C}}),Object.keys(r[M.VIDEO]).forEach(_=>{const d=r[M.VIDEO][_];if(s[_]={type:M.VIDEO,direction:d.direction},d.direction===$e.INBOUND){const h={avg:Qe(this._reports,M.VIDEO,"delta_jitter_ms_in",!1,_),min:Ye(this._reports,M.VIDEO,"delta_jitter_ms_in",_),max:Je(this._reports,M.VIDEO,"delta_jitter_ms_in",_),volatility:Ke(this._reports,M.VIDEO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},m={avg:Qe(this._reports,M.VIDEO,"delta_kbs_in",!1,_),min:Ye(this._reports,M.VIDEO,"delta_kbs_in",_),max:Je(this._reports,M.VIDEO,"delta_kbs_in",_),volatility:Ke(this._reports,M.VIDEO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.VIDEO,"delta_KBytes_in",!1,_),min:Ye(this._reports,M.VIDEO,"delta_KBytes_in",_),max:Je(this._reports,M.VIDEO,"delta_KBytes_in",_),volatility:Ke(this._reports,M.VIDEO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S=Ct(this._reports,M.VIDEO,"total_packets_lost_in",_),E=Ct(this._reports,M.VIDEO,"total_packets_in",_),A={lost:S,avg:Math.round((S/(S+E)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[_].jitter=h,s[_].traffic=T,s[_].bitrate=m,s[_].loss=A}else{const h={avg:Qe(this._reports,M.VIDEO,"delta_jitter_ms_out",!1,_),min:Ye(this._reports,M.VIDEO,"delta_jitter_ms_out",_),max:Je(this._reports,M.VIDEO,"delta_jitter_ms_out",_),volatility:Ke(this._reports,M.VIDEO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},m={avg:Qe(this._reports,M.VIDEO,"delta_kbs_out",!1,_),min:Ye(this._reports,M.VIDEO,"delta_kbs_out",_),max:Je(this._reports,M.VIDEO,"delta_kbs_out",_),volatility:Ke(this._reports,M.VIDEO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Qe(this._reports,M.VIDEO,"delta_KBytes_out",!1,_),min:Ye(this._reports,M.VIDEO,"delta_KBytes_out",_),max:Je(this._reports,M.VIDEO,"delta_KBytes_out",_),volatility:Ke(this._reports,M.VIDEO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},S={avg:Od(this._reports,M.VIDEO,_),min:Ye(this._reports,M.VIDEO,"delta_rtt_ms_out",_),max:Je(this._reports,M.VIDEO,"delta_rtt_ms_out",_),volatility:Ke(this._reports,M.VIDEO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},E=Ct(this._reports,M.VIDEO,"total_packets_lost_out",_),A=Ct(this._reports,M.VIDEO,"total_packets_out",_),R={lost:E,avg:Math.round((E/(E+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[_].jitter=h,s[_].rtt=S,s[_].traffic=T,s[_].bitrate=m,s[_].loss=R}})),{version:pv,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:gv(this._reports,"data"),min:Ye(this._reports,"data","delta_rtt_connectivity_ms"),max:Je(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ke(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((o/(o+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Qe(this._reports,"data","delta_kbs_in"),min:Ye(this._reports,"data","delta_kbs_in"),max:Je(this._reports,"data","delta_kbs_in"),volatility:Ke(this._reports,"data","delta_kbs_in")},out:{avg:Qe(this._reports,"data","delta_kbs_out"),min:Ye(this._reports,"data","delta_kbs_out"),max:Je(this._reports,"data","delta_kbs_out"),volatility:Ke(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:Ye(this._reports,"data","delta_KBytes_in"),max:Je(this._reports,"data","delta_KBytes_in"),volatility:Ke(this._reports,"data","delta_KBytes_in")},out:{avg:Qe(this._reports,"data","delta_KBytes_out"),min:Ye(this._reports,"data","delta_KBytes_out"),max:Je(this._reports,"data","delta_KBytes_out"),volatility:Ke(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:mv(this._reports),remoteConnection:Tv(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 Ls="extractor ",Dd=(c,t,n,o)=>{let a=!1;const s=o[t].total_rtt_ms_out,r=o[t].total_rtt_measure_out,_=n?n[t].total_rtt_ms_out:0,d=n?n[t].total_rtt_measure_out:0,h={rtt:null,totalRTT:s,totalRTTMeasurements:r};if(c[G.TIMESTAMP]===o[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,G.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(c,G.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(c[G.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(c[G.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===r))return h;const m=1e3*Number(c[G.ROUND_TRIP_TIME]);let T=s+m,S=r+1;return a&&(T=1e3*Number(c[G.TOTAL_ROUND_TRIP_TIME])-_,S=Number(c[G.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:m,totalRTT:T,totalRTTMeasurements:S}},Sv=(c,t,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,G.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:o[t].total_rtt_connectivity_ms,totalRTTMeasurements:o[t].total_rtt_connectivity_measure};const a=1e3*Number(c[G.CURRENT_ROUND_TRIP_TIME]);let s=o[t].total_rtt_connectivity_ms+a,r=o[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(c,G.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(c[G.TOTAL_ROUND_TRIP_TIME])-(n?n[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(c,G.RESPONSES_RECEIVED)&&(r=Number(c[G.RESPONSES_RECEIVED])-(n?n[t].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:s,totalRTTMeasurements:r}},bo=(c,t,n)=>c[G.TIMESTAMP]===n[t].timestamp_out||!Object.prototype.hasOwnProperty.call(c,G.JITTER)?null:1e3*(Number(c[G.JITTER])||0),Ev=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,G.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(c,G.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[G.FRAMES_DECODED],o=c[G.TOTAL_DECODE_TIME],a=o-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:o}},yv=(c,t)=>{if(!Object.prototype.hasOwnProperty.call(c,G.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(c,G.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[G.FRAMES_ENCODED],o=c[G.TOTAL_ENCODE_TIME],a=o-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:o}},Nd=(c,t,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,G.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(c,G.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[G.PACKETS_SENT])||0-(o?o[t].total_packets_out:0),s=a-n[t].total_packets_out,r=Number(c[G.BYTES_SENT])/1024-(o?o[t].total_KBytes_out:0),_=r-n[t].total_KBytes_out,d=c[G.TIMESTAMP]||Date.now(),h=o?o.timestamp:null;let m=n.timestamp;!m&&h&&(m=h);const T=m?d-m:0,S=T>0?_*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:s,KBytesSent:r,deltaKBytesSent:_,kbsSent:S}},xd=(c,t,n,o)=>{let a=n[t].total_packets_lost_out,s=0,r=0;return Object.prototype.hasOwnProperty.call(c,G.PACKETS_LOST)&&(a=Number(c[G.PACKETS_LOST])||0-(o?o[t].total_packets_lost_out:0),s=a-n[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(c,G.FRACTION_LOST)&&(r=Number(100*c[G.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:s,fractionLost:r}},Ud=(c,t,n,o)=>{if(!Object.prototype.hasOwnProperty.call(c,G.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(c,G.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(c,G.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[G.PACKETS_RECEIVED])||0-(o?o[t].total_packets_in:0),s=Number(c[G.PACKETS_LOST])||0-(o?o[t].total_packets_lost_in:0),r=s-n[t].total_packets_lost_in,_=a-n[t].total_packets_in,d=a!==n[t].total_packets_in?r*100/(r+_):0,h=Number(c[G.BYTES_RECEIVED])/1024-(o?o[t].total_KBytes_in:0),m=h-n[t].total_KBytes_in,T=c[G.TIMESTAMP]||Date.now(),S=o?o.timestamp:null;let E=n.timestamp;!E&&S&&(E=S);const A=E?T-E:0,R=A>0?m*.008*1024/A*1e3:0;return{percentPacketsLost:d,packetsReceived:a,deltaPacketsReceived:_,packetsLost:s,deltaPacketsLost:r,KBytesReceived:h,deltaKBytesReceived:m,kbsReceived:R}},Cv=c=>c[G.CANDIDATE_TYPE]!=="relay"?"":c[G.RELAY_PROTOCOL]||"",Av=c=>{if(!Object.prototype.hasOwnProperty.call(c,G.NETWORK_TYPE))return ii.WIFI;switch(c[G.NETWORK_TYPE]){case wu.ETHERNET:return ii.ETHERNET;case wu.CELLULAR_4G:return ii.CELLULAR_4G;case wu.WIFI:return ii.WIFI;default:return ii.CELLULAR}},kd=c=>!Object.prototype.hasOwnProperty.call(c,G.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(c,G.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:c[G.FRAME_WIDTH]||null,height:c[G.FRAME_HEIGHT]||null,framerate:c[G.FRAMES_PER_SECOND]},Rv=c=>{const t=Object.prototype.hasOwnProperty.call(c,G.QUALITY_LIMITATION_REASON)?c[G.QUALITY_LIMITATION_REASON]:null,n=Object.prototype.hasOwnProperty.call(c,G.QUALITY_LIMITATION_RESOLUTION_CHANGES)?c[G.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,o=Object.prototype.hasOwnProperty.call(c,G.QUALITY_LIMITATION_DURATIONS)?c[G.QUALITY_LIMITATION_DURATIONS]:null;return o&&Object.keys(o).forEach(a=>{o[a]>1e3&&(o[a]=Number(o[a]/1e3))}),{reason:t,durations:o,resolutionChanges:n}},bv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,G.PLI)||!Object.prototype.hasOwnProperty.call(c,G.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const o=(c[G.PLI]||0)-(n?n[M.VIDEO].total_pli_sent_in:0),a=(c[G.NACK]||0)-(n?n[M.VIDEO].total_nack_sent_in:0);return{pliCount:o,nackCount:a,deltaPliCount:o-t[M.VIDEO].total_pli_sent_in,deltaNackCount:a-t[M.VIDEO].total_nack_sent_in}},Iv=(c,t,n)=>{if(!Object.prototype.hasOwnProperty.call(c,G.PLI)||!Object.prototype.hasOwnProperty.call(c,G.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const o=(c[G.PLI]||0)-(n?n[M.VIDEO].total_pli_received_out:0),a=(c[G.NACK]||0)-(n?n[M.VIDEO].total_nack_received_out:0);return{pliCount:o,nackCount:a,deltaPliCount:o-t[M.VIDEO].total_pli_received_out,deltaNackCount:a-t[M.VIDEO].total_nack_received_out}},wv=c=>({channels:c[G.CHANNELS]||null,clock_rate:c[G.CLOCK_RATE]||null,mime_type:c[G.MIME_TYPE]||null,sdp_fmtp_line:c[G.SDP_FMTP_LINE]||null}),Ov=c=>({clock_rate:c[G.CLOCK_RATE]||null,mime_type:c[G.MIME_TYPE]||null}),Dv=(c,t,n)=>{const o=(c[G.BYTES_RECEIVED]||0)/1024-(n?n.data.total_KBytes_in:0),a=(c[G.BYTES_SENT]||0)/1024-(n?n.data.total_KBytes_out:0),s=c[G.TIMESTAMP]||Date.now(),r=o-t.data.total_KBytes_in,_=a-t.data.total_KBytes_out,d=n?n.timestamp:null;let h=t.timestamp;!h&&d&&(h=d);const m=h?s-h:0,T=m>0?r*.008*1024/m*1e3:0,S=m>0?_*.008*1024/m*1e3:0;return{total_KBytes_received:o,total_KBytes_sent:a,delta_KBytes_received:r,delta_KBytes_sent:_,kbs_speed_received:T,kbs_speed_sent:S}},Nv=c=>{const t=c[G.AVAILABLE_INCOMING_BITRATE]/1024||0,n=c[G.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:n}},xv=(c,t,n,o)=>{if(!c)return[];switch(c[G.TYPE]){case Qt.CANDIDATE_PAIR:let a=!1;if(c[G.NOMINATED]&&c[G.STATE]===M.SUCCEEDED&&(a=!0,Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c),G.SELECTED in c&&!c[G.SELECTED]&&(a=!1)),a){const r=c[G.LOCAL_CANDIDATE_ID],_=c[G.REMOTE_CANDIDATE_ID],d=Dv(c,t,o),h=Nv(c),m=Sv(c,"data",o,t);return[{type:ne.NETWORK,value:{local_candidate_id:r}},{type:ne.NETWORK,value:{remote_candidate_id:_}},{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:h.kbs_incoming_bandwidth}},{type:ne.DATA,value:{delta_kbs_bandwidth_out:h.kbs_outgoing_bandwidth}},{type:ne.DATA,value:{delta_rtt_connectivity_ms:m.rtt}},{type:ne.DATA,value:{total_rtt_connectivity_ms:m.totalRTT}},{type:ne.DATA,value:{total_rtt_connectivity_measure:m.totalRTTMeasurements}}]}break;case Qt.LOCAL_CANDIDATE:if(c[G.ID]===t.network.local_candidate_id)return[{type:ne.NETWORK,value:{infrastructure:Av(c)}},{type:ne.NETWORK,value:{local_candidate_type:c[G.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{local_candidate_protocol:c[G.PROTOCOL]||""}},{type:ne.NETWORK,value:{local_candidate_relay_protocol:Cv(c)}}];break;case Qt.REMOTE_CANDIDATE:if(c[G.ID]===t.network.remote_candidate_id)return[{type:ne.NETWORK,value:{remote_candidate_type:c[G.CANDIDATE_TYPE]||""}},{type:ne.NETWORK,value:{remote_candidate_protocol:c[G.PROTOCOL]||""}}];break;case Qt.INBOUND_RTP:{Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const r=c[G.SSRC],_=dt(r,t,$e.INBOUND);_&&(_.timestamp=t.timestamp);const d=dt(r,o,$e.INBOUND);if(d&&(d.timestamp=o.timestamp),c[G.MEDIA_TYPE]===M.AUDIO){const h=Ud(c,M.AUDIO,_,d),m=bo(c,M.AUDIO,_),T=c[G.CODEC_ID]||"";return[{ssrc:r,type:ne.AUDIO,value:{codec_id_in:T}},{ssrc:r,type:ne.AUDIO,value:{total_packets_in:h.packetsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_in:h.deltaPacketsReceived}},{ssrc:r,type:ne.AUDIO,value:{total_packets_lost_in:h.packetsLost}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_lost_in:h.deltaPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{percent_packets_lost_in:h.percentPacketsLost}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_in:h.KBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_in:h.deltaKBytesReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_in:h.kbsReceived}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_in:m}}]}if(c[G.MEDIA_TYPE]===M.VIDEO){const h=Ev(c,_),m=Ud(c,M.VIDEO,_,d),T=bo(c,M.VIDEO,_),S=c[G.DECODER_IMPLEMENTATION]||null,E=c[G.CODEC_ID]||null,A=kd(c),R=bv(c,_,d);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_in:E}},{ssrc:r,type:ne.VIDEO,value:{total_packets_in:m.packetsReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_in:m.deltaPacketsReceived}},{ssrc:r,type:ne.VIDEO,value:{total_packets_lost_in:m.packetsLost}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_lost_in:m.deltaPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{percent_packets_lost_in:m.percentPacketsLost}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_in:m.KBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_in:m.deltaKBytesReceived}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_in:m.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:h.delta_ms_decode_frame}},{ssrc:r,type:ne.VIDEO,value:{total_frames_decoded_in:h.frames_decoded}},{ssrc:r,type:ne.VIDEO,value:{total_time_decoded_in:h.total_decode_time}},{ssrc:r,type:ne.VIDEO,value:{total_nack_sent_in:R.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_sent_in:R.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_sent_in:R.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_sent_in:R.deltaPliCount}},{ssrc:r,type:ne.VIDEO,value:{size_in:A}}]}break}case Qt.OUTBOUND_RTP:{Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const r=c[G.SSRC],_=dt(r,t,$e.OUTBOUND);_&&(_.timestamp=t.timestamp);const d=dt(r,o,$e.OUTBOUND);if(d&&(d.timestamp=o.timestamp),c[G.MEDIA_TYPE]===M.AUDIO){const h=c[G.CODEC_ID]||null,m=Nd(c,M.AUDIO,_,d);return[{ssrc:r,type:ne.AUDIO,value:{codec_id_out:h}},{ssrc:r,type:ne.AUDIO,value:{total_packets_out:m.packetsSent}},{ssrc:r,type:ne.AUDIO,value:{delta_packets_out:m.deltaPacketsSent}},{ssrc:r,type:ne.AUDIO,value:{total_KBytes_out:m.KBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_KBytes_out:m.deltaKBytesSent}},{ssrc:r,type:ne.AUDIO,value:{delta_kbs_out:m.kbsSent}}]}if(c[G.MEDIA_TYPE]===M.VIDEO){const h=c[G.ENCODER_IMPLEMENTATION]||null,m=c[G.CODEC_ID]||null,T=yv(c,_),S=kd(c),E=Rv(c),A=Iv(c,_,d),R=Nd(c,M.VIDEO,_,d);return[{ssrc:r,type:ne.VIDEO,value:{codec_id_out:m}},{ssrc:r,type:ne.VIDEO,value:{total_packets_out:R.packetsSent}},{ssrc:r,type:ne.VIDEO,value:{delta_packets_out:R.deltaPacketsSent}},{ssrc:r,type:ne.VIDEO,value:{total_KBytes_out:R.KBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_KBytes_out:R.deltaKBytesSent}},{ssrc:r,type:ne.VIDEO,value:{delta_kbs_out:R.kbsSent}},{ssrc:r,type:ne.VIDEO,value:{encoder_out:h}},{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:A.nackCount}},{ssrc:r,type:ne.VIDEO,value:{delta_nack_received_out:A.deltaNackCount}},{ssrc:r,type:ne.VIDEO,value:{total_pli_received_out:A.pliCount}},{ssrc:r,type:ne.VIDEO,value:{delta_pli_received_out:A.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(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);break}case Qt.TRACK:{Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);break}case Qt.CODEC:const s=[];return Object.keys(t[M.AUDIO]).forEach(r=>{const _=t[M.AUDIO][r];if(_.codec_id_in===c[G.ID]||_.codec_id_out===c[G.ID]){Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const d=wv(c);c[G.ID]===_.codec_id_in?s.push({ssrc:_.ssrc,type:ne.AUDIO,value:{codec_in:d}}):s.push({ssrc:_.ssrc,type:ne.AUDIO,value:{codec_out:d}})}}),Object.keys(t[M.VIDEO]).forEach(r=>{const _=t[M.VIDEO][r];if(_.codec_id_in===c[G.ID]||_.codec_id_out===c[G.ID]){Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const d=Ov(c);c[G.ID]===_.codec_id_in?s.push({ssrc:_.ssrc,type:ne.VIDEO,value:{codec_in:d}}):s.push({ssrc:_.ssrc,type:ne.VIDEO,value:{codec_out:d}})}}),s;case Qt.REMOTE_INBOUND_RTP:{Ue(Ls,`analyze() - got stats ${c[G.TYPE]} for ${n}`,c);const r=c[G.SSRC],_=dt(r,t,$e.OUTBOUND),d=dt(r,o,$e.OUTBOUND);if(c[G.KIND]===M.AUDIO){const h=Dd(c,M.AUDIO,d,_),m=bo(c,M.AUDIO,_),T=xd(c,M.AUDIO,_,d);return[{ssrc:r,type:ne.AUDIO,value:{delta_rtt_ms_out:h.rtt}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_ms_out:h.totalRTT}},{ssrc:r,type:ne.AUDIO,value:{total_rtt_measure_out:h.totalRTTMeasurements}},{ssrc:r,type:ne.AUDIO,value:{delta_jitter_ms_out:m}},{ssrc:r,type:ne.AUDIO,value:{timestamp_out:c[G.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[G.KIND]===M.VIDEO){const h=Dd(c,M.VIDEO,d,_),m=bo(c,M.VIDEO,_),T=xd(c,M.VIDEO,_,d);return[{ssrc:r,type:ne.VIDEO,value:{delta_rtt_ms_out:h.rtt}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_ms_out:h.totalRTT}},{ssrc:r,type:ne.VIDEO,value:{total_rtt_measure_out:h.totalRTTMeasurements}},{ssrc:r,type:ne.VIDEO,value:{delta_jitter_ms_out:m}},{ssrc:r,type:ne.VIDEO,value:{timestamp_out:c[G.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[]},Io=c=>c<0?1:c>100?4.5:1+.035*c+7/1e6*c*(c-60)*(100-c),Uv=(c,t=M.AUDIO,n,o,a)=>{const s=dt(a,c,$e.INBOUND),r=dt(a,n,$e.INBOUND),_=dt(a,o,$e.INBOUND),d=[],h=[],m=s[t].percent_packets_lost_in,T=s[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=_&&_[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=n&&n.data.delta_rtt_connectivity_ms||null,C=o&&o.data.delta_rtt_connectivity_ms||null;A&&d.push(A),R&&d.push(R),C&&d.push(C),T&&h.push(T),n&&S&&h.push(S),o&&E&&h.push(E);const H=d.length>0?Ms(d):100,k=h.length>0?Ms(h):10,re=93.2-m,x=.18*re*re-27.9*re+1126.62,F=(H+k)/2,_e=F-177.3<0?0:1,pe=.024*F+.11*(F-177.3)*_e,P=x-pe;return Io(P)},kv=(c,t=M.AUDIO,n,o,a)=>{const s=dt(a,c,$e.OUTBOUND),r=dt(a,n,$e.OUTBOUND),_=dt(a,o,$e.OUTBOUND),d=[],h=[],m=s[t].percent_packets_lost_out,T=s[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=_&&_[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,R=r&&r[t].delta_jitter_ms_out||null,C=_&&_[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,k=n&&n.data.delta_rtt_connectivity_ms||null,re=o&&o.data.delta_rtt_connectivity_ms||null;T?d.push(T):H&&d.push(H),S?d.push(S):k&&d.push(k),E?d.push(E):re&&d.push(re),A&&h.push(A),n&&R&&h.push(R),o&&C&&h.push(C);const x=d.length>0?Ms(d):100,F=h.length>0?Ms(h):10,_e=93.2-m,pe=.18*_e*_e-27.9*_e+1126.62,P=(x+F)/2,N=P-177.3<0?0:1,q=.024*P+.11*(P-177.3)*N,j=pe-q;return Io(j)},Pv=(c,t=M.AUDIO,n,o,a)=>{const s=dt(a,c,$e.INBOUND),r=dt(a,n,$e.INBOUND),_=dt(a,o,$e.INBOUND),d=[],h=[],m=s[t].percent_packets_lost_in/100,T=s[t].delta_jitter_ms_in,S=r&&r[t].delta_jitter_ms_in||null,E=_&&_[t].delta_jitter_ms_in||null,A=c.data.delta_rtt_connectivity_ms,R=n&&n.data.delta_rtt_connectivity_ms||null,C=o&&o.data.delta_rtt_connectivity_ms||null;A&&d.push(A),R&&d.push(R),C&&d.push(C),T&&h.push(T),r&&S&&h.push(S),_&&E&&h.push(E);const H=d.length>0?Ms(d):100,k=h.length>0?Ms(h):10,re=0,x=19.8,F=29.7,_e=30,pe=(H+k)/2+_e,P=pe-177.3<0?0:1,N=.024*pe+.11*(pe-177.3)*P,j=93.2-(re+x*Math.log(1+F*m)+N);return Io(j)},Mv=(c,t=M.AUDIO,n,o,a)=>{const s=dt(a,c,$e.OUTBOUND),r=dt(a,n,$e.OUTBOUND),_=dt(a,o,$e.OUTBOUND),d=[],h=[],m=s[t].percent_packets_lost_out/100,T=s[t].delta_rtt_ms_out,S=r&&r[t].delta_rtt_ms_out||null,E=_&&_[t].delta_rtt_ms_out||null,A=s[t].delta_jitter_ms_out,R=r&&r[t].delta_jitter_ms_out||null,C=_&&_[t].delta_jitter_ms_out||null,H=c.data.delta_rtt_connectivity_ms,k=n&&n.data.delta_rtt_connectivity_ms||null,re=o&&o.data.delta_rtt_connectivity_ms||null;T?d.push(T):H&&d.push(H),S?d.push(S):k&&d.push(k),E?d.push(E):re&&d.push(re),A&&h.push(A),r&&R&&h.push(R),_&&C&&h.push(C);const x=d.length>0?Ms(d):100,F=h.length>0?Ms(h):10,_e=0,pe=19.8,P=29.7,N=30,q=(x+F)/2+N,j=q-177.3<0?0:1,K=.024*q+.11*(q-177.3)*j,z=93.2-(_e+pe*Math.log(1+P*m)+K);return Io(z)};class Lv{constructor(t,n){this._callbacks={onreport:null,onticket:null},this._id=hv(),this._moduleName=this._id,this._probeId=n,this._config=t,this._exporter=new vv(t),this._state=ys.IDLE,this.registerToPCEvents(),on(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,n,o,a){const s=(d,h)=>d===M.AUDIO?h===Qt.INBOUND_RTP?{...Ad}:{...Rd}:h===Qt.INBOUND_RTP?{...bd}:{...Id},r=av(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 _=null;return t.forEach(d=>{!_&&d.timestamp&&(_=d.timestamp),xv(d,r,r.pname,a).forEach(m=>{if(m.value&&m.type)if(m.ssrc){let T=r[m.type][m.ssrc];T||(T=s(m.type,d.type),T.ssrc=m.ssrc,r[m.type][m.ssrc]=T),Object.keys(m.value).forEach(S=>{T[S]=m.value[S]})}else Object.keys(m.value).forEach(T=>{r[m.type][T]=m.value[T]})})}),r.timestamp=_,Object.keys(r[M.AUDIO]).forEach(d=>{const h=r[M.AUDIO][d];h.direction===$e.INBOUND?(h.mos_emodel_in=Uv(r,M.AUDIO,n,o,h.ssrc),h.mos_in=Pv(r,M.AUDIO,n,o,h.ssrc)):(h.mos_emodel_out=kv(r,M.AUDIO,n,o,h.ssrc),h.mos_out=Mv(r,M.AUDIO,n,o,h.ssrc))}),r}async takeReferenceStats(){return new Promise((t,n)=>{const o=Date.now();setTimeout(async()=>{try{const a=Date.now()-o,s=Date.now(),r=await this._config.pc.getStats(),_=this.analyze(r,null,null,null),d=Date.now();_.experimental.time_to_measure_ms=d-s,_.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(_),Ue(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(a){n(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==ys.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(),o=this.analyze(n,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return o.experimental.time_to_measure_ms=a-t,this._exporter.addReport(o),Ue(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(o),o}catch(t){return jn(this._moduleName,`got error ${t}`),null}}async start(){Ue(this._moduleName,"starting"),this.state=ys.RUNNING,this._startedTime=this._exporter.start(),Ue(this._moduleName,"started")}async mute(){this.state=ys.MUTED,Ue(this._moduleName,"muted")}async unmute(){this.state=ys.RUNNING,Ue(this._moduleName,"unmuted")}async stop(t){if(Ue(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=ys.IDLE,this._config.ticket){const{ticket:n}=this._exporter;this.fireOnTicket(n)}this._exporter.reset(),Ue(this._moduleName,"stopped")}registerCallback(t,n,o){t in this._callbacks?(this._callbacks[t]={callback:n,context:o},Ue(this._moduleName,`registered callback '${t}'`)):jn(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}'`)):jn(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,o,a){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:n,name:o,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{jn(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const o=t.iceConnectionState;o===ri.CONNECTED||o===ri.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===ri.DISCONNECTED||o===ri.FAILED?this.addCustomEvent(new Date().toJSON(),"call",o,"ICE connection state"):o===ri.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const o=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",o,"ICE gathering state")},t.ontrack=o=>{this.addCustomEvent(new Date().toJSON(),"call",`${o.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 o=n[0],{transport:a}=o;if(a){const{iceTransport:s}=a;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class $v{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||dv(),this._moduleName=this._id,on(this._moduleName,"probe created"),this._config=t,this._collector=new Lv(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,o,a=new Date().toJSON()){this._collector.addCustomEvent(a,n,t,o)}get isRunning(){return this._collector.state===ys.RUNNING}get isIdle(){return this._collector.state===ys.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){Ro(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 Hv{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},on(It,`configured for probing every ${this._config.refreshEvery}ms`),on(It,`configured for starting after ${this._config.startAfter}ms`),on(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,n){if(!t)throw new Error("undefined peer connection");const o=cv(t,n,this._config),a=new $v(o);return this._probes.push(a),Ue(It,`${this._probes.length} probes registered`),a}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===ys.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())),o=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const s=ov(),r=this._probes.filter(_=>_.isRunning);for(const _ of r){const d=await _.collectStats();d&&s.probes.push(d),Ue(It,`got probe ${_.id}`),await wd(0)}return s.delta_time_to_measure_probes_ms=an(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=an(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=an(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=an(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=an(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=an(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=an(s.probes,"video","total_time_encoded_out"),s};for(Ue(It,"starting to collect"),t(),Ue(It,"generating reference reports..."),await n(),Ue(It,"reference reports generated"),this._startedTime=Date.now();o();)if(Ue(It,`wait ${this._config.refreshEvery}ms before collecting`),await wd(this._config.refreshEvery),o()){Ue(It,"collecting...");const s=Date.now(),r=await a(),_=Date.now();r.delta_time_consumed_to_measure_ms=_-s,this.fireOnReports(r),Ue(It,"collected")}Ue(It,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const n=o=>{this._probes.forEach(a=>{a.stop(o)})};on(It,"stop collecting"),n(t)}registerCallback(t,n,o){t in this._callbacks?(this._callbacks[t]={callback:n,context:o},Ue(It,`registered callback '${t}'`)):jn(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}'`)):jn(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 Fv="interface ";class Vv{constructor(t){this._config=fv(t),on(Fv,`welcome to ${this._config.name} version ${this._config.version}`),ZT(this._config.verbose||!1),this._engine=new Hv(this._config)}setupLogLevel(t){ev(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 jv(c,t){return Object.keys(c).filter(n=>t.includes(n)).reduce((n,o)=>{const a=o;return{...n,[a]:c[a]}},{})}const qv=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],Bv={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class Gv{constructor(t){this.intervals={},this.analysers={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}async start(t,n,o){n&&n.getTracks().length&&await this.beginCalculation(t,n,o)}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,o){this.clearVolumeInterval(o);const a=t.createAnalyser(),s=t.createMediaStreamSource(n);a.smoothingTimeConstant=.8,a.fftSize=1024,s.connect(a),this.analysers[o]=a,this.intervals[o]=setInterval(()=>{const r=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(r);let _=0;const d=r.length;for(let m=0;m<d;m++)_+=r[m];const h=_/d;this.onChangeFunction(o,h)},this.emitInterval)}}class Wv{constructor(){this.resumePromise=null,this.context=new AudioContext,this.setupErrorHandling()}setupErrorHandling(){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 wo={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Kv=0;class Yv{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.vadSessions={},this.vadSessionsState={},this.vadIntervals={},this.vadMrsIntervals={},this.ringbackTimers={},this.ringbackAudioContexts={},this.ringbackSessionProgressReceived={},this.hangupBeepContext=null,this.managedAudioContext=new Wv,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new Gv({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 o of n)this.noiseReduction[o]=t[o];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,o;const t=(o=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:o.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||{}}}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(o=>!o.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 Sd()?{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(wo.SELECTED_INPUT_DEVICE)||"default",n=localStorage.getItem(wo.SELECTED_OUTPUT_DEVICE)||"default";try{const o=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)}),o.getTracks().forEach(s=>s.stop())}catch(o){console.error(o)}}async cleanupConferenceNodes(t){const n=this.conferenceNodes[t];if(!n)return;let o=0;n.sources.forEach((r,_)=>{var d;try{r.disconnect(),o++}catch(h){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,_)=>{var d;try{r.disconnect(),a++}catch(h){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,_)=>{var d;try{r.disconnect(),s++}catch(h){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(o=>o.enabled=!t),this.roomReconfigure(n)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:n,automatic:o}){const a=this.extendedCalls[t];if(!a)return;a._automaticHold=o??!1;const s=new Promise((r,_)=>{const d=setTimeout(()=>{_(new Error("Hold operation timeout"))},5e3),h=()=>{clearTimeout(d),a.putOnHoldTimestamp=n?Date.now():void 0,r()},m=T=>{clearTimeout(d),_(T)};try{n?(this.stopSessionVad(a._id),a.hold({},h)):a.unhold({},h)}catch(T){m(T)}});try{await s,this.updateCall(a);const r=Object.values(this.extendedCalls).filter(_=>_.roomId===a.roomId&&(n?t!==_._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===Kv).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",o=>{this.triggerAddStream(o,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]=Td(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const o={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...o}},this.context.emit("updateRoom",{room:o,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const n=/answer-after=0/,a=t.request.getHeader("Call-Info");return a&&n.test(a)}addCall(t,n=!0){this.activeCalls={...this.activeCalls,[t._id]:Td(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 o={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(o.isMoving=t.isMoving),t.isTransferring!==void 0&&(o.isTransferring=t.isTransferring),t.isMerging!==void 0&&(o.isMerging=t.isMerging),t.isTransferred!==void 0&&(o.isTransferred=t.isTransferred),this.callStatus={...this.callStatus,[t.callId]:{...o}},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 Au(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 Au(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:o})=>o===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const n=Object.values(this.extendedCalls).filter(o=>o.roomId===this.currentActiveRoomId);n.length===1?Object.values(n).forEach(async o=>{await this.setupActiveStream();const a=this.activeStream;o.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(o)}):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 o=n.filter(a=>a.roomId===this.currentActiveRoomId);o.length===1?n.forEach(a=>{var s;(s=a.audioTag)==null||s.setSinkId(t),this.updateCall(a)}):await this.doConference(o)}removeRoom(t){const n={...this.activeRooms},o={...n[t]};delete n[t],this.activeRooms={...n},this.context.emit("removeRoom",{room:o,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({sessionId:t,stream:n,onNoiseDetected:o,onNoiseStop:a}){var m,T,S;let s;try{s=await this.managedAudioContext.getContext()}catch(E){console.error("[startNoiseMonitor] Failed to get AudioContext:",E),(m=this.context.logger)==null||m.error("[startNoiseMonitor] Failed to get AudioContext:",E);return}let r,_;try{r=s.createMediaStreamSource(n.clone()),_=s.createAnalyser()}catch(E){console.error("[startNoiseMonitor] Failed to create audio nodes:",E),console.error("[startNoiseMonitor] AudioContext state:",s.state),(T=this.context.logger)==null||T.error("[startNoiseMonitor] Failed to create audio nodes:",E),(S=this.context.logger)==null||S.error("[startNoiseMonitor] AudioContext state:",s.state);return}_.fftSize=1024;const d=new Float32Array(_.fftSize);r.connect(_);const h=[];this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),this.vadIntervals[t]=null),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),this.vadMrsIntervals[t]=null),this.vadMrsIntervals[t]=setInterval(()=>{_.getFloatTimeDomainData(d);const E=JT(d);h.push(E);const A=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);h.length>A&&h.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[t]=setInterval(()=>{var C;if(h.length===0)return;const E=h.reduce((H,k)=>H+k,0)/h.length,A=this.vadSessionsState[t];if(!A){console.warn(`[startNoiseMonitor] State not found for sessionId ${t}, stopping interval`),(C=this.context.logger)==null||C.warn(`[startNoiseMonitor] State not found for sessionId ${t}, stopping interval`),this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),delete this.vadIntervals[t]),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),delete this.vadMrsIntervals[t]);return}const R=E>this.noiseReduction.noiseThreshold;A.isSpeaking||(R&&A.currentMode==="clean"?(A.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!0}),o()):!R&&A.currentMode==="noisy"&&(A.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!1}),a()))},this.noiseReduction.noiseCheckInterval)}async processVAD(t,n){var d;const o=n.clone();this.stopSessionVad(t._id),this.vadSessionsState[t._id]={currentMode:"clean",isSpeaking:!1},console.log("[processVAD] Process for",t._id),(d=this.context.logger)==null||d.log("[processVAD] Process for",t._id);const a=await this.managedAudioContext.getContext(),s=await zT(o,a,150);let r=!1;const _=await this.MicVAD.new({getStream:()=>new Promise(h=>h(o)),...Bv,...this.noiseReduction.vadConfig,baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",onFrameProcessed:()=>{var h;if(!r){if(r=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){t.connection.getSenders()[0]&&t.connection.getSenders()[0].replaceTrack(s.stream.getAudioTracks()[0]);return}if(!this.vadSessionsState[t._id]){console.error(`[processVAD] CRITICAL: State not found for session ${t._id} after being set at line 988! This should not happen.`),(h=this.context.logger)==null||h.error(`[processVAD] CRITICAL: State not found for session ${t._id} after being set at line 988! This should not happen.`);return}this.startNoiseMonitor({sessionId:t._id,stream:o,onNoiseDetected:async()=>{var m,T;console.log("[processVad] - Replace track with Vad Controlled"),(m=this.context.logger)==null||m.log("[processVad] - Replace track with Vad Controlled"),await((T=t.connection.getSenders()[0])==null?void 0:T.replaceTrack(s.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const m=t.connection.getSenders()[0];m&&m.track&&m.transport&&m.transport.state!=="closed"&&m.transport.state!=="failed"&&(console.log("Replace track with Original"),await m.replaceTrack(o.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var h;console.log("🎤 Speech started"),s.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((h=t.connection.getSenders()[0])==null||h.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!0},onSpeechEnd:()=>{var h;console.log("🛑 Speech end"),s.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((h=t.connection.getSenders()[0])==null||h.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!1}});this.vadSessions[t._id]&&(this.vadSessions[t._id].pause(),delete this.vadSessions[t._id]),this.vadSessions[t._id]=_,_.start()}stopSessionVad(t){this.vadSessions[t]&&(this.vadSessions[t].pause(),delete this.vadSessions[t]),this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),delete this.vadIntervals[t]),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),delete this.vadMrsIntervals[t]),this.vadSessionsState[t]&&delete this.vadSessionsState[t]}async roomReconfigure(t){var a,s,r,_;if(t===void 0)return;const n=Object.values(this.extendedCalls).filter(d=>d.roomId===t),o=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,h)=>{if(d.audioTag){d.connection.getReceivers().forEach(T=>{T.track.enabled=!d.localMuted}),o&&this.muteReconfigure(d);const m=!o;d.audioTag.muted=m,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&&!o){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&&o){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"),(_=this.context.logger)==null||_.log("[roomReconfigure] - Call processVAD from roomReconfigure"),this.processVAD(n[0],E));const A=E.getTracks();await T.replaceTrack(A[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 h,m,T,S,E,A,R;if(console.log("[doConference] - In doConference, sessions:",t),(h=this.context.logger)==null||h.log("[doConference] - In doConference, sessions:",t),t.length===0)return;const n=t[0].roomId,o=this.currentActiveRoomId===n;if(t.find(C=>C.roomId!==n))return;let s;try{s=await this.managedAudioContext.getContext()}catch(C){console.error("[doConference] Failed to get AudioContext:",C),(m=this.context.logger)==null||m.error("[doConference] Failed to get AudioContext:",C);return}const r=s.state;if(r!=="running")if(console.error(`[doConference] ERROR: AudioContext is not running! State: ${r}`),(T=this.context.logger)==null||T.error(`[doConference] ERROR: AudioContext is not running! State: ${r}`),r==="suspended"||r==="interrupted")try{await s.resume();const C=s.state;if(C!=="running"){console.error(`[doConference] Failed to resume AudioContext, state: ${C}`),(S=this.context.logger)==null||S.error(`[doConference] Failed to resume AudioContext, state: ${C}`);return}}catch(C){console.error("[doConference] Error resuming AudioContext:",C),(E=this.context.logger)==null||E.error("[doConference] Error resuming AudioContext:",C);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 _=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((C,H)=>{var k,re,x;if(console.log("[doConference] - In sessions forEach, iteration for",C._id),(k=this.context.logger)==null||k.log("[doConference] - In sessions forEach, iteration for",C._id),C&&C.connection){const F=C.connection.getReceivers();console.log("[doConference] - Receivers list length for",C._id,F.length),(re=this.context.logger)==null||re.log("[doConference] - Receivers list length for",C._id,F.length),F.forEach((_e,pe)=>{var q,j,K,V,z,D;_e.track.enabled=!C.localMuted;const P=(q=_e.track)==null?void 0:q.id;(j=_e.track)==null||j.readyState,(K=_e.track)==null||K.kind;const N=`${C._id}-${P}`;console.log("[doConference] - Gathering receiver tracks",C._id),console.log("[doConference] - Receiver track readyState",_e.track.readyState),(V=this.context.logger)==null||V.log("[doConference] - Gathering receiver tracks",C._id),(z=this.context.logger)==null||z.log("[doConference] - Receiver track readyState",_e.track.readyState),_e.track&&_e.track.readyState==="live"&&(console.log("[doConference] - Gathered receiver track",C._id),(D=this.context.logger)==null||D.log("[doConference] - Gathered receiver track",C._id),d.set(N,_e.track))})}else console.log("[doConference] - No session or RTC connection, session:",C),(x=this.context.logger)==null||x.log("[doConference] - No session or RTC connection, session:",C)}),await this.setupActiveStream(),await XT.forEach(t,async(C,H)=>{var N,q,j,K,V,z;if(!C||!C.connection){console.log("[doConference] - Return because of no session or connection, session:",C),(N=this.context.logger)==null||N.log("[doConference] - Return because of no session or connection, session:",C);return}const k=s.createMediaStreamDestination();_.destinations.set(C._id,k);let re=0;const x=C.connection.getReceivers(),F=x.length>0;if(console.log(`[doConference] Session ${C._id} has ${x.length} receivers`),(q=this.context.logger)==null||q.log(`[doConference] Session ${C._id} has ${x.length} receivers`),F||(console.warn(`[doConference] Session ${C._id} has no receivers yet. Will re-configure when track arrives.`),(j=this.context.logger)==null||j.warn(`[doConference] Session ${C._id} has no receivers yet. Will re-configure when track arrives.`)),d.forEach((D,U)=>{var X,je,Q;if(console.log("[doConference] - In forEach receiverTracks for",C._id),(X=this.context.logger)==null||X.log("[doConference] - In forEach receiverTracks for",C._id),!U.startsWith(C._id)){if(!D||D.readyState!=="live"){console.warn(`[doConference] Skipping invalid track ${(D==null?void 0:D.id)||"unknown"} for session ${C._id}`),(je=this.context.logger)==null||je.warn(`[doConference] Skipping invalid track ${(D==null?void 0:D.id)||"unknown"} for session ${C._id}`);return}try{const W=s.createMediaStreamSource(new MediaStream([D])),B=s.createGain(),ie=`${C._id}-${U}`;W.connect(B),B.connect(k),console.log("[doConference] - In forEach connect track for",C._id),(Q=this.context.logger)==null||Q.log("[doConference] - In forEach connect track for",C._id),_.sources.set(ie,W),_.gains.set(ie,B),re++}catch(W){console.error(W)}}}),o&&this.activeStreamValue)try{const D=this.activeStream,U=s.createMediaStreamSource(D),X=s.createGain(),je=`${C._id}-local`;U.connect(X),X.connect(k),_.sources.set(je,U),_.gains.set(je,X)}catch(D){console.error(D)}else o&&(console.error(`Host room but no activeStreamValue - skipping host microphone for session ${C._id}`),(K=this.context.logger)==null||K.error(`Host room but no activeStreamValue - skipping host microphone for session ${C._id}`));const pe=C.connection.getSenders()[0],P=k.stream.getTracks();if(["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.processVAD(C,k.stream)),pe&&P[0])try{console.log("[doConference] - Final replaceTrack for",C._id),(z=this.context.logger)==null||z.log("[doConference] - Final replaceTrack for",C._id),await pe.replaceTrack(P[0]),this.muteReconfigure(C)}catch(D){console.error(D)}})}processCallerMute(t,n){const o=this.extendedCalls[t];o&&o.connection.getReceivers().length&&(o.localMuted=n,o.connection.getReceivers().forEach(a=>{a.track.enabled=!n}),this.updateCall(o))}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,_,d,h;let o=null;if(this.extendedCalls[t])o=t;else{const m=Object.values(this.extendedCalls).find(T=>T.id===t||T._id===t||T.id&&T.id.includes(t)||T._id&&T._id.includes(t));m&&(o=m.id)}if(!o){(s=this.context.logger)==null||s.warn(`[handleSipResponseForRingback] Could not find session for identifier ${t}, status ${n}`);return}const a=this.extendedCalls[o];if(!a){(r=this.context.logger)==null||r.warn(`[handleSipResponseForRingback] Call not found in extendedCalls for ${o}`);return}if(a.direction==="outgoing"){if(n===Ao.TRYING||n===Ao.RINGING){if(this.ringbackTimers[o])return;this.ringbackSessionProgressReceived[o]=!1,this.ringbackTimers[o]=setTimeout(()=>{var m;this.ringbackSessionProgressReceived[o]||(this.startLocalRingbackTone(o),(m=this.context.logger)==null||m.log(`[handleSipResponseForRingback] Started local ringback tone for call ${o} after 2 seconds without 183`)),delete this.ringbackTimers[o]},2e3),(_=this.context.logger)==null||_.log(`[handleSipResponseForRingback] Started 2-second timer for call ${o} after receiving ${n}`)}n===Ao.SESSION_PROGRESS&&(this.ringbackSessionProgressReceived[o]=!0,this.ringbackTimers[o]&&(clearTimeout(this.ringbackTimers[o]),delete this.ringbackTimers[o],(d=this.context.logger)==null||d.log(`[handleSipResponseForRingback] Cancelled ringback timer for call ${o} - 183 received`)),this.stopLocalRingbackTone(o),(h=this.context.logger)==null||h.log(`[handleSipResponseForRingback] Stopped local ringback tone for call ${o} - 183 received with SDP`))}}async startLocalRingbackTone(t){var n,o;if(!this.ringbackAudioContexts[t])try{const a=await this.managedAudioContext.getContext(),s=a.createOscillator(),r=a.createOscillator(),_=a.createGain();s.frequency.value=440,r.frequency.value=480,s.type="sine",r.type="sine",_.gain.value=0,s.connect(_),r.connect(_),_.connect(a.destination),s.start(),r.start();const d={context:a,oscillator1:s,oscillator2:r,gainNode:_,intervalId:null};this.ringbackAudioContexts[t]=d;const h=()=>{if(!this.ringbackAudioContexts[t])return;const T=a.currentTime;_.gain.cancelScheduledValues(T),_.gain.setValueAtTime(0,T),_.gain.linearRampToValueAtTime(.3,T+.05),_.gain.linearRampToValueAtTime(0,T+1)};h();const m=setInterval(()=>{if(!this.ringbackAudioContexts[t]){clearInterval(m);return}h()},4e3);d.intervalId=m,this.ringbackAudioContexts[t]=d,(n=this.context.logger)==null||n.log(`[startLocalRingbackTone] Started ringback tone for session ${t}`)}catch(a){(o=this.context.logger)==null||o.error(`[startLocalRingbackTone] Error starting ringback tone for session ${t}:`,a),console.error(`[startLocalRingbackTone] Error starting ringback tone for session ${t}:`,a)}}stopLocalRingbackTone(t){var o,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],(o=this.context.logger)==null||o.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 o=await this.managedAudioContext.getContext(),a=o.createOscillator(),s=o.createGain();a.frequency.value=800,a.type="sine",s.gain.value=0,a.connect(s),s.connect(o.destination),this.hangupBeepContext={context:o,oscillator:a,gainNode:s},a.start();const r=o.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(_){console.error("[playHangupBeep] Cleanup playing hangup beep error:",_)}this.hangupBeepContext=null}},250),(t=this.context.logger)==null||t.log("[playHangupBeep] Played hangup beep")}catch(o){(n=this.context.logger)==null||n.error("[playHangupBeep] Error playing hangup beep:",o),console.error("[playHangupBeep] Error playing hangup beep:",o),this.hangupBeepContext=null}}transferCall(t,n){if(n.toString().length===0)return new Error("Target must be passed");const o=this.extendedCalls[t];if(!o._is_confirmed&&!o._is_canceled){const a=`sip:${n}@${this.context.sipDomain}`;o.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:t,isTransferring:!0,isTransferred:!1}),o.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(o)}mergeCall(t){const n=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(n.length!==2)return;const o=n[0],a=n[1];!o||!a||(this.updateCallStatus({callId:o._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o))}mergeCallByIds(t,n){const o=Object.values(this.extendedCalls).find(s=>s._id===t),a=Object.values(this.extendedCalls).find(s=>s._id===n);if(!o||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:n,isMerging:!0}),o.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(o)}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 o=setInterval(()=>{const a={...this.callTime[t]},s=YT(a);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,o)}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 h,m;const n=t.session;if(this.getActiveCalls[n.id]!==void 0)return;const a=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:a};if(n.direction==="incoming")this.context.logger.log("New incoming call from",(m=(h=n._remote_identity)==null?void 0:h._uri)==null?void 0:m._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))});else if(n.direction==="outgoing"){const T=S=>{var C,H,k,re,x,F,_e,pe,P;const E=!!((C=S==null?void 0:S.response)!=null&&C.body),A=(k=(H=S==null?void 0:S.response)==null?void 0:H.getHeader)==null?void 0:k.call(H,"Content-Type"),R=(x=(re=S==null?void 0:S.response)==null?void 0:re.getHeader)==null?void 0:x.call(re,"Content-Length");console.log("PPP SDP Check:",{hasBody:E,contentType:A,contentLength:R,bodyLength:((_e=(F=S==null?void 0:S.response)==null?void 0:F.body)==null?void 0:_e.length)||0,bodyPreview:((P=(pe=S==null?void 0:S.response)==null?void 0:pe.body)==null?void 0:P.substring(0,100))||"N/A"}),S.response&&S.response.status_code===Ao.SESSION_PROGRESS&&(this.startCallTimer(n.id),n.off("progress",T))};n.on("progress",T),n.once("confirmed",()=>{this.startCallTimer(n.id)})}const r=n,_=this.hasAutoAnswerHeaders(t),d=r.direction==="incoming"&&!this.hasActiveCalls&&(_||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&&this.answerCall(r._id)}removeCall(t){const n={...this.activeCalls};delete n[t],this.activeCalls={...n};const o={...this.extendedCalls};delete o[t],this.extendedCalls={...o},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 o=n.roomId;this.removeCall(t._id),this.roomReconfigure(o).then(()=>{}).catch(a=>{console.error("Error reconfiguring room after call removal:",a)})}shouldTerminateNewSession(t){if(t.session.direction==="outgoing")return!1;const o=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||o}async newRTCSessionCallback(t){const n=t.session;if(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",a=>{var r,_,d;if(this.stopVUMeter(n.id),this.context.logger.log("Session ended for",(_=(r=n._remote_identity)==null?void 0:r._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_ENDED,session:n,event:a}),n._is_confirmed&&this.playHangupBeep(),n.connection){const h=n.connection.connectionState;(h==="closed"||h==="disconnected")&&this.context.emit("connectionStateChange",{session:n,connectionState:h})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(n._id),this.cleanupRingbackTone(n.id);const s=this.getActiveCalls[n.id];s&&this.activeCallListRemove(s),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("progress",a=>{var s,r;this.context.logger.log("Session in progress for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_PROGRESS,session:n,event:a})}),n.on("failed",a=>{var r,_,d;if(this.stopVUMeter(n.id),this.context.logger.log("Session failed for",(_=(r=n._remote_identity)==null?void 0:r._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Xt.CALL_FAILED,session:n,event:a}),n.connection){const h=n.connection.connectionState;(h==="closed"||h==="disconnected")&&this.context.emit("connectionStateChange",{session:n,connectionState:h})}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(n._id),this.cleanupRingbackTone(n.id),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const s=this.getActiveCalls[n.id];s&&this.activeCallListRemove(s),this.stopCallTimer(n.id),this.removeCallStatus(n.id),this.removeCallMetrics(n.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(h=>h.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),n.on("confirmed",a=>{var s,r;this.context.logger.log("Session confirmed for",(r=(s=n._remote_identity)==null?void 0:s._uri)==null?void 0:r._user),this.context.triggerListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:a}),this.updateCall(n),this.cleanupRingbackTone(n.id),n.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)});const o=a=>{a&&a.addEventListener("connectionstatechange",s=>{this.context.emit("connectionStateChange",{session:n,connectionState:a.connectionState})})};if(n.connection&&o(n.connection),n.on("peerconnection",({peerconnection:a})=>{o(a)}),await this.setupCall(t),n.direction==="outgoing"){const a=this.getActiveCalls[n.id].roomId;await this.setActiveRoom(a)}}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(wo.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(wo.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 Vv(this.metricConfig),o=n.createProbe(t.connection,{cid:t._id}),a=[];let s;o.onreport=r=>{Object.entries(r.audio).forEach(([h,m])=>{m.direction==="inbound"&&!a.includes(h)&&(a.push(h),s=h)});const _=r.audio[s];if(!_)return;const d=jv(_,qv);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 o=this.muteWhenJoin||this.isMuted;this.setIsMuted(o),this.initialStreamValue||await this.setupStream();const a=await this.managedAudioContext.getContext(),s=await Au(a,this.initialStreamValue,this.microphoneInputLevel*2),r=this.isMuted||this.muteWhenJoin;s.getTracks().forEach(A=>{A.enabled=!r}),await this.setActiveStream(s),await n.connection.getSenders()[0].replaceTrack(s.getTracks()[0]);const h=new MediaStream([t.track]);!Object.values(this.extendedCalls).find(A=>A.audioTag&&A.audioTag.id===n._id)&&UT(h,n,this.selectedOutputDevice,this.speakerVolume);const T=n.roomId===this.currentActiveRoomId;n.audioTag&&(n.audioTag.muted=!T),await this.setupVUMeter(h,n._id),this.getCallQuality(n),this.updateCall(n),n.roomId!==void 0&&Object.values(this.extendedCalls).filter(R=>R.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.processVAD(n,s)}initCall(t,n,o=!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}),o)){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 o=this.extendedCalls[t];if(!o)return;const a=o.roomId;o.roomId=n,this.updateCall(o),await this.roomReconfigure(a),await this.roomReconfigure(n)}}class Jv{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 zv{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]=vd(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:vd(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,n){const o=this.msrpHistory[n.id]||[];o.push(t),this.msrpHistory={...this.msrpHistory,[n.id]:[...o]},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 o=t;this.addMMSRPSession(o)}triggerMSRPListener({listenerType:t,session:n,event:o}){const a=this.context.listenersList[t];!a||!a.length||a.forEach(s=>{s(n,o)})}removeMMSRPSession(t){const n={...this.activeMessages};delete n[t],this.activeMessages={...n};const o={...this.extendedMessages};delete o[t],this.extendedMessages={...o},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",o=>{this.triggerMSRPListener({listenerType:Xt.CALL_ENDED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("failed",o=>{this.triggerMSRPListener({listenerType:Xt.CALL_FAILED,session:n,event:o});const a=this.getActiveMessages[n.id];this.activeMessageListRemove(a)}),n.on("confirmed",o=>{this.triggerMSRPListener({listenerType:Xt.CALL_CONFIRMED,session:n,event:o}),this.updateMSRPSession(n)}),n.on("newMessage",o=>{this.addMSRPMessage(o,n)}),this.addMessageSession(n)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,n,o){if(t.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(t,o);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(n),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,n){const o=this.extendedMessages[t];if(!o)throw new Error(`MSRP session with id ${t} doesn't exist!`);o.sendMSRP(n)}}const Oo={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Pd{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 Md extends Pd{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=ke.cloneArray(t.extraHeaders),o={from_tag:this.session._from_tag};t.fromUserName&&(o.from_uri=new ln("sip",t.fromUserName,this.session._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(o.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 Tt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,o,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 Wr(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 o={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},a=JSON.stringify(o);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 o={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($.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(o),eventHandlers:{onSuccessResponse:async s=>{var r,_,d,h;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const m=JSON.parse(s.body)||{};((_=(r=m.plugindata)==null?void 0:r.data)==null?void 0:_.videoroom)==="joined"&&this.session.myFeedList.push(m.plugindata.data.id),(h=(d=m.plugindata)==null?void 0:d.data)!=null&&h.publishers&&this.session.receivePublishers(m)}catch(m){console.error(m)}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(kt.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
+ `),h=d[d.length-1],m=JSON.parse(h);await this._connection.setRemoteDescription(m.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},n=[this.session.getPTypeHeader(kt.DETACH)];this.session.sendRequest($.INFO,{extraHeaders:n,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(n=>{const o=n.track;o&&o.stop()}),t.forEach(n=>{this._connection.removeTrack(n)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Ld extends Pd{constructor(t,n,o={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=o.immediate||!1,this.type=n}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const n=await this.start(t);return this.running=!0,n}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 Xv extends bT{constructor(t,n){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const o={...t.configuration,sockets:t.socketInterfaces.map(a=>new KT.WebSocketInterface(a))};super(o),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),n&&kT(n)&&(this.logger=n)}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(Oo.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(t,n){return super.on(t,n)}off(t,n){return super.off(t,n)}emit(t,n){return super.emit(t,n)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(n=>n.name===t.name)||this.processStreamPlugins.find(n=>n.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof Md)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof Ld)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(n=>n.name===t)||this.processStreamPlugins.find(n=>n.name===t)}reconnect(){if(this.reconnectionAttemptsCounter<this.reconnectionAttemptsLimit){const n=5e3*Math.pow(2,this.reconnectionAttemptsCounter);this.reconnectionAttemptsCounter++,setTimeout(this.start.bind(this),n)}else this.emit("reconnectionAttemptsLimitReached",void 0)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Oo.AUDIO)&&(this.audio=new Yv(this)),this.modules.includes(Oo.MSRP)&&(this.msrp=new zv(this)),this.modules.includes(Oo.VIDEO)&&(this.video=new Jv(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,n){const a=!this.listenersList[t]||!this.listenersList[t].length?[n]:[...this.listenersList[t],n];this.listenersList={...this.listenersList,[t]:a}}removeIListener(t){const n={...this.listenersList};delete n[t],this.listenersList={...n}}triggerListener({listenerType:t,session:n,event:o}){const a=this.listenersList[t];!a||!a.length||a.forEach(s=>{s(n,o)})}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)}}return Wt.BaseNewStreamPlugin=Md,Wt.BaseProcessStreamPlugin=Ld,Wt.default=Xv,Object.defineProperties(Wt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),Wt}({});