opensips-js-vue 0.1.19 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/library/index.d.ts +3 -0
- package/library/super.mjs +1436 -1420
- package/library/super.mjs.map +1 -1
- package/library/super.umd.js +52 -52
- package/library/super.umd.js.map +1 -1
- package/package.json +2 -2
package/library/super.umd.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
(function(xs,At){typeof exports=="object"&&typeof module<"u"?At(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],At):(xs=typeof globalThis<"u"?globalThis:xs||self,At(xs["vsip-next"]={},xs.Vue))})(this,function(xs,At){"use strict";function Tb(o,n){for(var r=0;r<n.length;r++){const a=n[r];if(typeof a!="string"&&!Array.isArray(a)){for(const c in a)if(c!=="default"&&!(c in o)){const e=Object.getOwnPropertyDescriptor(a,c);e&&Object.defineProperty(o,c,e.get?e:{enumerable:!0,get:()=>a[c]})}}}return Object.freeze(Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}))}var bb=Object.defineProperty,wb=(o,n,r)=>n in o?bb(o,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):o[n]=r,rs=(o,n,r)=>(wb(o,typeof n!="symbol"?n+"":n,r),r),Sb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Qt(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}const Eb="jssip",Cb="JsSIP",Ab="the Javascript SIP library",Ib="3.10.0",Rb="https://jssip.net",$b=["José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)","Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)"],xb="lib/JsSIP.d.ts",Ob="lib-es5/JsSIP.js",kb=["sip","websocket","webrtc","node","browser","library"],Db="MIT",Nb={type:"git",url:"https://github.com/versatica/JsSIP.git"},Mb={url:"https://github.com/versatica/JsSIP/issues"},Ub={"@types/events":"^3.0.0","@types/debug":"^4.1.7",debug:"^4.3.1",events:"^3.3.0","sdp-transform":"^2.14.1"},Pb={"@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"},Lb={lint:"node npm-scripts.js lint",test:"node npm-scripts.js test",prepublish:"node npm-scripts.js prepublish",release:"node npm-scripts.js release"},Pl={name:Eb,title:Cb,description:Ab,version:Ib,homepage:Rb,contributors:$b,types:xb,main:Ob,keywords:kb,license:Db,repository:Nb,bugs:Mb,dependencies:Ub,devDependencies:Pb,scripts:Lb};var Gh=Pl,dn={USER_AGENT:"".concat(Gh.title," ").concat(Gh.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 Ll(o){"@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(o)}function ql(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Hl(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Do(o,n)}function zl(o){var n=Wh();return function(){var r=No(o),a;if(n){var c=No(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return qb(this,a)}}function qb(o,n){return n&&(Ll(n)==="object"||typeof n=="function")?n:Hb(o)}function Hb(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function ja(o){var n=typeof Map=="function"?new Map:void 0;return ja=function(r){if(r===null||!zb(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(typeof n<"u"){if(n.has(r))return n.get(r);n.set(r,a)}function a(){return Fl(r,arguments,No(this).constructor)}return a.prototype=Object.create(r.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),Do(a,r)},ja(o)}function Fl(o,n,r){return Wh()?Fl=Reflect.construct:Fl=function(a,c,e){var f=[null];f.push.apply(f,c);var g=Function.bind.apply(a,f),d=new g;return e&&Do(d,e.prototype),d},Fl.apply(null,arguments)}function Wh(){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 zb(o){return Function.toString.call(o).indexOf("[native code]")!==-1}function Do(o,n){return Do=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Do(o,n)}function No(o){return No=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},No(o)}var Fb=function(o){Hl(r,o);var n=zl(r);function r(a,c){var e;return ql(this,r),e=n.call(this),e.code=1,e.name="CONFIGURATION_ERROR",e.parameter=a,e.value=c,e.message=e.value?"Invalid value ".concat(JSON.stringify(e.value),' for parameter "').concat(e.parameter,'"'):"Missing parameter: ".concat(e.parameter),e}return r}(ja(Error)),Bb=function(o){Hl(r,o);var n=zl(r);function r(a){var c;return ql(this,r),c=n.call(this),c.code=2,c.name="INVALID_STATE_ERROR",c.status=a,c.message="Invalid status: ".concat(a),c}return r}(ja(Error)),Vb=function(o){Hl(r,o);var n=zl(r);function r(a){var c;return ql(this,r),c=n.call(this),c.code=3,c.name="NOT_SUPPORTED_ERROR",c.message=a,c}return r}(ja(Error)),jb=function(o){Hl(r,o);var n=zl(r);function r(a){var c;return ql(this,r),c=n.call(this),c.code=4,c.name="NOT_READY_ERROR",c.message=a,c}return r}(ja(Error)),ai={ConfigurationError:Fb,InvalidStateError:Bb,NotSupportedError:Vb,NotReadyError:jb},on={},uc,Kh;function cc(){if(Kh)return uc;Kh=1;function o(e,f){if(!(e instanceof f))throw new TypeError("Cannot call a class as a function")}function n(e,f){for(var g=0;g<f.length;g++){var d=f[g];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(e,d.key,d)}}function r(e,f,g){return f&&n(e.prototype,f),g&&n(e,g),e}var a=oi(),c=ss();return uc=function(){r(e,null,[{key:"parse",value:function(f){if(f=c.parse(f,"Name_Addr_Header"),f!==-1)return f}}]);function e(f,g,d){if(o(this,e),!f||!(f instanceof a))throw new TypeError('missing or invalid "uri" parameter');this._uri=f,this._parameters={},this.display_name=g;for(var A in d)Object.prototype.hasOwnProperty.call(d,A)&&this.setParam(A,d[A])}return r(e,[{key:"setParam",value:function(f,g){f&&(this._parameters[f.toLowerCase()]=typeof g>"u"||g===null?null:g.toString())}},{key:"getParam",value:function(f){if(f)return this._parameters[f.toLowerCase()]}},{key:"hasParam",value:function(f){if(f)return this._parameters.hasOwnProperty(f.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(f){if(f=f.toLowerCase(),this._parameters.hasOwnProperty(f)){var g=this._parameters[f];return delete this._parameters[f],g}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"clone",value:function(){return new e(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}},{key:"_quote",value:function(f){return f.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}},{key:"toString",value:function(){var f=this._display_name?'"'.concat(this._quote(this._display_name),'" '):"";f+="<".concat(this._uri.toString(),">");for(var g in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,g)&&(f+=";".concat(g),this._parameters[g]!==null&&(f+="=".concat(this._parameters[g])));return f}},{key:"uri",get:function(){return this._uri}},{key:"display_name",get:function(){return this._display_name},set:function(f){this._display_name=f===0?"0":f}}]),e}(),uc}var Yh,Xh;function ss(){return Xh||(Xh=1,Yh=function(){function o(r){return'"'+r.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 n={parse:function(r,a){var c={CRLF:A,DIGIT:S,ALPHA:R,HEXDIG:N,WSP:H,OCTET:W,DQUOTE:G,SP:K,HTAB:ae,alphanum:ee,reserved:De,unreserved:X,mark:re,escaped:be,LWS:Ne,SWS:Q,HCOLON:ce,TEXT_UTF8_TRIM:me,TEXT_UTF8char:_e,UTF8_NONASCII:ue,UTF8_CONT:ye,LHEX:Re,token:J,token_nodot:Se,separators:$e,word:zt,STAR:Ae,SLASH:fe,EQUAL:se,LPAREN:st,RPAREN:We,RAQUOT:ht,LAQUOT:It,COMMA:qe,SEMI:Ue,COLON:wt,LDQUOT:Yt,RDQUOT:Xe,comment:Je,ctext:ut,quoted_string:_t,quoted_string_clean:mt,qdtext:Le,quoted_pair:Pe,SIP_URI_noparams:Ze,SIP_URI:Tt,uri_scheme:qt,uri_scheme_sips:rn,uri_scheme_sip:Dt,userinfo:Wn,user:Pn,user_unreserved:Bs,password:Aa,hostport:jr,host:ar,hostname:_n,domainlabel:Gr,toplabel:yi,IPv6reference:Wr,IPv6address:Kr,h16:de,ls32:Pt,IPv4address:or,dec_octet:lr,port:gn,uri_parameters:Vs,uri_parameter:$r,transport_param:vi,user_param:Ti,method_param:js,ttl_param:bi,maddr_param:Gs,lr_param:wi,other_param:Ws,pname:Si,pvalue:Ks,paramchar:Qn,param_unreserved:ds,headers:Yr,header:mr,hname:Ei,hvalue:Ci,hnv_unreserved:ur,Request_Response:Ia,Request_Line:$t,Request_URI:gr,absoluteURI:yn,hier_part:hs,net_path:Et,abs_path:yr,opaque_part:Ai,uric:vr,uric_no_slash:Ii,path_segments:Ri,segment:xr,param:Tr,pchar:cr,scheme:$i,authority:Ra,srvr:br,reg_name:Zn,query:wr,SIP_Version:Or,INVITEm:ps,ACKm:Ys,OPTIONSm:Xs,BYEm:Js,CANCELm:rt,REGISTERm:Qs,SUBSCRIBEm:xi,NOTIFYm:Oi,REFERm:ki,Method:kr,Status_Line:Di,Status_Code:Zs,extension_code:Ni,Reason_Phrase:vt,Allow_Events:Sr,Call_ID:lo,Contact:_s,contact_param:ne,name_addr:fn,display_name:Dr,contact_params:fs,c_p_q:Mi,c_p_expires:ct,delta_seconds:vn,qvalue:Ui,generic_param:gt,gen_value:ei,Content_Disposition:$a,disp_type:Pi,disp_param:Xr,handling_param:Li,Content_Encoding:xa,Content_Length:Oa,Content_Type:ka,media_type:qi,m_type:Hi,discrete_type:Da,composite_type:Jr,extension_token:Nr,x_token:zi,m_subtype:Na,m_parameter:Qr,m_value:ti,CSeq:Fi,CSeq_value:ms,Expires:uo,Event:co,event_type:er,From:Ma,from_param:gs,tag_param:ys,Max_Forwards:El,Min_Expires:ho,Name_Addr_Header:Ct,Proxy_Authenticate:Ft,challenge:dr,other_challenge:vs,auth_param:Nt,digest_cln:Gt,realm:Qe,realm_value:Ut,domain:ni,URI:Kn,nonce:hr,nonce_value:Ke,opaque:Zr,stale:le,algorithm:Ge,qop_options:Bi,qop_value:Er,Proxy_Require:po,Record_Route:_o,rec_route:at,Reason:fo,reason_param:es,reason_cause:Vi,Require:mo,Route:go,route_param:Mr,Subscription_State:Ln,substate_value:ji,subexp_params:Ts,event_reason_value:pr,Subject:yo,Supported:vo,To,to_param:bs,Via:bo,via_param:Ur,via_params:ws,via_ttl:Gi,via_maddr:Wi,via_received:Ki,via_branch:qn,response_port:Yi,rport:Xi,sent_protocol:Ji,protocol_name:Qi,transport:Zi,sent_by:ea,via_host:ta,via_port:na,ttl:Ss,WWW_Authenticate:wo,Session_Expires:Cl,s_e_expires:Hn,s_e_params:Es,s_e_refresher:Cs,extension_header:Ua,header_value:zn,message_body:So,uuid_URI:Eo,uuid:ra,hex4:sn,hex8:sa,hex12:ia,Refer_To:Co,Replaces:Ao,call_id:aa,replaces_param:As,to_tag:Fn,from_tag:oa,early_flag:la};if(a!==void 0){if(c[a]===void 0)throw new Error("Invalid rule name: "+o(a)+".")}else a="CRLF";var e=0,f=0,g=[];function d(t){e<f||(e>f&&(f=e,g=[]),g.push(t))}function A(){var t;return r.substr(e,2)===`\r
|
|
1
|
+
(function(xs,At){typeof exports=="object"&&typeof module<"u"?At(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],At):(xs=typeof globalThis<"u"?globalThis:xs||self,At(xs["vsip-next"]={},xs.Vue))})(this,function(xs,At){"use strict";function Tb(o,n){for(var r=0;r<n.length;r++){const a=n[r];if(typeof a!="string"&&!Array.isArray(a)){for(const c in a)if(c!=="default"&&!(c in o)){const e=Object.getOwnPropertyDescriptor(a,c);e&&Object.defineProperty(o,c,e.get?e:{enumerable:!0,get:()=>a[c]})}}}return Object.freeze(Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}))}var bb=Object.defineProperty,wb=(o,n,r)=>n in o?bb(o,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):o[n]=r,rs=(o,n,r)=>(wb(o,typeof n!="symbol"?n+"":n,r),r),Sb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Qt(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}const Eb="jssip",Cb="JsSIP",Ab="the Javascript SIP library",Ib="3.10.0",Rb="https://jssip.net",$b=["José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)","Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)"],xb="lib/JsSIP.d.ts",Ob="lib-es5/JsSIP.js",kb=["sip","websocket","webrtc","node","browser","library"],Db="MIT",Nb={type:"git",url:"https://github.com/versatica/JsSIP.git"},Mb={url:"https://github.com/versatica/JsSIP/issues"},Ub={"@types/events":"^3.0.0","@types/debug":"^4.1.7",debug:"^4.3.1",events:"^3.3.0","sdp-transform":"^2.14.1"},Pb={"@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"},Lb={lint:"node npm-scripts.js lint",test:"node npm-scripts.js test",prepublish:"node npm-scripts.js prepublish",release:"node npm-scripts.js release"},Pl={name:Eb,title:Cb,description:Ab,version:Ib,homepage:Rb,contributors:$b,types:xb,main:Ob,keywords:kb,license:Db,repository:Nb,bugs:Mb,dependencies:Ub,devDependencies:Pb,scripts:Lb};var Gh=Pl,dn={USER_AGENT:"".concat(Gh.title," ").concat(Gh.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 Ll(o){"@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(o)}function ql(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Hl(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Do(o,n)}function zl(o){var n=Wh();return function(){var r=No(o),a;if(n){var c=No(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return qb(this,a)}}function qb(o,n){return n&&(Ll(n)==="object"||typeof n=="function")?n:Hb(o)}function Hb(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function ja(o){var n=typeof Map=="function"?new Map:void 0;return ja=function(r){if(r===null||!zb(r))return r;if(typeof r!="function")throw new TypeError("Super expression must either be null or a function");if(typeof n<"u"){if(n.has(r))return n.get(r);n.set(r,a)}function a(){return Fl(r,arguments,No(this).constructor)}return a.prototype=Object.create(r.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),Do(a,r)},ja(o)}function Fl(o,n,r){return Wh()?Fl=Reflect.construct:Fl=function(a,c,e){var _=[null];_.push.apply(_,c);var g=Function.bind.apply(a,_),d=new g;return e&&Do(d,e.prototype),d},Fl.apply(null,arguments)}function Wh(){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 zb(o){return Function.toString.call(o).indexOf("[native code]")!==-1}function Do(o,n){return Do=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Do(o,n)}function No(o){return No=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},No(o)}var Fb=function(o){Hl(r,o);var n=zl(r);function r(a,c){var e;return ql(this,r),e=n.call(this),e.code=1,e.name="CONFIGURATION_ERROR",e.parameter=a,e.value=c,e.message=e.value?"Invalid value ".concat(JSON.stringify(e.value),' for parameter "').concat(e.parameter,'"'):"Missing parameter: ".concat(e.parameter),e}return r}(ja(Error)),Bb=function(o){Hl(r,o);var n=zl(r);function r(a){var c;return ql(this,r),c=n.call(this),c.code=2,c.name="INVALID_STATE_ERROR",c.status=a,c.message="Invalid status: ".concat(a),c}return r}(ja(Error)),Vb=function(o){Hl(r,o);var n=zl(r);function r(a){var c;return ql(this,r),c=n.call(this),c.code=3,c.name="NOT_SUPPORTED_ERROR",c.message=a,c}return r}(ja(Error)),jb=function(o){Hl(r,o);var n=zl(r);function r(a){var c;return ql(this,r),c=n.call(this),c.code=4,c.name="NOT_READY_ERROR",c.message=a,c}return r}(ja(Error)),ai={ConfigurationError:Fb,InvalidStateError:Bb,NotSupportedError:Vb,NotReadyError:jb},on={},uc,Kh;function cc(){if(Kh)return uc;Kh=1;function o(e,_){if(!(e instanceof _))throw new TypeError("Cannot call a class as a function")}function n(e,_){for(var g=0;g<_.length;g++){var d=_[g];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(e,d.key,d)}}function r(e,_,g){return _&&n(e.prototype,_),g&&n(e,g),e}var a=oi(),c=ss();return uc=function(){r(e,null,[{key:"parse",value:function(_){if(_=c.parse(_,"Name_Addr_Header"),_!==-1)return _}}]);function e(_,g,d){if(o(this,e),!_||!(_ instanceof a))throw new TypeError('missing or invalid "uri" parameter');this._uri=_,this._parameters={},this.display_name=g;for(var A in d)Object.prototype.hasOwnProperty.call(d,A)&&this.setParam(A,d[A])}return r(e,[{key:"setParam",value:function(_,g){_&&(this._parameters[_.toLowerCase()]=typeof g>"u"||g===null?null:g.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 g=this._parameters[_];return delete this._parameters[_],g}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"clone",value:function(){return new e(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 g in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,g)&&(_+=";".concat(g),this._parameters[g]!==null&&(_+="=".concat(this._parameters[g])));return _}},{key:"uri",get:function(){return this._uri}},{key:"display_name",get:function(){return this._display_name},set:function(_){this._display_name=_===0?"0":_}}]),e}(),uc}var Yh,Xh;function ss(){return Xh||(Xh=1,Yh=function(){function o(r){return'"'+r.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 n={parse:function(r,a){var c={CRLF:A,DIGIT:S,ALPHA:R,HEXDIG:N,WSP:H,OCTET:W,DQUOTE:G,SP:K,HTAB:ae,alphanum:ee,reserved:De,unreserved:X,mark:re,escaped:be,LWS:Ne,SWS:Q,HCOLON:ce,TEXT_UTF8_TRIM:me,TEXT_UTF8char:_e,UTF8_NONASCII:ue,UTF8_CONT:ye,LHEX:Re,token:J,token_nodot:Se,separators:$e,word:zt,STAR:Ae,SLASH:fe,EQUAL:se,LPAREN:st,RPAREN:We,RAQUOT:ht,LAQUOT:It,COMMA:qe,SEMI:Ue,COLON:wt,LDQUOT:Yt,RDQUOT:Xe,comment:Je,ctext:ut,quoted_string:_t,quoted_string_clean:mt,qdtext:Le,quoted_pair:Pe,SIP_URI_noparams:Ze,SIP_URI:Tt,uri_scheme:qt,uri_scheme_sips:rn,uri_scheme_sip:Dt,userinfo:Wn,user:Pn,user_unreserved:Bs,password:Aa,hostport:jr,host:ar,hostname:_n,domainlabel:Gr,toplabel:yi,IPv6reference:Wr,IPv6address:Kr,h16:de,ls32:Pt,IPv4address:or,dec_octet:lr,port:gn,uri_parameters:Vs,uri_parameter:$r,transport_param:vi,user_param:Ti,method_param:js,ttl_param:bi,maddr_param:Gs,lr_param:wi,other_param:Ws,pname:Si,pvalue:Ks,paramchar:Qn,param_unreserved:ds,headers:Yr,header:mr,hname:Ei,hvalue:Ci,hnv_unreserved:ur,Request_Response:Ia,Request_Line:$t,Request_URI:gr,absoluteURI:yn,hier_part:hs,net_path:Et,abs_path:yr,opaque_part:Ai,uric:vr,uric_no_slash:Ii,path_segments:Ri,segment:xr,param:Tr,pchar:cr,scheme:$i,authority:Ra,srvr:br,reg_name:Zn,query:wr,SIP_Version:Or,INVITEm:ps,ACKm:Ys,OPTIONSm:Xs,BYEm:Js,CANCELm:rt,REGISTERm:Qs,SUBSCRIBEm:xi,NOTIFYm:Oi,REFERm:ki,Method:kr,Status_Line:Di,Status_Code:Zs,extension_code:Ni,Reason_Phrase:vt,Allow_Events:Sr,Call_ID:lo,Contact:_s,contact_param:ne,name_addr:fn,display_name:Dr,contact_params:fs,c_p_q:Mi,c_p_expires:ct,delta_seconds:vn,qvalue:Ui,generic_param:gt,gen_value:ei,Content_Disposition:$a,disp_type:Pi,disp_param:Xr,handling_param:Li,Content_Encoding:xa,Content_Length:Oa,Content_Type:ka,media_type:qi,m_type:Hi,discrete_type:Da,composite_type:Jr,extension_token:Nr,x_token:zi,m_subtype:Na,m_parameter:Qr,m_value:ti,CSeq:Fi,CSeq_value:ms,Expires:uo,Event:co,event_type:er,From:Ma,from_param:gs,tag_param:ys,Max_Forwards:El,Min_Expires:ho,Name_Addr_Header:Ct,Proxy_Authenticate:Ft,challenge:dr,other_challenge:vs,auth_param:Nt,digest_cln:Gt,realm:Qe,realm_value:Ut,domain:ni,URI:Kn,nonce:hr,nonce_value:Ke,opaque:Zr,stale:le,algorithm:Ge,qop_options:Bi,qop_value:Er,Proxy_Require:po,Record_Route:_o,rec_route:at,Reason:fo,reason_param:es,reason_cause:Vi,Require:mo,Route:go,route_param:Mr,Subscription_State:Ln,substate_value:ji,subexp_params:Ts,event_reason_value:pr,Subject:yo,Supported:vo,To,to_param:bs,Via:bo,via_param:Ur,via_params:ws,via_ttl:Gi,via_maddr:Wi,via_received:Ki,via_branch:qn,response_port:Yi,rport:Xi,sent_protocol:Ji,protocol_name:Qi,transport:Zi,sent_by:ea,via_host:ta,via_port:na,ttl:Ss,WWW_Authenticate:wo,Session_Expires:Cl,s_e_expires:Hn,s_e_params:Es,s_e_refresher:Cs,extension_header:Ua,header_value:zn,message_body:So,uuid_URI:Eo,uuid:ra,hex4:sn,hex8:sa,hex12:ia,Refer_To:Co,Replaces:Ao,call_id:aa,replaces_param:As,to_tag:Fn,from_tag:oa,early_flag:la};if(a!==void 0){if(c[a]===void 0)throw new Error("Invalid rule name: "+o(a)+".")}else a="CRLF";var e=0,_=0,g=[];function d(t){e<_||(e>_&&(_=e,g=[]),g.push(t))}function A(){var t;return r.substr(e,2)===`\r
|
|
2
2
|
`?(t=`\r
|
|
3
|
-
`,e+=2):(t=null,d('"\\r\\n"')),t}function S(){var t;return/^[0-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[0-9]")),t}function R(){var t;return/^[a-zA-Z]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-zA-Z]")),t}function N(){var t;return/^[0-9a-fA-F]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[0-9a-fA-F]")),t}function H(){var t;return t=K(),t===null&&(t=ae()),t}function W(){var t;return/^[\0-\xFF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\0-\\xFF]")),t}function G(){var t;return/^["]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d('["]')),t}function K(){var t;return r.charCodeAt(e)===32?(t=" ",e++):(t=null,d('" "')),t}function ae(){var t;return r.charCodeAt(e)===9?(t=" ",e++):(t=null,d('"\\t"')),t}function ee(){var t;return/^[a-zA-Z0-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-zA-Z0-9]")),t}function De(){var t;return r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","'))))))))))),t}function X(){var t;return t=ee(),t===null&&(t=re()),t}function re(){var t;return r.charCodeAt(e)===45?(t="-",e++):(t=null,d('"-"')),t===null&&(r.charCodeAt(e)===95?(t="_",e++):(t=null,d('"_"')),t===null&&(r.charCodeAt(e)===46?(t=".",e++):(t=null,d('"."')),t===null&&(r.charCodeAt(e)===33?(t="!",e++):(t=null,d('"!"')),t===null&&(r.charCodeAt(e)===126?(t="~",e++):(t=null,d('"~"')),t===null&&(r.charCodeAt(e)===42?(t="*",e++):(t=null,d('"*"')),t===null&&(r.charCodeAt(e)===39?(t="'",e++):(t=null,d(`"'"`)),t===null&&(r.charCodeAt(e)===40?(t="(",e++):(t=null,d('"("')),t===null&&(r.charCodeAt(e)===41?(t=")",e++):(t=null,d('")"')))))))))),t}function be(){var t,i,l,h,_;return h=e,_=e,r.charCodeAt(e)===37?(t="%",e++):(t=null,d('"%"')),t!==null?(i=N(),i!==null?(l=N(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){return I.join("")}(h,t)),t===null&&(e=h),t}function Ne(){var t,i,l,h,_,v;for(h=e,_=e,v=e,t=[],i=H();i!==null;)t.push(i),i=H();if(t!==null?(i=A(),i!==null?t=[t,i]:(t=null,e=v)):(t=null,e=v),t=t!==null?t:"",t!==null){if(l=H(),l!==null)for(i=[];l!==null;)i.push(l),l=H();else i=null;i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t!==null&&(t=function(I){return" "}()),t===null&&(e=h),t}function Q(){var t;return t=Ne(),t=t!==null?t:"",t}function ce(){var t,i,l,h,_;for(h=e,_=e,t=[],i=K(),i===null&&(i=ae());i!==null;)t.push(i),i=K(),i===null&&(i=ae());return t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return":"}()),t===null&&(e=h),t}function me(){var t,i,l,h,_,v,I;if(_=e,v=e,i=_e(),i!==null)for(t=[];i!==null;)t.push(i),i=_e();else t=null;if(t!==null){for(i=[],I=e,l=[],h=Ne();h!==null;)l.push(h),h=Ne();for(l!==null?(h=_e(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;){for(i.push(l),I=e,l=[],h=Ne();h!==null;)l.push(h),h=Ne();l!==null?(h=_e(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I)}i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){return r.substring(e,q)}(_)),t===null&&(e=_),t}function _e(){var t;return/^[!-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[!-~]")),t===null&&(t=ue()),t}function ue(){var t;return/^[\x80-\uFFFF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\x80-\\uFFFF]")),t}function ye(){var t;return/^[\x80-\xBF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\x80-\\xBF]")),t}function Re(){var t;return t=S(),t===null&&(/^[a-f]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-f]"))),t}function J(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"'))))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function Se(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"'))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function $e(){var t;return r.charCodeAt(e)===40?(t="(",e++):(t=null,d('"("')),t===null&&(r.charCodeAt(e)===41?(t=")",e++):(t=null,d('")"')),t===null&&(r.charCodeAt(e)===60?(t="<",e++):(t=null,d('"<"')),t===null&&(r.charCodeAt(e)===62?(t=">",e++):(t=null,d('">"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===92?(t="\\",e++):(t=null,d('"\\\\"')),t===null&&(t=G(),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===123?(t="{",e++):(t=null,d('"{"')),t===null&&(r.charCodeAt(e)===125?(t="}",e++):(t=null,d('"}"')),t===null&&(t=K(),t===null&&(t=ae())))))))))))))))))),t}function zt(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')),i===null&&(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i===null&&(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i===null&&(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i===null&&(r.charCodeAt(e)===62?(i=">",e++):(i=null,d('">"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===92?(i="\\",e++):(i=null,d('"\\\\"')),i===null&&(i=G(),i===null&&(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i===null&&(r.charCodeAt(e)===91?(i="[",e++):(i=null,d('"["')),i===null&&(r.charCodeAt(e)===93?(i="]",e++):(i=null,d('"]"')),i===null&&(r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i===null&&(r.charCodeAt(e)===123?(i="{",e++):(i=null,d('"{"')),i===null&&(r.charCodeAt(e)===125?(i="}",e++):(i=null,d('"}"'))))))))))))))))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')),i===null&&(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i===null&&(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i===null&&(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i===null&&(r.charCodeAt(e)===62?(i=">",e++):(i=null,d('">"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===92?(i="\\",e++):(i=null,d('"\\\\"')),i===null&&(i=G(),i===null&&(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i===null&&(r.charCodeAt(e)===91?(i="[",e++):(i=null,d('"["')),i===null&&(r.charCodeAt(e)===93?(i="]",e++):(i=null,d('"]"')),i===null&&(r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i===null&&(r.charCodeAt(e)===123?(i="{",e++):(i=null,d('"{"')),i===null&&(r.charCodeAt(e)===125?(i="}",e++):(i=null,d('"}"')))))))))))))))))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function Ae(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return"*"}()),t===null&&(e=h),t}function fe(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return"/"}()),t===null&&(e=h),t}function se(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return"="}()),t===null&&(e=h),t}function st(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return"("}()),t===null&&(e=h),t}function We(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return")"}()),t===null&&(e=h),t}function ht(){var t,i,l,h;return l=e,h=e,r.charCodeAt(e)===62?(t=">",e++):(t=null,d('">"')),t!==null?(i=Q(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_){return">"}()),t===null&&(e=l),t}function It(){var t,i,l,h;return l=e,h=e,t=Q(),t!==null?(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_){return"<"}()),t===null&&(e=l),t}function qe(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return","}()),t===null&&(e=h),t}function Ue(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return";"}()),t===null&&(e=h),t}function wt(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return":"}()),t===null&&(e=h),t}function Yt(){var t,i,l,h;return l=e,h=e,t=Q(),t!==null?(i=G(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_){return'"'}()),t===null&&(e=l),t}function Xe(){var t,i,l,h;return l=e,h=e,t=G(),t!==null?(i=Q(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_){return'"'}()),t===null&&(e=l),t}function Je(){var t,i,l,h;if(h=e,t=st(),t!==null){for(i=[],l=ut(),l===null&&(l=Pe(),l===null&&(l=Je()));l!==null;)i.push(l),l=ut(),l===null&&(l=Pe(),l===null&&(l=Je()));i!==null?(l=We(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)}else t=null,e=h;return t}function ut(){var t;return/^[!-']/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[!-']")),t===null&&(/^[*-[]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[*-[]")),t===null&&(/^[\]-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\]-~]")),t===null&&(t=ue(),t===null&&(t=Ne())))),t}function _t(){var t,i,l,h,_,v;if(_=e,v=e,t=Q(),t!==null)if(i=G(),i!==null){for(l=[],h=Le(),h===null&&(h=Pe());h!==null;)l.push(h),h=Le(),h===null&&(h=Pe());l!==null?(h=G(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I){return r.substring(e,I)}(_)),t===null&&(e=_),t}function mt(){var t,i,l,h,_,v;if(_=e,v=e,t=Q(),t!==null)if(i=G(),i!==null){for(l=[],h=Le(),h===null&&(h=Pe());h!==null;)l.push(h),h=Le(),h===null&&(h=Pe());l!==null?(h=G(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I){var q=r.substring(e,I).trim();return q.substring(1,q.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(_)),t===null&&(e=_),t}function Le(){var t;return t=Ne(),t===null&&(r.charCodeAt(e)===33?(t="!",e++):(t=null,d('"!"')),t===null&&(/^[#-[]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[#-[]")),t===null&&(/^[\]-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\]-~]")),t===null&&(t=ue())))),t}function Pe(){var t,i,l;return l=e,r.charCodeAt(e)===92?(t="\\",e++):(t=null,d('"\\\\"')),t!==null?(/^[\0-\t]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\0-\\t]")),i===null&&(/^[\x0B-\f]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\x0B-\\f]")),i===null&&(/^[\x0E-]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\x0E-]")))),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Ze(){var t,i,l,h,_,v;return _=e,v=e,t=qt(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Wn(),l=l!==null?l:"",l!==null?(h=jr(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t!==null&&(t=function(I){try{M.uri=new ua(M.scheme,M.user,M.host,M.port),delete M.scheme,delete M.user,delete M.host,delete M.host_type,delete M.port}catch{M=-1}}()),t===null&&(e=_),t}function Tt(){var t,i,l,h,_,v,I,q;return I=e,q=e,t=qt(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Wn(),l=l!==null?l:"",l!==null?(h=jr(),h!==null?(_=Vs(),_!==null?(v=Yr(),v=v!==null?v:"",v!==null?t=[t,i,l,h,_,v]:(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q),t!==null&&(t=function(j){try{M.uri=new ua(M.scheme,M.user,M.host,M.port,M.uri_params,M.uri_headers),delete M.scheme,delete M.user,delete M.host,delete M.host_type,delete M.port,delete M.uri_params,a==="SIP_URI"&&(M=M.uri)}catch{M=-1}}()),t===null&&(e=I),t}function qt(){var t;return t=rn(),t===null&&(t=Dt()),t}function rn(){var t,i;return i=e,r.substr(e,4).toLowerCase()==="sips"?(t=r.substr(e,4),e+=4):(t=null,d('"sips"')),t!==null&&(t=function(l,h){M.scheme=h.toLowerCase()}(i,t)),t===null&&(e=i),t}function Dt(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"sip"')),t!==null&&(t=function(l,h){M.scheme=h.toLowerCase()}(i,t)),t===null&&(e=i),t}function Wn(){var t,i,l,h,_,v;return h=e,_=e,t=Pn(),t!==null?(v=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Aa(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?(r.charCodeAt(e)===64?(l="@",e++):(l=null,d('"@"')),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){M.user=decodeURIComponent(r.substring(e-1,I))}(h)),t===null&&(e=h),t}function Pn(){var t,i;if(i=X(),i===null&&(i=be(),i===null&&(i=Bs())),i!==null)for(t=[];i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(i=Bs()));else t=null;return t}function Bs(){var t;return r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"'))))))))),t}function Aa(){var t,i,l;for(l=e,t=[],i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","'))))))));i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","'))))))));return t!==null&&(t=function(h){M.password=r.substring(e,h)}(l)),t===null&&(e=l),t}function jr(){var t,i,l,h,_;return h=e,t=ar(),t!==null?(_=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=gn(),l!==null?i=[i,l]:(i=null,e=_)):(i=null,e=_),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function ar(){var t,i;return i=e,t=_n(),t===null&&(t=or(),t===null&&(t=Wr())),t!==null&&(t=function(l){return M.host=r.substring(e,l).toLowerCase(),M.host}(i)),t===null&&(e=i),t}function _n(){var t,i,l,h,_,v;for(h=e,_=e,t=[],v=e,i=Gr(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v);i!==null;)t.push(i),v=e,i=Gr(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v);return t!==null?(i=yi(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){return M.host_type="domain",r.substring(e,I)}(h)),t===null&&(e=h),t}function Gr(){var t,i,l,h;if(h=e,t=ee(),t!==null){for(i=[],l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));l!==null;)i.push(l),l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function yi(){var t,i,l,h;if(h=e,t=R(),t!==null){for(i=[],l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));l!==null;)i.push(l),l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function Wr(){var t,i,l,h,_;return h=e,_=e,r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t!==null?(i=Kr(),i!==null?(r.charCodeAt(e)===93?(l="]",e++):(l=null,d('"]"')),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return M.host_type="IPv6",r.substring(e,v)}(h)),t===null&&(e=h),t}function Kr(){var t,i,l,h,_,v,I,q,j,Oe,it,an,Pr,ts,z,he;return ts=e,z=e,t=de(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?(r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=de(),j!==null?(r.charCodeAt(e)===58?(Oe=":",e++):(Oe=null,d('":"')),Oe!==null?(it=de(),it!==null?(r.charCodeAt(e)===58?(an=":",e++):(an=null,d('":"')),an!==null?(Pr=Pt(),Pr!==null?t=[t,i,l,h,_,v,I,q,j,Oe,it,an,Pr]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=de(),Oe!==null?(r.charCodeAt(e)===58?(it=":",e++):(it=null,d('":"')),it!==null?(an=Pt(),an!==null?t=[t,i,l,h,_,v,I,q,j,Oe,it,an]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=Pt(),Oe!==null?t=[t,i,l,h,_,v,I,q,j,Oe]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=Pt(),q!==null?t=[t,i,l,h,_,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=Pt(),v!==null?t=[t,i,l,h,_,v]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=Pt(),h!==null?t=[t,i,l,h]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=Pt(),i!==null?t=[t,i]:(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?t=[t,i]:(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(r.substr(e,2)==="::"?(i="::",e+=2):(i=null,d('"::"')),i!==null?(l=de(),l!==null?(r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=de(),j!==null?(r.charCodeAt(e)===58?(Oe=":",e++):(Oe=null,d('":"')),Oe!==null?(it=Pt(),it!==null?t=[t,i,l,h,_,v,I,q,j,Oe,it]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(r.substr(e,2)==="::"?(l="::",e+=2):(l=null,d('"::"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=Pt(),Oe!==null?t=[t,i,l,h,_,v,I,q,j,Oe]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(r.substr(e,2)==="::"?(h="::",e+=2):(h=null,d('"::"')),h!==null?(_=de(),_!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=Pt(),j!==null?t=[t,i,l,h,_,v,I,q,j]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?h=[h,_]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(r.substr(e,2)==="::"?(_="::",e+=2):(_=null,d('"::"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=Pt(),q!==null?t=[t,i,l,h,_,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?h=[h,_]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?_=[_,v]:(_=null,e=he)):(_=null,e=he),_=_!==null?_:"",_!==null?(r.substr(e,2)==="::"?(v="::",e+=2):(v=null,d('"::"')),v!==null?(I=Pt(),I!==null?t=[t,i,l,h,_,v,I]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?h=[h,_]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?_=[_,v]:(_=null,e=he)):(_=null,e=he),_=_!==null?_:"",_!==null?(he=e,r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?v=[v,I]:(v=null,e=he)):(v=null,e=he),v=v!==null?v:"",v!==null?(r.substr(e,2)==="::"?(I="::",e+=2):(I=null,d('"::"')),I!==null?(q=de(),q!==null?t=[t,i,l,h,_,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?h=[h,_]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?_=[_,v]:(_=null,e=he)):(_=null,e=he),_=_!==null?_:"",_!==null?(he=e,r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?v=[v,I]:(v=null,e=he)):(v=null,e=he),v=v!==null?v:"",v!==null?(he=e,r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?I=[I,q]:(I=null,e=he)):(I=null,e=he),I=I!==null?I:"",I!==null?(r.substr(e,2)==="::"?(q="::",e+=2):(q=null,d('"::"')),q!==null?t=[t,i,l,h,_,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z))))))))))))))),t!==null&&(t=function(Oo){return M.host_type="IPv6",r.substring(e,Oo)}(ts)),t===null&&(e=ts),t}function de(){var t,i,l,h,_;return _=e,t=N(),t!==null?(i=N(),i=i!==null?i:"",i!==null?(l=N(),l=l!==null?l:"",l!==null?(h=N(),h=h!==null?h:"",h!==null?t=[t,i,l,h]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t}function Pt(){var t,i,l,h;return h=e,t=de(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(t=or()),t}function or(){var t,i,l,h,_,v,I,q,j;return q=e,j=e,t=lr(),t!==null?(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i!==null?(l=lr(),l!==null?(r.charCodeAt(e)===46?(h=".",e++):(h=null,d('"."')),h!==null?(_=lr(),_!==null?(r.charCodeAt(e)===46?(v=".",e++):(v=null,d('"."')),v!==null?(I=lr(),I!==null?t=[t,i,l,h,_,v,I]:(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j),t!==null&&(t=function(Oe){return M.host_type="IPv4",r.substring(e,Oe)}(q)),t===null&&(e=q),t}function lr(){var t,i,l,h;return h=e,r.substr(e,2)==="25"?(t="25",e+=2):(t=null,d('"25"')),t!==null?(/^[0-5]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[0-5]")),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t===null&&(h=e,r.charCodeAt(e)===50?(t="2",e++):(t=null,d('"2"')),t!==null?(/^[0-4]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[0-4]")),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(h=e,r.charCodeAt(e)===49?(t="1",e++):(t=null,d('"1"')),t!==null?(i=S(),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(h=e,/^[1-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[1-9]")),t!==null?(i=S(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t===null&&(t=S())))),t}function gn(){var t,i,l,h,_,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(_=S(),_=_!==null?_:"",_!==null?t=[t,i,l,h,_]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){return j=parseInt(j.join("")),M.port=j,j}(v,t)),t===null&&(e=v),t}function Vs(){var t,i,l,h;for(t=[],h=e,r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=$r(),l!==null?i=[i,l]:(i=null,e=h)):(i=null,e=h);i!==null;)t.push(i),h=e,r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=$r(),l!==null?i=[i,l]:(i=null,e=h)):(i=null,e=h);return t}function $r(){var t;return t=vi(),t===null&&(t=Ti(),t===null&&(t=js(),t===null&&(t=bi(),t===null&&(t=Gs(),t===null&&(t=wi(),t===null&&(t=Ws())))))),t}function vi(){var t,i,l,h;return l=e,h=e,r.substr(e,10).toLowerCase()==="transport="?(t=r.substr(e,10),e+=10):(t=null,d('"transport="')),t!==null?(r.substr(e,3).toLowerCase()==="udp"?(i=r.substr(e,3),e+=3):(i=null,d('"udp"')),i===null&&(r.substr(e,3).toLowerCase()==="tcp"?(i=r.substr(e,3),e+=3):(i=null,d('"tcp"')),i===null&&(r.substr(e,4).toLowerCase()==="sctp"?(i=r.substr(e,4),e+=4):(i=null,d('"sctp"')),i===null&&(r.substr(e,3).toLowerCase()==="tls"?(i=r.substr(e,3),e+=3):(i=null,d('"tls"')),i===null&&(i=J())))),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.uri_params||(M.uri_params={}),M.uri_params.transport=v.toLowerCase()}(l,t[1])),t===null&&(e=l),t}function Ti(){var t,i,l,h;return l=e,h=e,r.substr(e,5).toLowerCase()==="user="?(t=r.substr(e,5),e+=5):(t=null,d('"user="')),t!==null?(r.substr(e,5).toLowerCase()==="phone"?(i=r.substr(e,5),e+=5):(i=null,d('"phone"')),i===null&&(r.substr(e,2).toLowerCase()==="ip"?(i=r.substr(e,2),e+=2):(i=null,d('"ip"')),i===null&&(i=J())),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.uri_params||(M.uri_params={}),M.uri_params.user=v.toLowerCase()}(l,t[1])),t===null&&(e=l),t}function js(){var t,i,l,h;return l=e,h=e,r.substr(e,7).toLowerCase()==="method="?(t=r.substr(e,7),e+=7):(t=null,d('"method="')),t!==null?(i=kr(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.uri_params||(M.uri_params={}),M.uri_params.method=v}(l,t[1])),t===null&&(e=l),t}function bi(){var t,i,l,h;return l=e,h=e,r.substr(e,4).toLowerCase()==="ttl="?(t=r.substr(e,4),e+=4):(t=null,d('"ttl="')),t!==null?(i=Ss(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.params||(M.params={}),M.params.ttl=v}(l,t[1])),t===null&&(e=l),t}function Gs(){var t,i,l,h;return l=e,h=e,r.substr(e,6).toLowerCase()==="maddr="?(t=r.substr(e,6),e+=6):(t=null,d('"maddr="')),t!==null?(i=ar(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.uri_params||(M.uri_params={}),M.uri_params.maddr=v}(l,t[1])),t===null&&(e=l),t}function wi(){var t,i,l,h,_,v;return h=e,_=e,r.substr(e,2).toLowerCase()==="lr"?(t=r.substr(e,2),e+=2):(t=null,d('"lr"')),t!==null?(v=e,r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=J(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){M.uri_params||(M.uri_params={}),M.uri_params.lr=void 0}()),t===null&&(e=h),t}function Ws(){var t,i,l,h,_,v;return h=e,_=e,t=Si(),t!==null?(v=e,r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Ks(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I,q,j){M.uri_params||(M.uri_params={}),typeof j>"u"?j=void 0:j=j[1],M.uri_params[q.toLowerCase()]=j}(h,t[0],t[1])),t===null&&(e=h),t}function Si(){var t,i,l;if(l=e,i=Qn(),i!==null)for(t=[];i!==null;)t.push(i),i=Qn();else t=null;return t!==null&&(t=function(h,_){return _.join("")}(l,t)),t===null&&(e=l),t}function Ks(){var t,i,l;if(l=e,i=Qn(),i!==null)for(t=[];i!==null;)t.push(i),i=Qn();else t=null;return t!==null&&(t=function(h,_){return _.join("")}(l,t)),t===null&&(e=l),t}function Qn(){var t;return t=ds(),t===null&&(t=X(),t===null&&(t=be())),t}function ds(){var t;return r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')))))))),t}function Yr(){var t,i,l,h,_,v,I;if(v=e,r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t!==null)if(i=mr(),i!==null){for(l=[],I=e,r.charCodeAt(e)===38?(h="&",e++):(h=null,d('"&"')),h!==null?(_=mr(),_!==null?h=[h,_]:(h=null,e=I)):(h=null,e=I);h!==null;)l.push(h),I=e,r.charCodeAt(e)===38?(h="&",e++):(h=null,d('"&"')),h!==null?(_=mr(),_!==null?h=[h,_]:(h=null,e=I)):(h=null,e=I);l!==null?t=[t,i,l]:(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t}function mr(){var t,i,l,h,_;return h=e,_=e,t=Ei(),t!==null?(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Ci(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I,q){I=I.join("").toLowerCase(),q=q.join(""),M.uri_headers||(M.uri_headers={}),M.uri_headers[I]?M.uri_headers[I].push(q):M.uri_headers[I]=[q]}(h,t[0],t[2])),t===null&&(e=h),t}function Ei(){var t,i;if(i=ur(),i===null&&(i=X(),i===null&&(i=be())),i!==null)for(t=[];i!==null;)t.push(i),i=ur(),i===null&&(i=X(),i===null&&(i=be()));else t=null;return t}function Ci(){var t,i;for(t=[],i=ur(),i===null&&(i=X(),i===null&&(i=be()));i!==null;)t.push(i),i=ur(),i===null&&(i=X(),i===null&&(i=be()));return t}function ur(){var t;return r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')))))))),t}function Ia(){var t;return t=Di(),t===null&&(t=$t()),t}function $t(){var t,i,l,h,_,v;return v=e,t=kr(),t!==null?(i=K(),i!==null?(l=gr(),l!==null?(h=K(),h!==null?(_=Or(),_!==null?t=[t,i,l,h,_]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function gr(){var t;return t=Tt(),t===null&&(t=yn()),t}function yn(){var t,i,l,h;return h=e,t=$i(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=hs(),l===null&&(l=Ai()),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function hs(){var t,i,l,h,_;return h=e,t=Et(),t===null&&(t=yr()),t!==null?(_=e,r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i!==null?(l=wr(),l!==null?i=[i,l]:(i=null,e=_)):(i=null,e=_),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function Et(){var t,i,l,h;return h=e,r.substr(e,2)==="//"?(t="//",e+=2):(t=null,d('"//"')),t!==null?(i=Ra(),i!==null?(l=yr(),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function yr(){var t,i,l;return l=e,r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t!==null?(i=Ri(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Ai(){var t,i,l,h;if(h=e,t=Ii(),t!==null){for(i=[],l=vr();l!==null;)i.push(l),l=vr();i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function vr(){var t;return t=De(),t===null&&(t=X(),t===null&&(t=be())),t}function Ii(){var t;return t=X(),t===null&&(t=be(),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')))))))))))),t}function Ri(){var t,i,l,h,_,v;if(_=e,t=xr(),t!==null){for(i=[],v=e,r.charCodeAt(e)===47?(l="/",e++):(l=null,d('"/"')),l!==null?(h=xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===47?(l="/",e++):(l=null,d('"/"')),l!==null?(h=xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function xr(){var t,i,l,h,_,v;for(_=e,t=[],i=cr();i!==null;)t.push(i),i=cr();if(t!==null){for(i=[],v=e,r.charCodeAt(e)===59?(l=";",e++):(l=null,d('";"')),l!==null?(h=Tr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===59?(l=";",e++):(l=null,d('";"')),l!==null?(h=Tr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Tr(){var t,i;for(t=[],i=cr();i!==null;)t.push(i),i=cr();return t}function cr(){var t;return t=X(),t===null&&(t=be(),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')))))))))),t}function $i(){var t,i,l,h,_;if(h=e,_=e,t=R(),t!==null){for(i=[],l=R(),l===null&&(l=S(),l===null&&(r.charCodeAt(e)===43?(l="+",e++):(l=null,d('"+"')),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."'))))));l!==null;)i.push(l),l=R(),l===null&&(l=S(),l===null&&(r.charCodeAt(e)===43?(l="+",e++):(l=null,d('"+"')),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."'))))));i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t!==null&&(t=function(v){M.scheme=r.substring(e,v)}(h)),t===null&&(e=h),t}function Ra(){var t;return t=br(),t===null&&(t=Zn()),t}function br(){var t,i,l,h;return l=e,h=e,t=Wn(),t!==null?(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t=t!==null?t:"",t!==null?(i=jr(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t=t!==null?t:"",t}function Zn(){var t,i;if(i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i===null&&(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"'))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i===null&&(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')))))))))));else t=null;return t}function wr(){var t,i;for(t=[],i=vr();i!==null;)t.push(i),i=vr();return t}function Or(){var t,i,l,h,_,v,I,q;if(I=e,q=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t!==null)if(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i!==null){if(h=S(),h!==null)for(l=[];h!==null;)l.push(h),h=S();else l=null;if(l!==null)if(r.charCodeAt(e)===46?(h=".",e++):(h=null,d('"."')),h!==null){if(v=S(),v!==null)for(_=[];v!==null;)_.push(v),v=S();else _=null;_!==null?t=[t,i,l,h,_]:(t=null,e=q)}else t=null,e=q;else t=null,e=q}else t=null,e=q;else t=null,e=q;return t!==null&&(t=function(j){M.sip_version=r.substring(e,j)}(I)),t===null&&(e=I),t}function ps(){var t;return r.substr(e,6)==="INVITE"?(t="INVITE",e+=6):(t=null,d('"INVITE"')),t}function Ys(){var t;return r.substr(e,3)==="ACK"?(t="ACK",e+=3):(t=null,d('"ACK"')),t}function Xs(){var t;return r.substr(e,7)==="OPTIONS"?(t="OPTIONS",e+=7):(t=null,d('"OPTIONS"')),t}function Js(){var t;return r.substr(e,3)==="BYE"?(t="BYE",e+=3):(t=null,d('"BYE"')),t}function rt(){var t;return r.substr(e,6)==="CANCEL"?(t="CANCEL",e+=6):(t=null,d('"CANCEL"')),t}function Qs(){var t;return r.substr(e,8)==="REGISTER"?(t="REGISTER",e+=8):(t=null,d('"REGISTER"')),t}function xi(){var t;return r.substr(e,9)==="SUBSCRIBE"?(t="SUBSCRIBE",e+=9):(t=null,d('"SUBSCRIBE"')),t}function Oi(){var t;return r.substr(e,6)==="NOTIFY"?(t="NOTIFY",e+=6):(t=null,d('"NOTIFY"')),t}function ki(){var t;return r.substr(e,5)==="REFER"?(t="REFER",e+=5):(t=null,d('"REFER"')),t}function kr(){var t,i;return i=e,t=ps(),t===null&&(t=Ys(),t===null&&(t=Xs(),t===null&&(t=Js(),t===null&&(t=rt(),t===null&&(t=Qs(),t===null&&(t=xi(),t===null&&(t=Oi(),t===null&&(t=ki(),t===null&&(t=J()))))))))),t!==null&&(t=function(l){return M.method=r.substring(e,l),M.method}(i)),t===null&&(e=i),t}function Di(){var t,i,l,h,_,v;return v=e,t=Or(),t!==null?(i=K(),i!==null?(l=Zs(),l!==null?(h=K(),h!==null?(_=vt(),_!==null?t=[t,i,l,h,_]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function Zs(){var t,i;return i=e,t=Ni(),t!==null&&(t=function(l,h){M.status_code=parseInt(h.join(""))}(i,t)),t===null&&(e=i),t}function Ni(){var t,i,l,h;return h=e,t=S(),t!==null?(i=S(),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function vt(){var t,i,l;for(l=e,t=[],i=De(),i===null&&(i=X(),i===null&&(i=be(),i===null&&(i=ue(),i===null&&(i=ye(),i===null&&(i=K(),i===null&&(i=ae()))))));i!==null;)t.push(i),i=De(),i===null&&(i=X(),i===null&&(i=be(),i===null&&(i=ue(),i===null&&(i=ye(),i===null&&(i=K(),i===null&&(i=ae()))))));return t!==null&&(t=function(h){M.reason_phrase=r.substring(e,h)}(l)),t===null&&(e=l),t}function Sr(){var t,i,l,h,_,v;if(_=e,t=er(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=er(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=er(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function lo(){var t,i,l,h,_,v;return h=e,_=e,t=zt(),t!==null?(v=e,r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?(l=zt(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){M=r.substring(e,I)}(h)),t===null&&(e=h),t}function _s(){var t,i,l,h,_,v,I;if(_=e,t=Ae(),t===null)if(v=e,t=ne(),t!==null){for(i=[],I=e,l=qe(),l!==null?(h=ne(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=qe(),l!==null?(h=ne(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j,Oe;for(Oe=M.multi_header.length,j=0;j<Oe;j++)if(M.multi_header[j].parsed===null){M=null;break}M!==null?M=M.multi_header:M=-1}()),t===null&&(e=_),t}function ne(){var t,i,l,h,_,v,I;if(_=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=fs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=fs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j;M.multi_header||(M.multi_header=[]);try{j=new Yn(M.uri,M.display_name,M.params),delete M.uri,delete M.display_name,delete M.params}catch{j=null}M.multi_header.push({possition:e,offset:q,parsed:j})}(_)),t===null&&(e=_),t}function fn(){var t,i,l,h,_;return _=e,t=Dr(),t=t!==null?t:"",t!==null?(i=It(),i!==null?(l=Tt(),l!==null?(h=ht(),h!==null?t=[t,i,l,h]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t}function Dr(){var t,i,l,h,_,v,I;if(_=e,v=e,t=J(),t!==null){for(i=[],I=e,l=Ne(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ne(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t===null&&(t=mt()),t!==null&&(t=function(q,j){typeof j=="string"?M.display_name=j:M.display_name=j[1].reduce(function(Oe,it){return Oe+it[0]+it[1]},j[0])}(_,t)),t===null&&(e=_),t}function fs(){var t;return t=Mi(),t===null&&(t=ct(),t===null&&(t=gt())),t}function Mi(){var t,i,l,h,_;return h=e,_=e,r.substr(e,1).toLowerCase()==="q"?(t=r.substr(e,1),e++):(t=null,d('"q"')),t!==null?(i=se(),i!==null?(l=Ui(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.params||(M.params={}),M.params.q=I}(h,t[2])),t===null&&(e=h),t}function ct(){var t,i,l,h,_;return h=e,_=e,r.substr(e,7).toLowerCase()==="expires"?(t=r.substr(e,7),e+=7):(t=null,d('"expires"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.params||(M.params={}),M.params.expires=I}(h,t[2])),t===null&&(e=h),t}function vn(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,_){return parseInt(_.join(""))}(l,t)),t===null&&(e=l),t}function Ui(){var t,i,l,h,_,v,I,q;return v=e,I=e,r.charCodeAt(e)===48?(t="0",e++):(t=null,d('"0"')),t!==null?(q=e,r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(_=S(),_=_!==null?_:"",_!==null?i=[i,l,h,_]:(i=null,e=q)):(i=null,e=q)):(i=null,e=q)):(i=null,e=q),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(j){return parseFloat(r.substring(e,j))}(v)),t===null&&(e=v),t}function gt(){var t,i,l,h,_,v;return h=e,_=e,t=J(),t!==null?(v=e,i=se(),i!==null?(l=ei(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I,q,j){M.params||(M.params={}),typeof j>"u"?j=void 0:j=j[1],M.params[q.toLowerCase()]=j}(h,t[0],t[1])),t===null&&(e=h),t}function ei(){var t;return t=J(),t===null&&(t=ar(),t===null&&(t=_t())),t}function $a(){var t,i,l,h,_,v;if(_=e,t=Pi(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Pi(){var t;return r.substr(e,6).toLowerCase()==="render"?(t=r.substr(e,6),e+=6):(t=null,d('"render"')),t===null&&(r.substr(e,7).toLowerCase()==="session"?(t=r.substr(e,7),e+=7):(t=null,d('"session"')),t===null&&(r.substr(e,4).toLowerCase()==="icon"?(t=r.substr(e,4),e+=4):(t=null,d('"icon"')),t===null&&(r.substr(e,5).toLowerCase()==="alert"?(t=r.substr(e,5),e+=5):(t=null,d('"alert"')),t===null&&(t=J())))),t}function Xr(){var t;return t=Li(),t===null&&(t=gt()),t}function Li(){var t,i,l,h;return h=e,r.substr(e,8).toLowerCase()==="handling"?(t=r.substr(e,8),e+=8):(t=null,d('"handling"')),t!==null?(i=se(),i!==null?(r.substr(e,8).toLowerCase()==="optional"?(l=r.substr(e,8),e+=8):(l=null,d('"optional"')),l===null&&(r.substr(e,8).toLowerCase()==="required"?(l=r.substr(e,8),e+=8):(l=null,d('"required"')),l===null&&(l=J())),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function xa(){var t,i,l,h,_,v;if(_=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Oa(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,_){M=parseInt(_.join(""))}(l,t)),t===null&&(e=l),t}function ka(){var t,i;return i=e,t=qi(),t!==null&&(t=function(l){M=r.substring(e,l)}(i)),t===null&&(e=i),t}function qi(){var t,i,l,h,_,v,I,q;if(I=e,t=Hi(),t!==null)if(i=fe(),i!==null)if(l=Na(),l!==null){for(h=[],q=e,_=Ue(),_!==null?(v=Qr(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);_!==null;)h.push(_),q=e,_=Ue(),_!==null?(v=Qr(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function Hi(){var t;return t=Da(),t===null&&(t=Jr()),t}function Da(){var t;return r.substr(e,4).toLowerCase()==="text"?(t=r.substr(e,4),e+=4):(t=null,d('"text"')),t===null&&(r.substr(e,5).toLowerCase()==="image"?(t=r.substr(e,5),e+=5):(t=null,d('"image"')),t===null&&(r.substr(e,5).toLowerCase()==="audio"?(t=r.substr(e,5),e+=5):(t=null,d('"audio"')),t===null&&(r.substr(e,5).toLowerCase()==="video"?(t=r.substr(e,5),e+=5):(t=null,d('"video"')),t===null&&(r.substr(e,11).toLowerCase()==="application"?(t=r.substr(e,11),e+=11):(t=null,d('"application"')),t===null&&(t=Nr()))))),t}function Jr(){var t;return r.substr(e,7).toLowerCase()==="message"?(t=r.substr(e,7),e+=7):(t=null,d('"message"')),t===null&&(r.substr(e,9).toLowerCase()==="multipart"?(t=r.substr(e,9),e+=9):(t=null,d('"multipart"')),t===null&&(t=Nr())),t}function Nr(){var t;return t=J(),t===null&&(t=zi()),t}function zi(){var t,i,l;return l=e,r.substr(e,2).toLowerCase()==="x-"?(t=r.substr(e,2),e+=2):(t=null,d('"x-"')),t!==null?(i=J(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Na(){var t;return t=Nr(),t===null&&(t=J()),t}function Qr(){var t,i,l,h;return h=e,t=J(),t!==null?(i=se(),i!==null?(l=ti(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function ti(){var t;return t=J(),t===null&&(t=_t()),t}function Fi(){var t,i,l,h;return h=e,t=ms(),t!==null?(i=Ne(),i!==null?(l=kr(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function ms(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,_){M.value=parseInt(_.join(""))}(l,t)),t===null&&(e=l),t}function uo(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M=h}(i,t)),t===null&&(e=i),t}function co(){var t,i,l,h,_,v,I;if(_=e,v=e,t=er(),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q,j){M.event=j.join("").toLowerCase()}(_,t[0])),t===null&&(e=_),t}function er(){var t,i,l,h,_,v;if(_=e,t=Se(),t!==null){for(i=[],v=e,r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?(h=Se(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?(h=Se(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Ma(){var t,i,l,h,_,v,I;if(_=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j=M.tag;try{M=new Yn(M.uri,M.display_name,M.params),j&&M.setParam("tag",j)}catch{M=-1}}()),t===null&&(e=_),t}function gs(){var t;return t=ys(),t===null&&(t=gt()),t}function ys(){var t,i,l,h,_;return h=e,_=e,r.substr(e,3).toLowerCase()==="tag"?(t=r.substr(e,3),e+=3):(t=null,d('"tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.tag=I}(h,t[2])),t===null&&(e=h),t}function El(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,_){M=parseInt(_.join(""))}(l,t)),t===null&&(e=l),t}function ho(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M=h}(i,t)),t===null&&(e=i),t}function Ct(){var t,i,l,h,_,v,I,q,j,Oe;for(q=e,j=e,t=[],i=Dr();i!==null;)t.push(i),i=Dr();if(t!==null)if(i=It(),i!==null)if(l=Tt(),l!==null)if(h=ht(),h!==null){for(_=[],Oe=e,v=Ue(),v!==null?(I=gt(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);v!==null;)_.push(v),Oe=e,v=Ue(),v!==null?(I=gt(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);_!==null?t=[t,i,l,h,_]:(t=null,e=j)}else t=null,e=j;else t=null,e=j;else t=null,e=j;else t=null,e=j;return t!==null&&(t=function(it){try{M=new Yn(M.uri,M.display_name,M.params)}catch{M=-1}}()),t===null&&(e=q),t}function Ft(){var t;return t=dr(),t}function dr(){var t,i,l,h,_,v,I,q;if(I=e,r.substr(e,6).toLowerCase()==="digest"?(t=r.substr(e,6),e+=6):(t=null,d('"Digest"')),t!==null)if(i=Ne(),i!==null)if(l=Gt(),l!==null){for(h=[],q=e,_=qe(),_!==null?(v=Gt(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);_!==null;)h.push(_),q=e,_=qe(),_!==null?(v=Gt(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t===null&&(t=vs()),t}function vs(){var t,i,l,h,_,v,I,q;if(I=e,t=J(),t!==null)if(i=Ne(),i!==null)if(l=Nt(),l!==null){for(h=[],q=e,_=qe(),_!==null?(v=Nt(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);_!==null;)h.push(_),q=e,_=qe(),_!==null?(v=Nt(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function Nt(){var t,i,l,h;return h=e,t=J(),t!==null?(i=se(),i!==null?(l=J(),l===null&&(l=_t()),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Gt(){var t;return t=Qe(),t===null&&(t=ni(),t===null&&(t=hr(),t===null&&(t=Zr(),t===null&&(t=le(),t===null&&(t=Ge(),t===null&&(t=Bi(),t===null&&(t=Nt()))))))),t}function Qe(){var t,i,l,h;return h=e,r.substr(e,5).toLowerCase()==="realm"?(t=r.substr(e,5),e+=5):(t=null,d('"realm"')),t!==null?(i=se(),i!==null?(l=Ut(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ut(){var t,i;return i=e,t=mt(),t!==null&&(t=function(l,h){M.realm=h}(i,t)),t===null&&(e=i),t}function ni(){var t,i,l,h,_,v,I,q,j;if(q=e,r.substr(e,6).toLowerCase()==="domain"?(t=r.substr(e,6),e+=6):(t=null,d('"domain"')),t!==null)if(i=se(),i!==null)if(l=Yt(),l!==null)if(h=Kn(),h!==null){if(_=[],j=e,I=K(),I!==null)for(v=[];I!==null;)v.push(I),I=K();else v=null;for(v!==null?(I=Kn(),I!==null?v=[v,I]:(v=null,e=j)):(v=null,e=j);v!==null;){if(_.push(v),j=e,I=K(),I!==null)for(v=[];I!==null;)v.push(I),I=K();else v=null;v!==null?(I=Kn(),I!==null?v=[v,I]:(v=null,e=j)):(v=null,e=j)}_!==null?(v=Xe(),v!==null?t=[t,i,l,h,_,v]:(t=null,e=q)):(t=null,e=q)}else t=null,e=q;else t=null,e=q;else t=null,e=q;else t=null,e=q;return t}function Kn(){var t;return t=yn(),t===null&&(t=yr()),t}function hr(){var t,i,l,h;return h=e,r.substr(e,5).toLowerCase()==="nonce"?(t=r.substr(e,5),e+=5):(t=null,d('"nonce"')),t!==null?(i=se(),i!==null?(l=Ke(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ke(){var t,i;return i=e,t=mt(),t!==null&&(t=function(l,h){M.nonce=h}(i,t)),t===null&&(e=i),t}function Zr(){var t,i,l,h,_;return h=e,_=e,r.substr(e,6).toLowerCase()==="opaque"?(t=r.substr(e,6),e+=6):(t=null,d('"opaque"')),t!==null?(i=se(),i!==null?(l=mt(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.opaque=I}(h,t[2])),t===null&&(e=h),t}function le(){var t,i,l,h,_;return h=e,r.substr(e,5).toLowerCase()==="stale"?(t=r.substr(e,5),e+=5):(t=null,d('"stale"')),t!==null?(i=se(),i!==null?(_=e,r.substr(e,4).toLowerCase()==="true"?(l=r.substr(e,4),e+=4):(l=null,d('"true"')),l!==null&&(l=function(v){M.stale=!0}()),l===null&&(e=_),l===null&&(_=e,r.substr(e,5).toLowerCase()==="false"?(l=r.substr(e,5),e+=5):(l=null,d('"false"')),l!==null&&(l=function(v){M.stale=!1}()),l===null&&(e=_)),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ge(){var t,i,l,h,_;return h=e,_=e,r.substr(e,9).toLowerCase()==="algorithm"?(t=r.substr(e,9),e+=9):(t=null,d('"algorithm"')),t!==null?(i=se(),i!==null?(r.substr(e,3).toLowerCase()==="md5"?(l=r.substr(e,3),e+=3):(l=null,d('"MD5"')),l===null&&(r.substr(e,8).toLowerCase()==="md5-sess"?(l=r.substr(e,8),e+=8):(l=null,d('"MD5-sess"')),l===null&&(l=J())),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.algorithm=I.toUpperCase()}(h,t[2])),t===null&&(e=h),t}function Bi(){var t,i,l,h,_,v,I,q,j,Oe;if(q=e,r.substr(e,3).toLowerCase()==="qop"?(t=r.substr(e,3),e+=3):(t=null,d('"qop"')),t!==null)if(i=se(),i!==null)if(l=Yt(),l!==null){if(j=e,h=Er(),h!==null){for(_=[],Oe=e,r.charCodeAt(e)===44?(v=",",e++):(v=null,d('","')),v!==null?(I=Er(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);v!==null;)_.push(v),Oe=e,r.charCodeAt(e)===44?(v=",",e++):(v=null,d('","')),v!==null?(I=Er(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);_!==null?h=[h,_]:(h=null,e=j)}else h=null,e=j;h!==null?(_=Xe(),_!==null?t=[t,i,l,h,_]:(t=null,e=q)):(t=null,e=q)}else t=null,e=q;else t=null,e=q;else t=null,e=q;return t}function Er(){var t,i;return i=e,r.substr(e,8).toLowerCase()==="auth-int"?(t=r.substr(e,8),e+=8):(t=null,d('"auth-int"')),t===null&&(r.substr(e,4).toLowerCase()==="auth"?(t=r.substr(e,4),e+=4):(t=null,d('"auth"')),t===null&&(t=J())),t!==null&&(t=function(l,h){M.qop||(M.qop=[]),M.qop.push(h.toLowerCase())}(i,t)),t===null&&(e=i),t}function po(){var t,i,l,h,_,v;if(_=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function _o(){var t,i,l,h,_,v,I;if(_=e,v=e,t=at(),t!==null){for(i=[],I=e,l=qe(),l!==null?(h=at(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=qe(),l!==null?(h=at(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j,Oe;for(Oe=M.multi_header.length,j=0;j<Oe;j++)if(M.multi_header[j].parsed===null){M=null;break}M!==null?M=M.multi_header:M=-1}()),t===null&&(e=_),t}function at(){var t,i,l,h,_,v,I;if(_=e,v=e,t=fn(),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j;M.multi_header||(M.multi_header=[]);try{j=new Yn(M.uri,M.display_name,M.params),delete M.uri,delete M.display_name,delete M.params}catch{j=null}M.multi_header.push({possition:e,offset:q,parsed:j})}(_)),t===null&&(e=_),t}function fo(){var t,i,l,h,_,v,I;if(_=e,v=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t===null&&(t=J()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=es(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=es(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q,j){if(M.protocol=j.toLowerCase(),M.params||(M.params={}),M.params.text&&M.params.text[0]==='"'){var Oe=M.params.text;M.text=Oe.substring(1,Oe.length-1),delete M.params.text}}(_,t[0])),t===null&&(e=_),t}function es(){var t;return t=Vi(),t===null&&(t=gt()),t}function Vi(){var t,i,l,h,_,v;if(_=e,v=e,r.substr(e,5).toLowerCase()==="cause"?(t=r.substr(e,5),e+=5):(t=null,d('"cause"')),t!==null)if(i=se(),i!==null){if(h=S(),h!==null)for(l=[];h!==null;)l.push(h),h=S();else l=null;l!==null?t=[t,i,l]:(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I,q){M.cause=parseInt(q.join(""))}(_,t[2])),t===null&&(e=_),t}function mo(){var t,i,l,h,_,v;if(_=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function go(){var t,i,l,h,_,v;if(_=e,t=Mr(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=Mr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=Mr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Mr(){var t,i,l,h,_,v;if(_=e,t=fn(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Ln(){var t,i,l,h,_,v;if(_=e,t=ji(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Ts(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Ts(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function ji(){var t,i;return i=e,r.substr(e,6).toLowerCase()==="active"?(t=r.substr(e,6),e+=6):(t=null,d('"active"')),t===null&&(r.substr(e,7).toLowerCase()==="pending"?(t=r.substr(e,7),e+=7):(t=null,d('"pending"')),t===null&&(r.substr(e,10).toLowerCase()==="terminated"?(t=r.substr(e,10),e+=10):(t=null,d('"terminated"')),t===null&&(t=J()))),t!==null&&(t=function(l){M.state=r.substring(e,l)}(i)),t===null&&(e=i),t}function Ts(){var t,i,l,h,_;return h=e,_=e,r.substr(e,6).toLowerCase()==="reason"?(t=r.substr(e,6),e+=6):(t=null,d('"reason"')),t!==null?(i=se(),i!==null?(l=pr(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){typeof I<"u"&&(M.reason=I)}(h,t[2])),t===null&&(e=h),t===null&&(h=e,_=e,r.substr(e,7).toLowerCase()==="expires"?(t=r.substr(e,7),e+=7):(t=null,d('"expires"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){typeof I<"u"&&(M.expires=I)}(h,t[2])),t===null&&(e=h),t===null&&(h=e,_=e,r.substr(e,11).toLowerCase()==="retry_after"?(t=r.substr(e,11),e+=11):(t=null,d('"retry_after"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){typeof I<"u"&&(M.retry_after=I)}(h,t[2])),t===null&&(e=h),t===null&&(t=gt()))),t}function pr(){var t;return r.substr(e,11).toLowerCase()==="deactivated"?(t=r.substr(e,11),e+=11):(t=null,d('"deactivated"')),t===null&&(r.substr(e,9).toLowerCase()==="probation"?(t=r.substr(e,9),e+=9):(t=null,d('"probation"')),t===null&&(r.substr(e,8).toLowerCase()==="rejected"?(t=r.substr(e,8),e+=8):(t=null,d('"rejected"')),t===null&&(r.substr(e,7).toLowerCase()==="timeout"?(t=r.substr(e,7),e+=7):(t=null,d('"timeout"')),t===null&&(r.substr(e,6).toLowerCase()==="giveup"?(t=r.substr(e,6),e+=6):(t=null,d('"giveup"')),t===null&&(r.substr(e,10).toLowerCase()==="noresource"?(t=r.substr(e,10),e+=10):(t=null,d('"noresource"')),t===null&&(r.substr(e,9).toLowerCase()==="invariant"?(t=r.substr(e,9),e+=9):(t=null,d('"invariant"')),t===null&&(t=J()))))))),t}function yo(){var t;return t=me(),t=t!==null?t:"",t}function vo(){var t,i,l,h,_,v;if(_=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t=t!==null?t:"",t}function To(){var t,i,l,h,_,v,I;if(_=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=bs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=bs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j=M.tag;try{M=new Yn(M.uri,M.display_name,M.params),j&&M.setParam("tag",j)}catch{M=-1}}()),t===null&&(e=_),t}function bs(){var t;return t=ys(),t===null&&(t=gt()),t}function bo(){var t,i,l,h,_,v;if(_=e,t=Ur(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=Ur(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=Ur(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Ur(){var t,i,l,h,_,v,I,q;if(I=e,t=Ji(),t!==null)if(i=Ne(),i!==null)if(l=ea(),l!==null){for(h=[],q=e,_=Ue(),_!==null?(v=ws(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);_!==null;)h.push(_),q=e,_=Ue(),_!==null?(v=ws(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function ws(){var t;return t=Gi(),t===null&&(t=Wi(),t===null&&(t=Ki(),t===null&&(t=qn(),t===null&&(t=Yi(),t===null&&(t=gt()))))),t}function Gi(){var t,i,l,h,_;return h=e,_=e,r.substr(e,3).toLowerCase()==="ttl"?(t=r.substr(e,3),e+=3):(t=null,d('"ttl"')),t!==null?(i=se(),i!==null?(l=Ss(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.ttl=I}(h,t[2])),t===null&&(e=h),t}function Wi(){var t,i,l,h,_;return h=e,_=e,r.substr(e,5).toLowerCase()==="maddr"?(t=r.substr(e,5),e+=5):(t=null,d('"maddr"')),t!==null?(i=se(),i!==null?(l=ar(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.maddr=I}(h,t[2])),t===null&&(e=h),t}function Ki(){var t,i,l,h,_;return h=e,_=e,r.substr(e,8).toLowerCase()==="received"?(t=r.substr(e,8),e+=8):(t=null,d('"received"')),t!==null?(i=se(),i!==null?(l=or(),l===null&&(l=Kr()),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.received=I}(h,t[2])),t===null&&(e=h),t}function qn(){var t,i,l,h,_;return h=e,_=e,r.substr(e,6).toLowerCase()==="branch"?(t=r.substr(e,6),e+=6):(t=null,d('"branch"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.branch=I}(h,t[2])),t===null&&(e=h),t}function Yi(){var t,i,l,h,_;return h=e,r.substr(e,5).toLowerCase()==="rport"?(t=r.substr(e,5),e+=5):(t=null,d('"rport"')),t!==null?(_=e,i=se(),i!==null?(l=Xi(),l!==null?i=[i,l]:(i=null,e=_)):(i=null,e=_),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function Xi(){var t,i,l,h,_,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(_=S(),_=_!==null?_:"",_!==null?t=[t,i,l,h,_]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){M.rport=parseInt(j.join(""))}(v,t)),t===null&&(e=v),t}function Ji(){var t,i,l,h,_,v;return v=e,t=Qi(),t!==null?(i=fe(),i!==null?(l=J(),l!==null?(h=fe(),h!==null?(_=Zi(),_!==null?t=[t,i,l,h,_]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function Qi(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t===null&&(t=J()),t!==null&&(t=function(l,h){M.protocol=h}(i,t)),t===null&&(e=i),t}function Zi(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="udp"?(t=r.substr(e,3),e+=3):(t=null,d('"UDP"')),t===null&&(r.substr(e,3).toLowerCase()==="tcp"?(t=r.substr(e,3),e+=3):(t=null,d('"TCP"')),t===null&&(r.substr(e,3).toLowerCase()==="tls"?(t=r.substr(e,3),e+=3):(t=null,d('"TLS"')),t===null&&(r.substr(e,4).toLowerCase()==="sctp"?(t=r.substr(e,4),e+=4):(t=null,d('"SCTP"')),t===null&&(t=J())))),t!==null&&(t=function(l,h){M.transport=h}(i,t)),t===null&&(e=i),t}function ea(){var t,i,l,h,_;return h=e,t=ta(),t!==null?(_=e,i=wt(),i!==null?(l=na(),l!==null?i=[i,l]:(i=null,e=_)):(i=null,e=_),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function ta(){var t,i;return i=e,t=or(),t===null&&(t=Wr(),t===null&&(t=_n())),t!==null&&(t=function(l){M.host=r.substring(e,l)}(i)),t===null&&(e=i),t}function na(){var t,i,l,h,_,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(_=S(),_=_!==null?_:"",_!==null?t=[t,i,l,h,_]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){M.port=parseInt(j.join(""))}(v,t)),t===null&&(e=v),t}function Ss(){var t,i,l,h,_;return h=e,_=e,t=S(),t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){return parseInt(I.join(""))}(h,t)),t===null&&(e=h),t}function wo(){var t;return t=dr(),t}function Cl(){var t,i,l,h,_,v;if(_=e,t=Hn(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Es(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Es(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Hn(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M.expires=h}(i,t)),t===null&&(e=i),t}function Es(){var t;return t=Cs(),t===null&&(t=gt()),t}function Cs(){var t,i,l,h,_;return h=e,_=e,r.substr(e,9).toLowerCase()==="refresher"?(t=r.substr(e,9),e+=9):(t=null,d('"refresher"')),t!==null?(i=se(),i!==null?(r.substr(e,3).toLowerCase()==="uac"?(l=r.substr(e,3),e+=3):(l=null,d('"uac"')),l===null&&(r.substr(e,3).toLowerCase()==="uas"?(l=r.substr(e,3),e+=3):(l=null,d('"uas"'))),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.refresher=I.toLowerCase()}(h,t[2])),t===null&&(e=h),t}function Ua(){var t,i,l,h;return h=e,t=J(),t!==null?(i=ce(),i!==null?(l=zn(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function zn(){var t,i;for(t=[],i=_e(),i===null&&(i=ye(),i===null&&(i=Ne()));i!==null;)t.push(i),i=_e(),i===null&&(i=ye(),i===null&&(i=Ne()));return t}function So(){var t,i;for(t=[],i=W();i!==null;)t.push(i),i=W();return t}function Eo(){var t,i,l;return l=e,r.substr(e,5)==="uuid:"?(t="uuid:",e+=5):(t=null,d('"uuid:"')),t!==null?(i=ra(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function ra(){var t,i,l,h,_,v,I,q,j,Oe,it;return Oe=e,it=e,t=sa(),t!==null?(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i!==null?(l=sn(),l!==null?(r.charCodeAt(e)===45?(h="-",e++):(h=null,d('"-"')),h!==null?(_=sn(),_!==null?(r.charCodeAt(e)===45?(v="-",e++):(v=null,d('"-"')),v!==null?(I=sn(),I!==null?(r.charCodeAt(e)===45?(q="-",e++):(q=null,d('"-"')),q!==null?(j=ia(),j!==null?t=[t,i,l,h,_,v,I,q,j]:(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it),t!==null&&(t=function(an,Pr){M=r.substring(e+5,an)}(Oe,t[0])),t===null&&(e=Oe),t}function sn(){var t,i,l,h,_;return _=e,t=N(),t!==null?(i=N(),i!==null?(l=N(),l!==null?(h=N(),h!==null?t=[t,i,l,h]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t}function sa(){var t,i,l;return l=e,t=sn(),t!==null?(i=sn(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function ia(){var t,i,l,h;return h=e,t=sn(),t!==null?(i=sn(),i!==null?(l=sn(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Co(){var t,i,l,h,_,v,I;if(_=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){try{M=new Yn(M.uri,M.display_name,M.params)}catch{M=-1}}()),t===null&&(e=_),t}function Ao(){var t,i,l,h,_,v;if(_=e,t=aa(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=As(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=As(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function aa(){var t,i,l,h,_,v;return h=e,_=e,t=zt(),t!==null?(v=e,r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?(l=zt(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){M.call_id=r.substring(e,I)}(h)),t===null&&(e=h),t}function As(){var t;return t=Fn(),t===null&&(t=oa(),t===null&&(t=la(),t===null&&(t=gt()))),t}function Fn(){var t,i,l,h,_;return h=e,_=e,r.substr(e,6)==="to-tag"?(t="to-tag",e+=6):(t=null,d('"to-tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.to_tag=I}(h,t[2])),t===null&&(e=h),t}function oa(){var t,i,l,h,_;return h=e,_=e,r.substr(e,8)==="from-tag"?(t="from-tag",e+=8):(t=null,d('"from-tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.from_tag=I}(h,t[2])),t===null&&(e=h),t}function la(){var t,i;return i=e,r.substr(e,10)==="early-only"?(t="early-only",e+=10):(t=null,d('"early-only"')),t!==null&&(t=function(l){M.early_only=!0}()),t===null&&(e=i),t}function Io(t){t.sort();for(var i=null,l=[],h=0;h<t.length;h++)t[h]!==i&&(l.push(t[h]),i=t[h]);return l}function Ro(){for(var t=1,i=1,l=!1,h=0;h<Math.max(e,f);h++){var _=r.charAt(h);_===`
|
|
4
|
-
`?(l||t++,i=1,l=!1):
|
|
5
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var W=!0,G=!1,K;return{s:function(){R=A[Symbol.iterator]()},n:function(){var ae=R.next();return W=ae.done,ae},e:function(ae){G=!0,K=ae},f:function(){try{!W&&R.return!=null&&R.return()}finally{if(G)throw K}}}}function n(A,S){if(A){if(typeof A=="string")return r(A,S);var R=Object.prototype.toString.call(A).slice(8,-1);if(R==="Object"&&A.constructor&&(R=A.constructor.name),R==="Map"||R==="Set")return Array.from(A);if(R==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(R))return r(A,S)}}function r(A,S){(S==null||S>A.length)&&(S=A.length);for(var R=0,N=new Array(S);R<S;R++)N[R]=A[R];return N}function a(A,S){if(!(A instanceof S))throw new TypeError("Cannot call a class as a function")}function c(A,S){for(var R=0;R<S.length;R++){var N=S[R];N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(A,N.key,N)}}function e(A,S,R){return S&&c(A.prototype,S),R&&c(A,R),A}var
|
|
6
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var G=!0,K=!1,ae;return{s:function(){N=S[Symbol.iterator]()},n:function(){var ee=N.next();return G=ee.done,ee},e:function(ee){K=!0,ae=ee},f:function(){try{!G&&N.return!=null&&N.return()}finally{if(K)throw ae}}}}function r(S,R){if(S){if(typeof S=="string")return a(S,R);var N=Object.prototype.toString.call(S).slice(8,-1);if(N==="Object"&&S.constructor&&(N=S.constructor.name),N==="Map"||N==="Set")return Array.from(S);if(N==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(N))return a(S,R)}}function a(S,R){(R==null||R>S.length)&&(R=S.length);for(var N=0,H=new Array(R);N<R;N++)H[N]=S[N];return H}var c=dn,e=oi(),f=ss();on.str_utf8_length=function(S){return unescape(encodeURIComponent(S)).length};var g=on.isFunction=function(S){return S!==void 0?Object.prototype.toString.call(S)==="[object Function]":!1};on.isString=function(S){return S!==void 0?Object.prototype.toString.call(S)==="[object String]":!1},on.isDecimal=function(S){return!isNaN(S)&&parseFloat(S)===parseInt(S,10)},on.isEmpty=function(S){return S===null||S===""||S===void 0||Array.isArray(S)&&S.length===0||typeof S=="number"&&isNaN(S)},on.hasMethods=function(S){for(var R=arguments.length,N=new Array(R>1?R-1:0),H=1;H<R;H++)N[H-1]=arguments[H];for(var W=0,G=N;W<G.length;W++){var K=G[W];if(g(S[K]))return!1}return!0};var d=on.createRandomToken=function(S){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:32,N,H,W="";for(N=0;N<S;N++)H=Math.random()*R|0,W+=H.toString(R);return W};on.newTag=function(){return d(10)},on.newUUID=function(){var S="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(R){var N=Math.random()*16|0,H=R==="x"?N:N&3|8;return H.toString(16)});return S},on.hostType=function(S){if(S){if(S=f.parse(S,"host"),S!==-1)return S.host_type}else return};var A=on.escapeUser=function(S){return encodeURIComponent(decodeURIComponent(S)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/")};return on.normalizeTarget=function(S,R){if(S){if(S instanceof e)return S;if(typeof S=="string"){var N=S.split("@"),H,W;switch(N.length){case 1:if(!R)return;H=S,W=R;break;case 2:H=N[0],W=N[1];break;default:H=N.slice(0,N.length-1).join("@"),W=N[N.length-1]}H=H.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(H)&&(H=H.replace(/[-.()]/g,"")),S="".concat(c.SIP,":").concat(A(H),"@").concat(W);var G;return(G=e.parse(S))?G:void 0}else return}else return},on.headerize=function(S){var R={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},N=S.toLowerCase().replace(/_/g,"-").split("-"),H="",W=N.length,G;for(G=0;G<W;G++)G!==0&&(H+="-"),H+=N[G].charAt(0).toUpperCase()+N[G].substring(1);return R[H]&&(H=R[H]),H},on.sipErrorCause=function(S){for(var R in c.SIP_ERROR_CAUSES)if(c.SIP_ERROR_CAUSES[R].indexOf(S)!==-1)return c.causes[R];return c.causes.SIP_FAILURE_CODE},on.getRandomTestNetIP=function(){function S(R,N){return Math.floor(Math.random()*(N-R+1)+R)}return"192.0.2.".concat(S(1,254))},on.calculateMD5=function(S){function R(Le,Pe){return Le<<Pe|Le>>>32-Pe}function N(Le,Pe){var Ze=Le&2147483648,Tt=Pe&2147483648,qt=Le&1073741824,rn=Pe&1073741824,Dt=(Le&1073741823)+(Pe&1073741823);return qt&rn?Dt^2147483648^Ze^Tt:qt|rn?Dt&1073741824?Dt^3221225472^Ze^Tt:Dt^1073741824^Ze^Tt:Dt^Ze^Tt}function H(Le,Pe,Ze){return Le&Pe|~Le&Ze}function W(Le,Pe,Ze){return Le&Ze|Pe&~Ze}function G(Le,Pe,Ze){return Le^Pe^Ze}function K(Le,Pe,Ze){return Pe^(Le|~Ze)}function ae(Le,Pe,Ze,Tt,qt,rn,Dt){return Le=N(Le,N(N(H(Pe,Ze,Tt),qt),Dt)),N(R(Le,rn),Pe)}function ee(Le,Pe,Ze,Tt,qt,rn,Dt){return Le=N(Le,N(N(W(Pe,Ze,Tt),qt),Dt)),N(R(Le,rn),Pe)}function De(Le,Pe,Ze,Tt,qt,rn,Dt){return Le=N(Le,N(N(G(Pe,Ze,Tt),qt),Dt)),N(R(Le,rn),Pe)}function X(Le,Pe,Ze,Tt,qt,rn,Dt){return Le=N(Le,N(N(K(Pe,Ze,Tt),qt),Dt)),N(R(Le,rn),Pe)}function re(Le){for(var Pe,Ze=Le.length,Tt=Ze+8,qt=(Tt-Tt%64)/64,rn=(qt+1)*16,Dt=new Array(rn-1),Wn=0,Pn=0;Pn<Ze;)Pe=(Pn-Pn%4)/4,Wn=Pn%4*8,Dt[Pe]=Dt[Pe]|Le.charCodeAt(Pn)<<Wn,Pn++;return Pe=(Pn-Pn%4)/4,Wn=Pn%4*8,Dt[Pe]=Dt[Pe]|128<<Wn,Dt[rn-2]=Ze<<3,Dt[rn-1]=Ze>>>29,Dt}function be(Le){var Pe="",Ze="",Tt,qt;for(qt=0;qt<=3;qt++)Tt=Le>>>qt*8&255,Ze="0".concat(Tt.toString(16)),Pe=Pe+Ze.substr(Ze.length-2,2);return Pe}function Ne(Le){for(var Pe="",Ze=0;Ze<Le.length;Ze++){var Tt=Le.charCodeAt(Ze);Tt<128?Pe+=String.fromCharCode(Tt):Tt>127&&Tt<2048?(Pe+=String.fromCharCode(Tt>>6|192),Pe+=String.fromCharCode(Tt&63|128)):(Pe+=String.fromCharCode(Tt>>12|224),Pe+=String.fromCharCode(Tt>>6&63|128),Pe+=String.fromCharCode(Tt&63|128))}return Pe}var Q=[],ce,me,_e,ue,ye,Re,J,Se,$e,zt=7,Ae=12,fe=17,se=22,st=5,We=9,ht=14,It=20,qe=4,Ue=11,wt=16,Yt=23,Xe=6,Je=10,ut=15,_t=21;for(S=Ne(S),Q=re(S),Re=1732584193,J=4023233417,Se=2562383102,$e=271733878,ce=0;ce<Q.length;ce+=16)me=Re,_e=J,ue=Se,ye=$e,Re=ae(Re,J,Se,$e,Q[ce+0],zt,3614090360),$e=ae($e,Re,J,Se,Q[ce+1],Ae,3905402710),Se=ae(Se,$e,Re,J,Q[ce+2],fe,606105819),J=ae(J,Se,$e,Re,Q[ce+3],se,3250441966),Re=ae(Re,J,Se,$e,Q[ce+4],zt,4118548399),$e=ae($e,Re,J,Se,Q[ce+5],Ae,1200080426),Se=ae(Se,$e,Re,J,Q[ce+6],fe,2821735955),J=ae(J,Se,$e,Re,Q[ce+7],se,4249261313),Re=ae(Re,J,Se,$e,Q[ce+8],zt,1770035416),$e=ae($e,Re,J,Se,Q[ce+9],Ae,2336552879),Se=ae(Se,$e,Re,J,Q[ce+10],fe,4294925233),J=ae(J,Se,$e,Re,Q[ce+11],se,2304563134),Re=ae(Re,J,Se,$e,Q[ce+12],zt,1804603682),$e=ae($e,Re,J,Se,Q[ce+13],Ae,4254626195),Se=ae(Se,$e,Re,J,Q[ce+14],fe,2792965006),J=ae(J,Se,$e,Re,Q[ce+15],se,1236535329),Re=ee(Re,J,Se,$e,Q[ce+1],st,4129170786),$e=ee($e,Re,J,Se,Q[ce+6],We,3225465664),Se=ee(Se,$e,Re,J,Q[ce+11],ht,643717713),J=ee(J,Se,$e,Re,Q[ce+0],It,3921069994),Re=ee(Re,J,Se,$e,Q[ce+5],st,3593408605),$e=ee($e,Re,J,Se,Q[ce+10],We,38016083),Se=ee(Se,$e,Re,J,Q[ce+15],ht,3634488961),J=ee(J,Se,$e,Re,Q[ce+4],It,3889429448),Re=ee(Re,J,Se,$e,Q[ce+9],st,568446438),$e=ee($e,Re,J,Se,Q[ce+14],We,3275163606),Se=ee(Se,$e,Re,J,Q[ce+3],ht,4107603335),J=ee(J,Se,$e,Re,Q[ce+8],It,1163531501),Re=ee(Re,J,Se,$e,Q[ce+13],st,2850285829),$e=ee($e,Re,J,Se,Q[ce+2],We,4243563512),Se=ee(Se,$e,Re,J,Q[ce+7],ht,1735328473),J=ee(J,Se,$e,Re,Q[ce+12],It,2368359562),Re=De(Re,J,Se,$e,Q[ce+5],qe,4294588738),$e=De($e,Re,J,Se,Q[ce+8],Ue,2272392833),Se=De(Se,$e,Re,J,Q[ce+11],wt,1839030562),J=De(J,Se,$e,Re,Q[ce+14],Yt,4259657740),Re=De(Re,J,Se,$e,Q[ce+1],qe,2763975236),$e=De($e,Re,J,Se,Q[ce+4],Ue,1272893353),Se=De(Se,$e,Re,J,Q[ce+7],wt,4139469664),J=De(J,Se,$e,Re,Q[ce+10],Yt,3200236656),Re=De(Re,J,Se,$e,Q[ce+13],qe,681279174),$e=De($e,Re,J,Se,Q[ce+0],Ue,3936430074),Se=De(Se,$e,Re,J,Q[ce+3],wt,3572445317),J=De(J,Se,$e,Re,Q[ce+6],Yt,76029189),Re=De(Re,J,Se,$e,Q[ce+9],qe,3654602809),$e=De($e,Re,J,Se,Q[ce+12],Ue,3873151461),Se=De(Se,$e,Re,J,Q[ce+15],wt,530742520),J=De(J,Se,$e,Re,Q[ce+2],Yt,3299628645),Re=X(Re,J,Se,$e,Q[ce+0],Xe,4096336452),$e=X($e,Re,J,Se,Q[ce+7],Je,1126891415),Se=X(Se,$e,Re,J,Q[ce+14],ut,2878612391),J=X(J,Se,$e,Re,Q[ce+5],_t,4237533241),Re=X(Re,J,Se,$e,Q[ce+12],Xe,1700485571),$e=X($e,Re,J,Se,Q[ce+3],Je,2399980690),Se=X(Se,$e,Re,J,Q[ce+10],ut,4293915773),J=X(J,Se,$e,Re,Q[ce+1],_t,2240044497),Re=X(Re,J,Se,$e,Q[ce+8],Xe,1873313359),$e=X($e,Re,J,Se,Q[ce+15],Je,4264355552),Se=X(Se,$e,Re,J,Q[ce+6],ut,2734768916),J=X(J,Se,$e,Re,Q[ce+13],_t,1309151649),Re=X(Re,J,Se,$e,Q[ce+4],Xe,4149444226),$e=X($e,Re,J,Se,Q[ce+11],Je,3174756917),Se=X(Se,$e,Re,J,Q[ce+2],ut,718787259),J=X(J,Se,$e,Re,Q[ce+9],_t,3951481745),Re=N(Re,me),J=N(J,_e),Se=N(Se,ue),$e=N($e,ye);var mt=be(Re)+be(J)+be(Se)+be($e);return mt.toLowerCase()},on.closeMediaStream=function(S){if(S)try{var R;if(S.getTracks){R=S.getTracks();var N=n(R),H;try{for(N.s();!(H=N.n()).done;){var W=H.value;W.stop()}}catch(re){N.e(re)}finally{N.f()}}else{R=S.getAudioTracks();var G=n(R),K;try{for(G.s();!(K=G.n()).done;){var ae=K.value;ae.stop()}}catch(re){G.e(re)}finally{G.f()}R=S.getVideoTracks();var ee=n(R),De;try{for(ee.s();!(De=ee.n()).done;){var X=De.value;X.stop()}}catch(re){ee.e(re)}finally{ee.f()}}}catch{(typeof S.stop=="function"||o(S.stop)==="object")&&S.stop()}},on.cloneArray=function(S){return S&&S.slice()||[]},on.cloneObject=function(S){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return S&&Object.assign({},S)||R},on}var hc={exports:{}},Ga=typeof Reflect=="object"?Reflect:null,Zh=Ga&&typeof Ga.apply=="function"?Ga.apply:function(o,n,r){return Function.prototype.apply.call(o,n,r)},Bl;Ga&&typeof Ga.ownKeys=="function"?Bl=Ga.ownKeys:Object.getOwnPropertySymbols?Bl=function(o){return Object.getOwnPropertyNames(o).concat(Object.getOwnPropertySymbols(o))}:Bl=function(o){return Object.getOwnPropertyNames(o)};function Gb(o){console&&console.warn&&console.warn(o)}var ep=Number.isNaN||function(o){return o!==o};function Lt(){Lt.init.call(this)}hc.exports=Lt,hc.exports.once=Xb,Lt.EventEmitter=Lt,Lt.prototype._events=void 0,Lt.prototype._eventsCount=0,Lt.prototype._maxListeners=void 0;var tp=10;function Vl(o){if(typeof o!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof o)}Object.defineProperty(Lt,"defaultMaxListeners",{enumerable:!0,get:function(){return tp},set:function(o){if(typeof o!="number"||o<0||ep(o))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+o+".");tp=o}}),Lt.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},Lt.prototype.setMaxListeners=function(o){if(typeof o!="number"||o<0||ep(o))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+o+".");return this._maxListeners=o,this};function np(o){return o._maxListeners===void 0?Lt.defaultMaxListeners:o._maxListeners}Lt.prototype.getMaxListeners=function(){return np(this)},Lt.prototype.emit=function(o){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var a=o==="error",c=this._events;if(c!==void 0)a=a&&c.error===void 0;else if(!a)return!1;if(a){var e;if(n.length>0&&(e=n[0]),e instanceof Error)throw e;var f=new Error("Unhandled error."+(e?" ("+e.message+")":""));throw f.context=e,f}var g=c[o];if(g===void 0)return!1;if(typeof g=="function")Zh(g,this,n);else for(var d=g.length,A=op(g,d),r=0;r<d;++r)Zh(A[r],this,n);return!0};function rp(o,n,r,a){var c,e,f;if(Vl(r),e=o._events,e===void 0?(e=o._events=Object.create(null),o._eventsCount=0):(e.newListener!==void 0&&(o.emit("newListener",n,r.listener?r.listener:r),e=o._events),f=e[n]),f===void 0)f=e[n]=r,++o._eventsCount;else if(typeof f=="function"?f=e[n]=a?[r,f]:[f,r]:a?f.unshift(r):f.push(r),c=np(o),c>0&&f.length>c&&!f.warned){f.warned=!0;var g=new Error("Possible EventEmitter memory leak detected. "+f.length+" "+String(n)+" listeners added. Use emitter.setMaxListeners() to increase limit");g.name="MaxListenersExceededWarning",g.emitter=o,g.type=n,g.count=f.length,Gb(g)}return o}Lt.prototype.addListener=function(o,n){return rp(this,o,n,!1)},Lt.prototype.on=Lt.prototype.addListener,Lt.prototype.prependListener=function(o,n){return rp(this,o,n,!0)};function Wb(){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 sp(o,n,r){var a={fired:!1,wrapFn:void 0,target:o,type:n,listener:r},c=Wb.bind(a);return c.listener=r,a.wrapFn=c,c}Lt.prototype.once=function(o,n){return Vl(n),this.on(o,sp(this,o,n)),this},Lt.prototype.prependOnceListener=function(o,n){return Vl(n),this.prependListener(o,sp(this,o,n)),this},Lt.prototype.removeListener=function(o,n){var r,a,c,e,f;if(Vl(n),a=this._events,a===void 0)return this;if(r=a[o],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete a[o],a.removeListener&&this.emit("removeListener",o,r.listener||n));else if(typeof r!="function"){for(c=-1,e=r.length-1;e>=0;e--)if(r[e]===n||r[e].listener===n){f=r[e].listener,c=e;break}if(c<0)return this;c===0?r.shift():Kb(r,c),r.length===1&&(a[o]=r[0]),a.removeListener!==void 0&&this.emit("removeListener",o,f||n)}return this},Lt.prototype.off=Lt.prototype.removeListener,Lt.prototype.removeAllListeners=function(o){var n,r,a;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[o]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[o]),this;if(arguments.length===0){var c=Object.keys(r),e;for(a=0;a<c.length;++a)e=c[a],e!=="removeListener"&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[o],typeof n=="function")this.removeListener(o,n);else if(n!==void 0)for(a=n.length-1;a>=0;a--)this.removeListener(o,n[a]);return this};function ip(o,n,r){var a=o._events;if(a===void 0)return[];var c=a[n];return c===void 0?[]:typeof c=="function"?r?[c.listener||c]:[c]:r?Yb(c):op(c,c.length)}Lt.prototype.listeners=function(o){return ip(this,o,!0)},Lt.prototype.rawListeners=function(o){return ip(this,o,!1)},Lt.listenerCount=function(o,n){return typeof o.listenerCount=="function"?o.listenerCount(n):ap.call(o,n)},Lt.prototype.listenerCount=ap;function ap(o){var n=this._events;if(n!==void 0){var r=n[o];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Lt.prototype.eventNames=function(){return this._eventsCount>0?Bl(this._events):[]};function op(o,n){for(var r=new Array(n),a=0;a<n;++a)r[a]=o[a];return r}function Kb(o,n){for(;n+1<o.length;n++)o[n]=o[n+1];o.pop()}function Yb(o){for(var n=new Array(o.length),r=0;r<n.length;++r)n[r]=o[r].listener||o[r];return n}function Xb(o,n){return new Promise(function(r,a){function c(f){o.removeListener(n,e),a(f)}function e(){typeof o.removeListener=="function"&&o.removeListener("error",c),r([].slice.call(arguments))}lp(o,n,e,{once:!0}),n!=="error"&&Jb(o,c,{once:!0})})}function Jb(o,n,r){typeof o.on=="function"&&lp(o,"error",n,r)}function lp(o,n,r,a){if(typeof o.on=="function")a.once?o.once(n,r):o.on(n,r);else if(typeof o.addEventListener=="function")o.addEventListener(n,function c(e){a.once&&o.removeEventListener(n,c),r(e)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof o)}var Tn=hc.exports,pc={exports:{}},_c,up;function Qb(){if(up)return _c;up=1;var o=1e3,n=o*60,r=n*60,a=r*24,c=a*7,e=a*365.25;_c=function(S,R){R=R||{};var N=typeof S;if(N==="string"&&S.length>0)return f(S);if(N==="number"&&isFinite(S))return R.long?d(S):g(S);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(S))};function f(S){if(S=String(S),!(S.length>100)){var R=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(S);if(R){var N=parseFloat(R[1]),H=(R[2]||"ms").toLowerCase();switch(H){case"years":case"year":case"yrs":case"yr":case"y":return N*e;case"weeks":case"week":case"w":return N*c;case"days":case"day":case"d":return N*a;case"hours":case"hour":case"hrs":case"hr":case"h":return N*r;case"minutes":case"minute":case"mins":case"min":case"m":return N*n;case"seconds":case"second":case"secs":case"sec":case"s":return N*o;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return N;default:return}}}}function g(S){var R=Math.abs(S);return R>=a?Math.round(S/a)+"d":R>=r?Math.round(S/r)+"h":R>=n?Math.round(S/n)+"m":R>=o?Math.round(S/o)+"s":S+"ms"}function d(S){var R=Math.abs(S);return R>=a?A(S,R,a,"day"):R>=r?A(S,R,r,"hour"):R>=n?A(S,R,n,"minute"):R>=o?A(S,R,o,"second"):S+" ms"}function A(S,R,N,H){var W=R>=N*1.5;return Math.round(S/N)+" "+H+(W?"s":"")}return _c}function Zb(o){r.debug=r,r.default=r,r.coerce=d,r.disable=e,r.enable=c,r.enabled=f,r.humanize=Qb(),r.destroy=A,Object.keys(o).forEach(S=>{r[S]=o[S]}),r.names=[],r.skips=[],r.formatters={};function n(S){let R=0;for(let N=0;N<S.length;N++)R=(R<<5)-R+S.charCodeAt(N),R|=0;return r.colors[Math.abs(R)%r.colors.length]}r.selectColor=n;function r(S){let R,N=null,H,W;function G(...K){if(!G.enabled)return;const ae=G,ee=Number(new Date),De=ee-(R||ee);ae.diff=De,ae.prev=R,ae.curr=ee,R=ee,K[0]=r.coerce(K[0]),typeof K[0]!="string"&&K.unshift("%O");let X=0;K[0]=K[0].replace(/%([a-zA-Z%])/g,(re,be)=>{if(re==="%%")return"%";X++;const Ne=r.formatters[be];if(typeof Ne=="function"){const Q=K[X];re=Ne.call(ae,Q),K.splice(X,1),X--}return re}),r.formatArgs.call(ae,K),(ae.log||r.log).apply(ae,K)}return G.namespace=S,G.useColors=r.useColors(),G.color=r.selectColor(S),G.extend=a,G.destroy=r.destroy,Object.defineProperty(G,"enabled",{enumerable:!0,configurable:!1,get:()=>N!==null?N:(H!==r.namespaces&&(H=r.namespaces,W=r.enabled(S)),W),set:K=>{N=K}}),typeof r.init=="function"&&r.init(G),G}function a(S,R){const N=r(this.namespace+(typeof R>"u"?":":R)+S);return N.log=this.log,N}function c(S){r.save(S),r.namespaces=S,r.names=[],r.skips=[];let R;const N=(typeof S=="string"?S:"").split(/[\s,]+/),H=N.length;for(R=0;R<H;R++)N[R]&&(S=N[R].replace(/\*/g,".*?"),S[0]==="-"?r.skips.push(new RegExp("^"+S.slice(1)+"$")):r.names.push(new RegExp("^"+S+"$")))}function e(){const S=[...r.names.map(g),...r.skips.map(g).map(R=>"-"+R)].join(",");return r.enable(""),S}function f(S){if(S[S.length-1]==="*")return!0;let R,N;for(R=0,N=r.skips.length;R<N;R++)if(r.skips[R].test(S))return!1;for(R=0,N=r.names.length;R<N;R++)if(r.names[R].test(S))return!0;return!1}function g(S){return S.toString().substring(2,S.toString().length-2).replace(/\.\*\?$/,"*")}function d(S){return S instanceof Error?S.stack||S.message:S}function A(){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 r.enable(r.load()),r}var e0=Zb;(function(o,n){n.formatArgs=a,n.save=c,n.load=e,n.useColors=r,n.storage=f(),n.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`."))}})(),n.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 r(){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 a(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+o.exports.humanize(this.diff),!this.useColors)return;const A="color: "+this.color;d.splice(1,0,A,"color: inherit");let S=0,R=0;d[0].replace(/%[a-zA-Z%]/g,N=>{N!=="%%"&&(S++,N==="%c"&&(R=S))}),d.splice(R,0,A)}n.log=console.debug||console.log||(()=>{});function c(d){try{d?n.storage.setItem("debug",d):n.storage.removeItem("debug")}catch{}}function e(){let d;try{d=n.storage.getItem("debug")}catch{}return!d&&typeof process<"u"&&"env"in process&&(d=process.env.DEBUG),d}function f(){try{return localStorage}catch{}}o.exports=e0(n);const{formatters:g}=o.exports;g.j=function(d){try{return JSON.stringify(d)}catch(A){return"[UnexpectedJSONParseError]: "+A.message}}})(pc,pc.exports);var Wa=pc.exports;function t0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function cp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function n0(o,n,r){return n&&cp(o.prototype,n),r&&cp(o,r),o}var Ka=Wa,Ya="JsSIP",bn=function(){function o(n){t0(this,o),n?(this._debug=Ka.default("".concat(Ya,":").concat(n)),this._warn=Ka.default("".concat(Ya,":WARN:").concat(n)),this._error=Ka.default("".concat(Ya,":ERROR:").concat(n))):(this._debug=Ka.default(Ya),this._warn=Ka.default("".concat(Ya,":WARN")),this._error=Ka.default("".concat(Ya,":ERROR"))),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}return n0(o,[{key:"debug",get:function(){return this._debug}},{key:"warn",get:function(){return this._warn}},{key:"error",get:function(){return this._error}}]),o}(),nr={},dp={},hp={exports:{}},pp=hp.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(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.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(o){return o.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(o){return o.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(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.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(o){var n="candidate:%s %d %s %d %s %d typ %s";return n+=o.raddr!=null?" raddr %s rport %d":"%v%v",n+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(n+=" generation %d"),n+=o["network-id"]!=null?" network-id %d":"%v",n+=o["network-cost"]!=null?" network-cost %d":"%v",n}},{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(o){var n="ssrc:%d";return o.attribute!=null&&(n+=" %s",o.value!=null&&(n+=":%s")),n}},{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(o){return o.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(o){return o.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(o){return"imageattr:%s %s %s"+(o.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(o){return"simulcast:%s %s"+(o.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(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var n="mediaclk:";return n+=o.id!=null?"id=%s %s":"%v%s",n+=o.mediaClockValue!=null?"=%s":"",n+=o.rateNumerator!=null?" rate=%s":"",n+=o.rateDenominator!=null?"/%s":"",n}},{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(pp).forEach(function(o){var n=pp[o];n.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})});var _p=hp.exports;(function(o){var n=function(g){return String(Number(g))===g?Number(g):g},r=function(g,d,A,S){if(S&&!A)d[S]=n(g[1]);else for(var R=0;R<A.length;R+=1)g[R+1]!=null&&(d[A[R]]=n(g[R+1]))},a=function(g,d,A){var S=g.name&&g.names;g.push&&!d[g.push]?d[g.push]=[]:S&&!d[g.name]&&(d[g.name]={});var R=g.push?{}:S?d[g.name]:d;r(A.match(g.reg),R,g.names,g.name),g.push&&d[g.push].push(R)},c=_p,e=RegExp.prototype.test.bind(/^([a-z])=(.*)/);o.parse=function(g){var d={},A=[],S=d;return g.split(/(\r\n|\r|\n)/).filter(e).forEach(function(R){var N=R[0],H=R.slice(2);N==="m"&&(A.push({rtp:[],fmtp:[]}),S=A[A.length-1]);for(var W=0;W<(c[N]||[]).length;W+=1){var G=c[N][W];if(G.reg.test(H))return a(G,S,H)}}),d.media=A,d};var f=function(g,d){var A=d.split(/=(.+)/,2);return A.length===2?g[A[0]]=n(A[1]):A.length===1&&d.length>1&&(g[A[0]]=void 0),g};o.parseParams=function(g){return g.split(/;\s?/).reduce(f,{})},o.parseFmtpConfig=o.parseParams,o.parsePayloads=function(g){return g.toString().split(" ").map(Number)},o.parseRemoteCandidates=function(g){for(var d=[],A=g.split(" ").map(n),S=0;S<A.length;S+=3)d.push({component:A[S],ip:A[S+1],port:A[S+2]});return d},o.parseImageAttributes=function(g){return g.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(f,{})})},o.parseSimulcastStreamList=function(g){return g.split(";").map(function(d){return d.split(",").map(function(A){var S,R=!1;return A[0]!=="~"?S=n(A):(S=n(A.substring(1,A.length)),R=!0),{scid:S,paused:R}})})}})(dp);var fc=_p,r0=/%[sdv%]/g,s0=function(o){var n=1,r=arguments,a=r.length;return o.replace(r0,function(c){if(n>=a)return c;var e=r[n];switch(n+=1,c){case"%%":return"%";case"%s":return String(e);case"%d":return Number(e);case"%v":return""}})},Mo=function(o,n,r){var a=n.format instanceof Function?n.format(n.push?r:r[n.name]):n.format,c=[o+"="+a];if(n.names)for(var e=0;e<n.names.length;e+=1){var f=n.names[e];n.name?c.push(r[n.name][f]):c.push(r[n.names[e]])}else c.push(r[n.name]);return s0.apply(null,c)},i0=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a0=["i","c","b","a"],o0=function(o,n){n=n||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(e){e.payloads==null&&(e.payloads="")});var r=n.outerOrder||i0,a=n.innerOrder||a0,c=[];return r.forEach(function(e){fc[e].forEach(function(f){f.name in o&&o[f.name]!=null?c.push(Mo(e,f,o)):f.push in o&&o[f.push]!=null&&o[f.push].forEach(function(g){c.push(Mo(e,f,g))})})}),o.media.forEach(function(e){c.push(Mo("m",fc.m[0],e)),a.forEach(function(f){fc[f].forEach(function(g){g.name in e&&e[g.name]!=null?c.push(Mo(f,g,e)):g.push in e&&e[g.push]!=null&&e[g.push].forEach(function(d){c.push(Mo(f,g,d))})})})}),c.join(`\r
|
|
3
|
+
`,e+=2):(t=null,d('"\\r\\n"')),t}function S(){var t;return/^[0-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[0-9]")),t}function R(){var t;return/^[a-zA-Z]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-zA-Z]")),t}function N(){var t;return/^[0-9a-fA-F]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[0-9a-fA-F]")),t}function H(){var t;return t=K(),t===null&&(t=ae()),t}function W(){var t;return/^[\0-\xFF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\0-\\xFF]")),t}function G(){var t;return/^["]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d('["]')),t}function K(){var t;return r.charCodeAt(e)===32?(t=" ",e++):(t=null,d('" "')),t}function ae(){var t;return r.charCodeAt(e)===9?(t=" ",e++):(t=null,d('"\\t"')),t}function ee(){var t;return/^[a-zA-Z0-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-zA-Z0-9]")),t}function De(){var t;return r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","'))))))))))),t}function X(){var t;return t=ee(),t===null&&(t=re()),t}function re(){var t;return r.charCodeAt(e)===45?(t="-",e++):(t=null,d('"-"')),t===null&&(r.charCodeAt(e)===95?(t="_",e++):(t=null,d('"_"')),t===null&&(r.charCodeAt(e)===46?(t=".",e++):(t=null,d('"."')),t===null&&(r.charCodeAt(e)===33?(t="!",e++):(t=null,d('"!"')),t===null&&(r.charCodeAt(e)===126?(t="~",e++):(t=null,d('"~"')),t===null&&(r.charCodeAt(e)===42?(t="*",e++):(t=null,d('"*"')),t===null&&(r.charCodeAt(e)===39?(t="'",e++):(t=null,d(`"'"`)),t===null&&(r.charCodeAt(e)===40?(t="(",e++):(t=null,d('"("')),t===null&&(r.charCodeAt(e)===41?(t=")",e++):(t=null,d('")"')))))))))),t}function be(){var t,i,l,h,f;return h=e,f=e,r.charCodeAt(e)===37?(t="%",e++):(t=null,d('"%"')),t!==null?(i=N(),i!==null?(l=N(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){return I.join("")}(h,t)),t===null&&(e=h),t}function Ne(){var t,i,l,h,f,v;for(h=e,f=e,v=e,t=[],i=H();i!==null;)t.push(i),i=H();if(t!==null?(i=A(),i!==null?t=[t,i]:(t=null,e=v)):(t=null,e=v),t=t!==null?t:"",t!==null){if(l=H(),l!==null)for(i=[];l!==null;)i.push(l),l=H();else i=null;i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t!==null&&(t=function(I){return" "}()),t===null&&(e=h),t}function Q(){var t;return t=Ne(),t=t!==null?t:"",t}function ce(){var t,i,l,h,f;for(h=e,f=e,t=[],i=K(),i===null&&(i=ae());i!==null;)t.push(i),i=K(),i===null&&(i=ae());return t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return":"}()),t===null&&(e=h),t}function me(){var t,i,l,h,f,v,I;if(f=e,v=e,i=_e(),i!==null)for(t=[];i!==null;)t.push(i),i=_e();else t=null;if(t!==null){for(i=[],I=e,l=[],h=Ne();h!==null;)l.push(h),h=Ne();for(l!==null?(h=_e(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;){for(i.push(l),I=e,l=[],h=Ne();h!==null;)l.push(h),h=Ne();l!==null?(h=_e(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I)}i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){return r.substring(e,q)}(f)),t===null&&(e=f),t}function _e(){var t;return/^[!-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[!-~]")),t===null&&(t=ue()),t}function ue(){var t;return/^[\x80-\uFFFF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\x80-\\uFFFF]")),t}function ye(){var t;return/^[\x80-\xBF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\x80-\\xBF]")),t}function Re(){var t;return t=S(),t===null&&(/^[a-f]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-f]"))),t}function J(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"'))))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function Se(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"'))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function $e(){var t;return r.charCodeAt(e)===40?(t="(",e++):(t=null,d('"("')),t===null&&(r.charCodeAt(e)===41?(t=")",e++):(t=null,d('")"')),t===null&&(r.charCodeAt(e)===60?(t="<",e++):(t=null,d('"<"')),t===null&&(r.charCodeAt(e)===62?(t=">",e++):(t=null,d('">"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===92?(t="\\",e++):(t=null,d('"\\\\"')),t===null&&(t=G(),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===123?(t="{",e++):(t=null,d('"{"')),t===null&&(r.charCodeAt(e)===125?(t="}",e++):(t=null,d('"}"')),t===null&&(t=K(),t===null&&(t=ae())))))))))))))))))),t}function zt(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')),i===null&&(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i===null&&(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i===null&&(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i===null&&(r.charCodeAt(e)===62?(i=">",e++):(i=null,d('">"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===92?(i="\\",e++):(i=null,d('"\\\\"')),i===null&&(i=G(),i===null&&(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i===null&&(r.charCodeAt(e)===91?(i="[",e++):(i=null,d('"["')),i===null&&(r.charCodeAt(e)===93?(i="]",e++):(i=null,d('"]"')),i===null&&(r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i===null&&(r.charCodeAt(e)===123?(i="{",e++):(i=null,d('"{"')),i===null&&(r.charCodeAt(e)===125?(i="}",e++):(i=null,d('"}"'))))))))))))))))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')),i===null&&(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i===null&&(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i===null&&(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i===null&&(r.charCodeAt(e)===62?(i=">",e++):(i=null,d('">"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===92?(i="\\",e++):(i=null,d('"\\\\"')),i===null&&(i=G(),i===null&&(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i===null&&(r.charCodeAt(e)===91?(i="[",e++):(i=null,d('"["')),i===null&&(r.charCodeAt(e)===93?(i="]",e++):(i=null,d('"]"')),i===null&&(r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i===null&&(r.charCodeAt(e)===123?(i="{",e++):(i=null,d('"{"')),i===null&&(r.charCodeAt(e)===125?(i="}",e++):(i=null,d('"}"')))))))))))))))))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function Ae(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return"*"}()),t===null&&(e=h),t}function fe(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return"/"}()),t===null&&(e=h),t}function se(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return"="}()),t===null&&(e=h),t}function st(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return"("}()),t===null&&(e=h),t}function We(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return")"}()),t===null&&(e=h),t}function ht(){var t,i,l,h;return l=e,h=e,r.charCodeAt(e)===62?(t=">",e++):(t=null,d('">"')),t!==null?(i=Q(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f){return">"}()),t===null&&(e=l),t}function It(){var t,i,l,h;return l=e,h=e,t=Q(),t!==null?(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f){return"<"}()),t===null&&(e=l),t}function qe(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return","}()),t===null&&(e=h),t}function Ue(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return";"}()),t===null&&(e=h),t}function wt(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return":"}()),t===null&&(e=h),t}function Yt(){var t,i,l,h;return l=e,h=e,t=Q(),t!==null?(i=G(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f){return'"'}()),t===null&&(e=l),t}function Xe(){var t,i,l,h;return l=e,h=e,t=G(),t!==null?(i=Q(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f){return'"'}()),t===null&&(e=l),t}function Je(){var t,i,l,h;if(h=e,t=st(),t!==null){for(i=[],l=ut(),l===null&&(l=Pe(),l===null&&(l=Je()));l!==null;)i.push(l),l=ut(),l===null&&(l=Pe(),l===null&&(l=Je()));i!==null?(l=We(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)}else t=null,e=h;return t}function ut(){var t;return/^[!-']/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[!-']")),t===null&&(/^[*-[]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[*-[]")),t===null&&(/^[\]-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\]-~]")),t===null&&(t=ue(),t===null&&(t=Ne())))),t}function _t(){var t,i,l,h,f,v;if(f=e,v=e,t=Q(),t!==null)if(i=G(),i!==null){for(l=[],h=Le(),h===null&&(h=Pe());h!==null;)l.push(h),h=Le(),h===null&&(h=Pe());l!==null?(h=G(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I){return r.substring(e,I)}(f)),t===null&&(e=f),t}function mt(){var t,i,l,h,f,v;if(f=e,v=e,t=Q(),t!==null)if(i=G(),i!==null){for(l=[],h=Le(),h===null&&(h=Pe());h!==null;)l.push(h),h=Le(),h===null&&(h=Pe());l!==null?(h=G(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I){var q=r.substring(e,I).trim();return q.substring(1,q.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(f)),t===null&&(e=f),t}function Le(){var t;return t=Ne(),t===null&&(r.charCodeAt(e)===33?(t="!",e++):(t=null,d('"!"')),t===null&&(/^[#-[]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[#-[]")),t===null&&(/^[\]-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\]-~]")),t===null&&(t=ue())))),t}function Pe(){var t,i,l;return l=e,r.charCodeAt(e)===92?(t="\\",e++):(t=null,d('"\\\\"')),t!==null?(/^[\0-\t]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\0-\\t]")),i===null&&(/^[\x0B-\f]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\x0B-\\f]")),i===null&&(/^[\x0E-]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\x0E-]")))),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Ze(){var t,i,l,h,f,v;return f=e,v=e,t=qt(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Wn(),l=l!==null?l:"",l!==null?(h=jr(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t!==null&&(t=function(I){try{M.uri=new ua(M.scheme,M.user,M.host,M.port),delete M.scheme,delete M.user,delete M.host,delete M.host_type,delete M.port}catch{M=-1}}()),t===null&&(e=f),t}function Tt(){var t,i,l,h,f,v,I,q;return I=e,q=e,t=qt(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Wn(),l=l!==null?l:"",l!==null?(h=jr(),h!==null?(f=Vs(),f!==null?(v=Yr(),v=v!==null?v:"",v!==null?t=[t,i,l,h,f,v]:(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q),t!==null&&(t=function(j){try{M.uri=new ua(M.scheme,M.user,M.host,M.port,M.uri_params,M.uri_headers),delete M.scheme,delete M.user,delete M.host,delete M.host_type,delete M.port,delete M.uri_params,a==="SIP_URI"&&(M=M.uri)}catch{M=-1}}()),t===null&&(e=I),t}function qt(){var t;return t=rn(),t===null&&(t=Dt()),t}function rn(){var t,i;return i=e,r.substr(e,4).toLowerCase()==="sips"?(t=r.substr(e,4),e+=4):(t=null,d('"sips"')),t!==null&&(t=function(l,h){M.scheme=h.toLowerCase()}(i,t)),t===null&&(e=i),t}function Dt(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"sip"')),t!==null&&(t=function(l,h){M.scheme=h.toLowerCase()}(i,t)),t===null&&(e=i),t}function Wn(){var t,i,l,h,f,v;return h=e,f=e,t=Pn(),t!==null?(v=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Aa(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?(r.charCodeAt(e)===64?(l="@",e++):(l=null,d('"@"')),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){M.user=decodeURIComponent(r.substring(e-1,I))}(h)),t===null&&(e=h),t}function Pn(){var t,i;if(i=X(),i===null&&(i=be(),i===null&&(i=Bs())),i!==null)for(t=[];i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(i=Bs()));else t=null;return t}function Bs(){var t;return r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"'))))))))),t}function Aa(){var t,i,l;for(l=e,t=[],i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","'))))))));i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","'))))))));return t!==null&&(t=function(h){M.password=r.substring(e,h)}(l)),t===null&&(e=l),t}function jr(){var t,i,l,h,f;return h=e,t=ar(),t!==null?(f=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=gn(),l!==null?i=[i,l]:(i=null,e=f)):(i=null,e=f),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function ar(){var t,i;return i=e,t=_n(),t===null&&(t=or(),t===null&&(t=Wr())),t!==null&&(t=function(l){return M.host=r.substring(e,l).toLowerCase(),M.host}(i)),t===null&&(e=i),t}function _n(){var t,i,l,h,f,v;for(h=e,f=e,t=[],v=e,i=Gr(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v);i!==null;)t.push(i),v=e,i=Gr(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v);return t!==null?(i=yi(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){return M.host_type="domain",r.substring(e,I)}(h)),t===null&&(e=h),t}function Gr(){var t,i,l,h;if(h=e,t=ee(),t!==null){for(i=[],l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));l!==null;)i.push(l),l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function yi(){var t,i,l,h;if(h=e,t=R(),t!==null){for(i=[],l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));l!==null;)i.push(l),l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function Wr(){var t,i,l,h,f;return h=e,f=e,r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t!==null?(i=Kr(),i!==null?(r.charCodeAt(e)===93?(l="]",e++):(l=null,d('"]"')),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return M.host_type="IPv6",r.substring(e,v)}(h)),t===null&&(e=h),t}function Kr(){var t,i,l,h,f,v,I,q,j,Oe,it,an,Pr,ts,z,he;return ts=e,z=e,t=de(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?(r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=de(),j!==null?(r.charCodeAt(e)===58?(Oe=":",e++):(Oe=null,d('":"')),Oe!==null?(it=de(),it!==null?(r.charCodeAt(e)===58?(an=":",e++):(an=null,d('":"')),an!==null?(Pr=Pt(),Pr!==null?t=[t,i,l,h,f,v,I,q,j,Oe,it,an,Pr]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=de(),Oe!==null?(r.charCodeAt(e)===58?(it=":",e++):(it=null,d('":"')),it!==null?(an=Pt(),an!==null?t=[t,i,l,h,f,v,I,q,j,Oe,it,an]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=Pt(),Oe!==null?t=[t,i,l,h,f,v,I,q,j,Oe]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=Pt(),q!==null?t=[t,i,l,h,f,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=Pt(),v!==null?t=[t,i,l,h,f,v]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=Pt(),h!==null?t=[t,i,l,h]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=Pt(),i!==null?t=[t,i]:(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?t=[t,i]:(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(r.substr(e,2)==="::"?(i="::",e+=2):(i=null,d('"::"')),i!==null?(l=de(),l!==null?(r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=de(),j!==null?(r.charCodeAt(e)===58?(Oe=":",e++):(Oe=null,d('":"')),Oe!==null?(it=Pt(),it!==null?t=[t,i,l,h,f,v,I,q,j,Oe,it]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(r.substr(e,2)==="::"?(l="::",e+=2):(l=null,d('"::"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=Pt(),Oe!==null?t=[t,i,l,h,f,v,I,q,j,Oe]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(r.substr(e,2)==="::"?(h="::",e+=2):(h=null,d('"::"')),h!==null?(f=de(),f!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=Pt(),j!==null?t=[t,i,l,h,f,v,I,q,j]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?h=[h,f]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(r.substr(e,2)==="::"?(f="::",e+=2):(f=null,d('"::"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=Pt(),q!==null?t=[t,i,l,h,f,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?h=[h,f]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?f=[f,v]:(f=null,e=he)):(f=null,e=he),f=f!==null?f:"",f!==null?(r.substr(e,2)==="::"?(v="::",e+=2):(v=null,d('"::"')),v!==null?(I=Pt(),I!==null?t=[t,i,l,h,f,v,I]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?h=[h,f]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?f=[f,v]:(f=null,e=he)):(f=null,e=he),f=f!==null?f:"",f!==null?(he=e,r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?v=[v,I]:(v=null,e=he)):(v=null,e=he),v=v!==null?v:"",v!==null?(r.substr(e,2)==="::"?(I="::",e+=2):(I=null,d('"::"')),I!==null?(q=de(),q!==null?t=[t,i,l,h,f,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?h=[h,f]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?f=[f,v]:(f=null,e=he)):(f=null,e=he),f=f!==null?f:"",f!==null?(he=e,r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?v=[v,I]:(v=null,e=he)):(v=null,e=he),v=v!==null?v:"",v!==null?(he=e,r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?I=[I,q]:(I=null,e=he)):(I=null,e=he),I=I!==null?I:"",I!==null?(r.substr(e,2)==="::"?(q="::",e+=2):(q=null,d('"::"')),q!==null?t=[t,i,l,h,f,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z))))))))))))))),t!==null&&(t=function(Oo){return M.host_type="IPv6",r.substring(e,Oo)}(ts)),t===null&&(e=ts),t}function de(){var t,i,l,h,f;return f=e,t=N(),t!==null?(i=N(),i=i!==null?i:"",i!==null?(l=N(),l=l!==null?l:"",l!==null?(h=N(),h=h!==null?h:"",h!==null?t=[t,i,l,h]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t}function Pt(){var t,i,l,h;return h=e,t=de(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(t=or()),t}function or(){var t,i,l,h,f,v,I,q,j;return q=e,j=e,t=lr(),t!==null?(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i!==null?(l=lr(),l!==null?(r.charCodeAt(e)===46?(h=".",e++):(h=null,d('"."')),h!==null?(f=lr(),f!==null?(r.charCodeAt(e)===46?(v=".",e++):(v=null,d('"."')),v!==null?(I=lr(),I!==null?t=[t,i,l,h,f,v,I]:(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j),t!==null&&(t=function(Oe){return M.host_type="IPv4",r.substring(e,Oe)}(q)),t===null&&(e=q),t}function lr(){var t,i,l,h;return h=e,r.substr(e,2)==="25"?(t="25",e+=2):(t=null,d('"25"')),t!==null?(/^[0-5]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[0-5]")),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t===null&&(h=e,r.charCodeAt(e)===50?(t="2",e++):(t=null,d('"2"')),t!==null?(/^[0-4]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[0-4]")),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(h=e,r.charCodeAt(e)===49?(t="1",e++):(t=null,d('"1"')),t!==null?(i=S(),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(h=e,/^[1-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[1-9]")),t!==null?(i=S(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t===null&&(t=S())))),t}function gn(){var t,i,l,h,f,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(f=S(),f=f!==null?f:"",f!==null?t=[t,i,l,h,f]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){return j=parseInt(j.join("")),M.port=j,j}(v,t)),t===null&&(e=v),t}function Vs(){var t,i,l,h;for(t=[],h=e,r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=$r(),l!==null?i=[i,l]:(i=null,e=h)):(i=null,e=h);i!==null;)t.push(i),h=e,r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=$r(),l!==null?i=[i,l]:(i=null,e=h)):(i=null,e=h);return t}function $r(){var t;return t=vi(),t===null&&(t=Ti(),t===null&&(t=js(),t===null&&(t=bi(),t===null&&(t=Gs(),t===null&&(t=wi(),t===null&&(t=Ws())))))),t}function vi(){var t,i,l,h;return l=e,h=e,r.substr(e,10).toLowerCase()==="transport="?(t=r.substr(e,10),e+=10):(t=null,d('"transport="')),t!==null?(r.substr(e,3).toLowerCase()==="udp"?(i=r.substr(e,3),e+=3):(i=null,d('"udp"')),i===null&&(r.substr(e,3).toLowerCase()==="tcp"?(i=r.substr(e,3),e+=3):(i=null,d('"tcp"')),i===null&&(r.substr(e,4).toLowerCase()==="sctp"?(i=r.substr(e,4),e+=4):(i=null,d('"sctp"')),i===null&&(r.substr(e,3).toLowerCase()==="tls"?(i=r.substr(e,3),e+=3):(i=null,d('"tls"')),i===null&&(i=J())))),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.uri_params||(M.uri_params={}),M.uri_params.transport=v.toLowerCase()}(l,t[1])),t===null&&(e=l),t}function Ti(){var t,i,l,h;return l=e,h=e,r.substr(e,5).toLowerCase()==="user="?(t=r.substr(e,5),e+=5):(t=null,d('"user="')),t!==null?(r.substr(e,5).toLowerCase()==="phone"?(i=r.substr(e,5),e+=5):(i=null,d('"phone"')),i===null&&(r.substr(e,2).toLowerCase()==="ip"?(i=r.substr(e,2),e+=2):(i=null,d('"ip"')),i===null&&(i=J())),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.uri_params||(M.uri_params={}),M.uri_params.user=v.toLowerCase()}(l,t[1])),t===null&&(e=l),t}function js(){var t,i,l,h;return l=e,h=e,r.substr(e,7).toLowerCase()==="method="?(t=r.substr(e,7),e+=7):(t=null,d('"method="')),t!==null?(i=kr(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.uri_params||(M.uri_params={}),M.uri_params.method=v}(l,t[1])),t===null&&(e=l),t}function bi(){var t,i,l,h;return l=e,h=e,r.substr(e,4).toLowerCase()==="ttl="?(t=r.substr(e,4),e+=4):(t=null,d('"ttl="')),t!==null?(i=Ss(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.params||(M.params={}),M.params.ttl=v}(l,t[1])),t===null&&(e=l),t}function Gs(){var t,i,l,h;return l=e,h=e,r.substr(e,6).toLowerCase()==="maddr="?(t=r.substr(e,6),e+=6):(t=null,d('"maddr="')),t!==null?(i=ar(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.uri_params||(M.uri_params={}),M.uri_params.maddr=v}(l,t[1])),t===null&&(e=l),t}function wi(){var t,i,l,h,f,v;return h=e,f=e,r.substr(e,2).toLowerCase()==="lr"?(t=r.substr(e,2),e+=2):(t=null,d('"lr"')),t!==null?(v=e,r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=J(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){M.uri_params||(M.uri_params={}),M.uri_params.lr=void 0}()),t===null&&(e=h),t}function Ws(){var t,i,l,h,f,v;return h=e,f=e,t=Si(),t!==null?(v=e,r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Ks(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I,q,j){M.uri_params||(M.uri_params={}),typeof j>"u"?j=void 0:j=j[1],M.uri_params[q.toLowerCase()]=j}(h,t[0],t[1])),t===null&&(e=h),t}function Si(){var t,i,l;if(l=e,i=Qn(),i!==null)for(t=[];i!==null;)t.push(i),i=Qn();else t=null;return t!==null&&(t=function(h,f){return f.join("")}(l,t)),t===null&&(e=l),t}function Ks(){var t,i,l;if(l=e,i=Qn(),i!==null)for(t=[];i!==null;)t.push(i),i=Qn();else t=null;return t!==null&&(t=function(h,f){return f.join("")}(l,t)),t===null&&(e=l),t}function Qn(){var t;return t=ds(),t===null&&(t=X(),t===null&&(t=be())),t}function ds(){var t;return r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')))))))),t}function Yr(){var t,i,l,h,f,v,I;if(v=e,r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t!==null)if(i=mr(),i!==null){for(l=[],I=e,r.charCodeAt(e)===38?(h="&",e++):(h=null,d('"&"')),h!==null?(f=mr(),f!==null?h=[h,f]:(h=null,e=I)):(h=null,e=I);h!==null;)l.push(h),I=e,r.charCodeAt(e)===38?(h="&",e++):(h=null,d('"&"')),h!==null?(f=mr(),f!==null?h=[h,f]:(h=null,e=I)):(h=null,e=I);l!==null?t=[t,i,l]:(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t}function mr(){var t,i,l,h,f;return h=e,f=e,t=Ei(),t!==null?(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Ci(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I,q){I=I.join("").toLowerCase(),q=q.join(""),M.uri_headers||(M.uri_headers={}),M.uri_headers[I]?M.uri_headers[I].push(q):M.uri_headers[I]=[q]}(h,t[0],t[2])),t===null&&(e=h),t}function Ei(){var t,i;if(i=ur(),i===null&&(i=X(),i===null&&(i=be())),i!==null)for(t=[];i!==null;)t.push(i),i=ur(),i===null&&(i=X(),i===null&&(i=be()));else t=null;return t}function Ci(){var t,i;for(t=[],i=ur(),i===null&&(i=X(),i===null&&(i=be()));i!==null;)t.push(i),i=ur(),i===null&&(i=X(),i===null&&(i=be()));return t}function ur(){var t;return r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')))))))),t}function Ia(){var t;return t=Di(),t===null&&(t=$t()),t}function $t(){var t,i,l,h,f,v;return v=e,t=kr(),t!==null?(i=K(),i!==null?(l=gr(),l!==null?(h=K(),h!==null?(f=Or(),f!==null?t=[t,i,l,h,f]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function gr(){var t;return t=Tt(),t===null&&(t=yn()),t}function yn(){var t,i,l,h;return h=e,t=$i(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=hs(),l===null&&(l=Ai()),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function hs(){var t,i,l,h,f;return h=e,t=Et(),t===null&&(t=yr()),t!==null?(f=e,r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i!==null?(l=wr(),l!==null?i=[i,l]:(i=null,e=f)):(i=null,e=f),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function Et(){var t,i,l,h;return h=e,r.substr(e,2)==="//"?(t="//",e+=2):(t=null,d('"//"')),t!==null?(i=Ra(),i!==null?(l=yr(),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function yr(){var t,i,l;return l=e,r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t!==null?(i=Ri(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Ai(){var t,i,l,h;if(h=e,t=Ii(),t!==null){for(i=[],l=vr();l!==null;)i.push(l),l=vr();i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function vr(){var t;return t=De(),t===null&&(t=X(),t===null&&(t=be())),t}function Ii(){var t;return t=X(),t===null&&(t=be(),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')))))))))))),t}function Ri(){var t,i,l,h,f,v;if(f=e,t=xr(),t!==null){for(i=[],v=e,r.charCodeAt(e)===47?(l="/",e++):(l=null,d('"/"')),l!==null?(h=xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===47?(l="/",e++):(l=null,d('"/"')),l!==null?(h=xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function xr(){var t,i,l,h,f,v;for(f=e,t=[],i=cr();i!==null;)t.push(i),i=cr();if(t!==null){for(i=[],v=e,r.charCodeAt(e)===59?(l=";",e++):(l=null,d('";"')),l!==null?(h=Tr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===59?(l=";",e++):(l=null,d('";"')),l!==null?(h=Tr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Tr(){var t,i;for(t=[],i=cr();i!==null;)t.push(i),i=cr();return t}function cr(){var t;return t=X(),t===null&&(t=be(),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')))))))))),t}function $i(){var t,i,l,h,f;if(h=e,f=e,t=R(),t!==null){for(i=[],l=R(),l===null&&(l=S(),l===null&&(r.charCodeAt(e)===43?(l="+",e++):(l=null,d('"+"')),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."'))))));l!==null;)i.push(l),l=R(),l===null&&(l=S(),l===null&&(r.charCodeAt(e)===43?(l="+",e++):(l=null,d('"+"')),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."'))))));i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t!==null&&(t=function(v){M.scheme=r.substring(e,v)}(h)),t===null&&(e=h),t}function Ra(){var t;return t=br(),t===null&&(t=Zn()),t}function br(){var t,i,l,h;return l=e,h=e,t=Wn(),t!==null?(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t=t!==null?t:"",t!==null?(i=jr(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t=t!==null?t:"",t}function Zn(){var t,i;if(i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i===null&&(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"'))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i===null&&(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')))))))))));else t=null;return t}function wr(){var t,i;for(t=[],i=vr();i!==null;)t.push(i),i=vr();return t}function Or(){var t,i,l,h,f,v,I,q;if(I=e,q=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t!==null)if(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i!==null){if(h=S(),h!==null)for(l=[];h!==null;)l.push(h),h=S();else l=null;if(l!==null)if(r.charCodeAt(e)===46?(h=".",e++):(h=null,d('"."')),h!==null){if(v=S(),v!==null)for(f=[];v!==null;)f.push(v),v=S();else f=null;f!==null?t=[t,i,l,h,f]:(t=null,e=q)}else t=null,e=q;else t=null,e=q}else t=null,e=q;else t=null,e=q;return t!==null&&(t=function(j){M.sip_version=r.substring(e,j)}(I)),t===null&&(e=I),t}function ps(){var t;return r.substr(e,6)==="INVITE"?(t="INVITE",e+=6):(t=null,d('"INVITE"')),t}function Ys(){var t;return r.substr(e,3)==="ACK"?(t="ACK",e+=3):(t=null,d('"ACK"')),t}function Xs(){var t;return r.substr(e,7)==="OPTIONS"?(t="OPTIONS",e+=7):(t=null,d('"OPTIONS"')),t}function Js(){var t;return r.substr(e,3)==="BYE"?(t="BYE",e+=3):(t=null,d('"BYE"')),t}function rt(){var t;return r.substr(e,6)==="CANCEL"?(t="CANCEL",e+=6):(t=null,d('"CANCEL"')),t}function Qs(){var t;return r.substr(e,8)==="REGISTER"?(t="REGISTER",e+=8):(t=null,d('"REGISTER"')),t}function xi(){var t;return r.substr(e,9)==="SUBSCRIBE"?(t="SUBSCRIBE",e+=9):(t=null,d('"SUBSCRIBE"')),t}function Oi(){var t;return r.substr(e,6)==="NOTIFY"?(t="NOTIFY",e+=6):(t=null,d('"NOTIFY"')),t}function ki(){var t;return r.substr(e,5)==="REFER"?(t="REFER",e+=5):(t=null,d('"REFER"')),t}function kr(){var t,i;return i=e,t=ps(),t===null&&(t=Ys(),t===null&&(t=Xs(),t===null&&(t=Js(),t===null&&(t=rt(),t===null&&(t=Qs(),t===null&&(t=xi(),t===null&&(t=Oi(),t===null&&(t=ki(),t===null&&(t=J()))))))))),t!==null&&(t=function(l){return M.method=r.substring(e,l),M.method}(i)),t===null&&(e=i),t}function Di(){var t,i,l,h,f,v;return v=e,t=Or(),t!==null?(i=K(),i!==null?(l=Zs(),l!==null?(h=K(),h!==null?(f=vt(),f!==null?t=[t,i,l,h,f]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function Zs(){var t,i;return i=e,t=Ni(),t!==null&&(t=function(l,h){M.status_code=parseInt(h.join(""))}(i,t)),t===null&&(e=i),t}function Ni(){var t,i,l,h;return h=e,t=S(),t!==null?(i=S(),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function vt(){var t,i,l;for(l=e,t=[],i=De(),i===null&&(i=X(),i===null&&(i=be(),i===null&&(i=ue(),i===null&&(i=ye(),i===null&&(i=K(),i===null&&(i=ae()))))));i!==null;)t.push(i),i=De(),i===null&&(i=X(),i===null&&(i=be(),i===null&&(i=ue(),i===null&&(i=ye(),i===null&&(i=K(),i===null&&(i=ae()))))));return t!==null&&(t=function(h){M.reason_phrase=r.substring(e,h)}(l)),t===null&&(e=l),t}function Sr(){var t,i,l,h,f,v;if(f=e,t=er(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=er(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=er(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function lo(){var t,i,l,h,f,v;return h=e,f=e,t=zt(),t!==null?(v=e,r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?(l=zt(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){M=r.substring(e,I)}(h)),t===null&&(e=h),t}function _s(){var t,i,l,h,f,v,I;if(f=e,t=Ae(),t===null)if(v=e,t=ne(),t!==null){for(i=[],I=e,l=qe(),l!==null?(h=ne(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=qe(),l!==null?(h=ne(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j,Oe;for(Oe=M.multi_header.length,j=0;j<Oe;j++)if(M.multi_header[j].parsed===null){M=null;break}M!==null?M=M.multi_header:M=-1}()),t===null&&(e=f),t}function ne(){var t,i,l,h,f,v,I;if(f=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=fs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=fs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j;M.multi_header||(M.multi_header=[]);try{j=new Yn(M.uri,M.display_name,M.params),delete M.uri,delete M.display_name,delete M.params}catch{j=null}M.multi_header.push({possition:e,offset:q,parsed:j})}(f)),t===null&&(e=f),t}function fn(){var t,i,l,h,f;return f=e,t=Dr(),t=t!==null?t:"",t!==null?(i=It(),i!==null?(l=Tt(),l!==null?(h=ht(),h!==null?t=[t,i,l,h]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t}function Dr(){var t,i,l,h,f,v,I;if(f=e,v=e,t=J(),t!==null){for(i=[],I=e,l=Ne(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ne(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t===null&&(t=mt()),t!==null&&(t=function(q,j){typeof j=="string"?M.display_name=j:M.display_name=j[1].reduce(function(Oe,it){return Oe+it[0]+it[1]},j[0])}(f,t)),t===null&&(e=f),t}function fs(){var t;return t=Mi(),t===null&&(t=ct(),t===null&&(t=gt())),t}function Mi(){var t,i,l,h,f;return h=e,f=e,r.substr(e,1).toLowerCase()==="q"?(t=r.substr(e,1),e++):(t=null,d('"q"')),t!==null?(i=se(),i!==null?(l=Ui(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.params||(M.params={}),M.params.q=I}(h,t[2])),t===null&&(e=h),t}function ct(){var t,i,l,h,f;return h=e,f=e,r.substr(e,7).toLowerCase()==="expires"?(t=r.substr(e,7),e+=7):(t=null,d('"expires"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.params||(M.params={}),M.params.expires=I}(h,t[2])),t===null&&(e=h),t}function vn(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,f){return parseInt(f.join(""))}(l,t)),t===null&&(e=l),t}function Ui(){var t,i,l,h,f,v,I,q;return v=e,I=e,r.charCodeAt(e)===48?(t="0",e++):(t=null,d('"0"')),t!==null?(q=e,r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(f=S(),f=f!==null?f:"",f!==null?i=[i,l,h,f]:(i=null,e=q)):(i=null,e=q)):(i=null,e=q)):(i=null,e=q),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(j){return parseFloat(r.substring(e,j))}(v)),t===null&&(e=v),t}function gt(){var t,i,l,h,f,v;return h=e,f=e,t=J(),t!==null?(v=e,i=se(),i!==null?(l=ei(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I,q,j){M.params||(M.params={}),typeof j>"u"?j=void 0:j=j[1],M.params[q.toLowerCase()]=j}(h,t[0],t[1])),t===null&&(e=h),t}function ei(){var t;return t=J(),t===null&&(t=ar(),t===null&&(t=_t())),t}function $a(){var t,i,l,h,f,v;if(f=e,t=Pi(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Pi(){var t;return r.substr(e,6).toLowerCase()==="render"?(t=r.substr(e,6),e+=6):(t=null,d('"render"')),t===null&&(r.substr(e,7).toLowerCase()==="session"?(t=r.substr(e,7),e+=7):(t=null,d('"session"')),t===null&&(r.substr(e,4).toLowerCase()==="icon"?(t=r.substr(e,4),e+=4):(t=null,d('"icon"')),t===null&&(r.substr(e,5).toLowerCase()==="alert"?(t=r.substr(e,5),e+=5):(t=null,d('"alert"')),t===null&&(t=J())))),t}function Xr(){var t;return t=Li(),t===null&&(t=gt()),t}function Li(){var t,i,l,h;return h=e,r.substr(e,8).toLowerCase()==="handling"?(t=r.substr(e,8),e+=8):(t=null,d('"handling"')),t!==null?(i=se(),i!==null?(r.substr(e,8).toLowerCase()==="optional"?(l=r.substr(e,8),e+=8):(l=null,d('"optional"')),l===null&&(r.substr(e,8).toLowerCase()==="required"?(l=r.substr(e,8),e+=8):(l=null,d('"required"')),l===null&&(l=J())),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function xa(){var t,i,l,h,f,v;if(f=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Oa(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,f){M=parseInt(f.join(""))}(l,t)),t===null&&(e=l),t}function ka(){var t,i;return i=e,t=qi(),t!==null&&(t=function(l){M=r.substring(e,l)}(i)),t===null&&(e=i),t}function qi(){var t,i,l,h,f,v,I,q;if(I=e,t=Hi(),t!==null)if(i=fe(),i!==null)if(l=Na(),l!==null){for(h=[],q=e,f=Ue(),f!==null?(v=Qr(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);f!==null;)h.push(f),q=e,f=Ue(),f!==null?(v=Qr(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function Hi(){var t;return t=Da(),t===null&&(t=Jr()),t}function Da(){var t;return r.substr(e,4).toLowerCase()==="text"?(t=r.substr(e,4),e+=4):(t=null,d('"text"')),t===null&&(r.substr(e,5).toLowerCase()==="image"?(t=r.substr(e,5),e+=5):(t=null,d('"image"')),t===null&&(r.substr(e,5).toLowerCase()==="audio"?(t=r.substr(e,5),e+=5):(t=null,d('"audio"')),t===null&&(r.substr(e,5).toLowerCase()==="video"?(t=r.substr(e,5),e+=5):(t=null,d('"video"')),t===null&&(r.substr(e,11).toLowerCase()==="application"?(t=r.substr(e,11),e+=11):(t=null,d('"application"')),t===null&&(t=Nr()))))),t}function Jr(){var t;return r.substr(e,7).toLowerCase()==="message"?(t=r.substr(e,7),e+=7):(t=null,d('"message"')),t===null&&(r.substr(e,9).toLowerCase()==="multipart"?(t=r.substr(e,9),e+=9):(t=null,d('"multipart"')),t===null&&(t=Nr())),t}function Nr(){var t;return t=J(),t===null&&(t=zi()),t}function zi(){var t,i,l;return l=e,r.substr(e,2).toLowerCase()==="x-"?(t=r.substr(e,2),e+=2):(t=null,d('"x-"')),t!==null?(i=J(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Na(){var t;return t=Nr(),t===null&&(t=J()),t}function Qr(){var t,i,l,h;return h=e,t=J(),t!==null?(i=se(),i!==null?(l=ti(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function ti(){var t;return t=J(),t===null&&(t=_t()),t}function Fi(){var t,i,l,h;return h=e,t=ms(),t!==null?(i=Ne(),i!==null?(l=kr(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function ms(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,f){M.value=parseInt(f.join(""))}(l,t)),t===null&&(e=l),t}function uo(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M=h}(i,t)),t===null&&(e=i),t}function co(){var t,i,l,h,f,v,I;if(f=e,v=e,t=er(),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q,j){M.event=j.join("").toLowerCase()}(f,t[0])),t===null&&(e=f),t}function er(){var t,i,l,h,f,v;if(f=e,t=Se(),t!==null){for(i=[],v=e,r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?(h=Se(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?(h=Se(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Ma(){var t,i,l,h,f,v,I;if(f=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j=M.tag;try{M=new Yn(M.uri,M.display_name,M.params),j&&M.setParam("tag",j)}catch{M=-1}}()),t===null&&(e=f),t}function gs(){var t;return t=ys(),t===null&&(t=gt()),t}function ys(){var t,i,l,h,f;return h=e,f=e,r.substr(e,3).toLowerCase()==="tag"?(t=r.substr(e,3),e+=3):(t=null,d('"tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.tag=I}(h,t[2])),t===null&&(e=h),t}function El(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,f){M=parseInt(f.join(""))}(l,t)),t===null&&(e=l),t}function ho(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M=h}(i,t)),t===null&&(e=i),t}function Ct(){var t,i,l,h,f,v,I,q,j,Oe;for(q=e,j=e,t=[],i=Dr();i!==null;)t.push(i),i=Dr();if(t!==null)if(i=It(),i!==null)if(l=Tt(),l!==null)if(h=ht(),h!==null){for(f=[],Oe=e,v=Ue(),v!==null?(I=gt(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);v!==null;)f.push(v),Oe=e,v=Ue(),v!==null?(I=gt(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);f!==null?t=[t,i,l,h,f]:(t=null,e=j)}else t=null,e=j;else t=null,e=j;else t=null,e=j;else t=null,e=j;return t!==null&&(t=function(it){try{M=new Yn(M.uri,M.display_name,M.params)}catch{M=-1}}()),t===null&&(e=q),t}function Ft(){var t;return t=dr(),t}function dr(){var t,i,l,h,f,v,I,q;if(I=e,r.substr(e,6).toLowerCase()==="digest"?(t=r.substr(e,6),e+=6):(t=null,d('"Digest"')),t!==null)if(i=Ne(),i!==null)if(l=Gt(),l!==null){for(h=[],q=e,f=qe(),f!==null?(v=Gt(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);f!==null;)h.push(f),q=e,f=qe(),f!==null?(v=Gt(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t===null&&(t=vs()),t}function vs(){var t,i,l,h,f,v,I,q;if(I=e,t=J(),t!==null)if(i=Ne(),i!==null)if(l=Nt(),l!==null){for(h=[],q=e,f=qe(),f!==null?(v=Nt(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);f!==null;)h.push(f),q=e,f=qe(),f!==null?(v=Nt(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function Nt(){var t,i,l,h;return h=e,t=J(),t!==null?(i=se(),i!==null?(l=J(),l===null&&(l=_t()),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Gt(){var t;return t=Qe(),t===null&&(t=ni(),t===null&&(t=hr(),t===null&&(t=Zr(),t===null&&(t=le(),t===null&&(t=Ge(),t===null&&(t=Bi(),t===null&&(t=Nt()))))))),t}function Qe(){var t,i,l,h;return h=e,r.substr(e,5).toLowerCase()==="realm"?(t=r.substr(e,5),e+=5):(t=null,d('"realm"')),t!==null?(i=se(),i!==null?(l=Ut(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ut(){var t,i;return i=e,t=mt(),t!==null&&(t=function(l,h){M.realm=h}(i,t)),t===null&&(e=i),t}function ni(){var t,i,l,h,f,v,I,q,j;if(q=e,r.substr(e,6).toLowerCase()==="domain"?(t=r.substr(e,6),e+=6):(t=null,d('"domain"')),t!==null)if(i=se(),i!==null)if(l=Yt(),l!==null)if(h=Kn(),h!==null){if(f=[],j=e,I=K(),I!==null)for(v=[];I!==null;)v.push(I),I=K();else v=null;for(v!==null?(I=Kn(),I!==null?v=[v,I]:(v=null,e=j)):(v=null,e=j);v!==null;){if(f.push(v),j=e,I=K(),I!==null)for(v=[];I!==null;)v.push(I),I=K();else v=null;v!==null?(I=Kn(),I!==null?v=[v,I]:(v=null,e=j)):(v=null,e=j)}f!==null?(v=Xe(),v!==null?t=[t,i,l,h,f,v]:(t=null,e=q)):(t=null,e=q)}else t=null,e=q;else t=null,e=q;else t=null,e=q;else t=null,e=q;return t}function Kn(){var t;return t=yn(),t===null&&(t=yr()),t}function hr(){var t,i,l,h;return h=e,r.substr(e,5).toLowerCase()==="nonce"?(t=r.substr(e,5),e+=5):(t=null,d('"nonce"')),t!==null?(i=se(),i!==null?(l=Ke(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ke(){var t,i;return i=e,t=mt(),t!==null&&(t=function(l,h){M.nonce=h}(i,t)),t===null&&(e=i),t}function Zr(){var t,i,l,h,f;return h=e,f=e,r.substr(e,6).toLowerCase()==="opaque"?(t=r.substr(e,6),e+=6):(t=null,d('"opaque"')),t!==null?(i=se(),i!==null?(l=mt(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.opaque=I}(h,t[2])),t===null&&(e=h),t}function le(){var t,i,l,h,f;return h=e,r.substr(e,5).toLowerCase()==="stale"?(t=r.substr(e,5),e+=5):(t=null,d('"stale"')),t!==null?(i=se(),i!==null?(f=e,r.substr(e,4).toLowerCase()==="true"?(l=r.substr(e,4),e+=4):(l=null,d('"true"')),l!==null&&(l=function(v){M.stale=!0}()),l===null&&(e=f),l===null&&(f=e,r.substr(e,5).toLowerCase()==="false"?(l=r.substr(e,5),e+=5):(l=null,d('"false"')),l!==null&&(l=function(v){M.stale=!1}()),l===null&&(e=f)),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ge(){var t,i,l,h,f;return h=e,f=e,r.substr(e,9).toLowerCase()==="algorithm"?(t=r.substr(e,9),e+=9):(t=null,d('"algorithm"')),t!==null?(i=se(),i!==null?(r.substr(e,3).toLowerCase()==="md5"?(l=r.substr(e,3),e+=3):(l=null,d('"MD5"')),l===null&&(r.substr(e,8).toLowerCase()==="md5-sess"?(l=r.substr(e,8),e+=8):(l=null,d('"MD5-sess"')),l===null&&(l=J())),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.algorithm=I.toUpperCase()}(h,t[2])),t===null&&(e=h),t}function Bi(){var t,i,l,h,f,v,I,q,j,Oe;if(q=e,r.substr(e,3).toLowerCase()==="qop"?(t=r.substr(e,3),e+=3):(t=null,d('"qop"')),t!==null)if(i=se(),i!==null)if(l=Yt(),l!==null){if(j=e,h=Er(),h!==null){for(f=[],Oe=e,r.charCodeAt(e)===44?(v=",",e++):(v=null,d('","')),v!==null?(I=Er(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);v!==null;)f.push(v),Oe=e,r.charCodeAt(e)===44?(v=",",e++):(v=null,d('","')),v!==null?(I=Er(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);f!==null?h=[h,f]:(h=null,e=j)}else h=null,e=j;h!==null?(f=Xe(),f!==null?t=[t,i,l,h,f]:(t=null,e=q)):(t=null,e=q)}else t=null,e=q;else t=null,e=q;else t=null,e=q;return t}function Er(){var t,i;return i=e,r.substr(e,8).toLowerCase()==="auth-int"?(t=r.substr(e,8),e+=8):(t=null,d('"auth-int"')),t===null&&(r.substr(e,4).toLowerCase()==="auth"?(t=r.substr(e,4),e+=4):(t=null,d('"auth"')),t===null&&(t=J())),t!==null&&(t=function(l,h){M.qop||(M.qop=[]),M.qop.push(h.toLowerCase())}(i,t)),t===null&&(e=i),t}function po(){var t,i,l,h,f,v;if(f=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function _o(){var t,i,l,h,f,v,I;if(f=e,v=e,t=at(),t!==null){for(i=[],I=e,l=qe(),l!==null?(h=at(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=qe(),l!==null?(h=at(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j,Oe;for(Oe=M.multi_header.length,j=0;j<Oe;j++)if(M.multi_header[j].parsed===null){M=null;break}M!==null?M=M.multi_header:M=-1}()),t===null&&(e=f),t}function at(){var t,i,l,h,f,v,I;if(f=e,v=e,t=fn(),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j;M.multi_header||(M.multi_header=[]);try{j=new Yn(M.uri,M.display_name,M.params),delete M.uri,delete M.display_name,delete M.params}catch{j=null}M.multi_header.push({possition:e,offset:q,parsed:j})}(f)),t===null&&(e=f),t}function fo(){var t,i,l,h,f,v,I;if(f=e,v=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t===null&&(t=J()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=es(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=es(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q,j){if(M.protocol=j.toLowerCase(),M.params||(M.params={}),M.params.text&&M.params.text[0]==='"'){var Oe=M.params.text;M.text=Oe.substring(1,Oe.length-1),delete M.params.text}}(f,t[0])),t===null&&(e=f),t}function es(){var t;return t=Vi(),t===null&&(t=gt()),t}function Vi(){var t,i,l,h,f,v;if(f=e,v=e,r.substr(e,5).toLowerCase()==="cause"?(t=r.substr(e,5),e+=5):(t=null,d('"cause"')),t!==null)if(i=se(),i!==null){if(h=S(),h!==null)for(l=[];h!==null;)l.push(h),h=S();else l=null;l!==null?t=[t,i,l]:(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I,q){M.cause=parseInt(q.join(""))}(f,t[2])),t===null&&(e=f),t}function mo(){var t,i,l,h,f,v;if(f=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function go(){var t,i,l,h,f,v;if(f=e,t=Mr(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=Mr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=Mr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Mr(){var t,i,l,h,f,v;if(f=e,t=fn(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Ln(){var t,i,l,h,f,v;if(f=e,t=ji(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Ts(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Ts(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function ji(){var t,i;return i=e,r.substr(e,6).toLowerCase()==="active"?(t=r.substr(e,6),e+=6):(t=null,d('"active"')),t===null&&(r.substr(e,7).toLowerCase()==="pending"?(t=r.substr(e,7),e+=7):(t=null,d('"pending"')),t===null&&(r.substr(e,10).toLowerCase()==="terminated"?(t=r.substr(e,10),e+=10):(t=null,d('"terminated"')),t===null&&(t=J()))),t!==null&&(t=function(l){M.state=r.substring(e,l)}(i)),t===null&&(e=i),t}function Ts(){var t,i,l,h,f;return h=e,f=e,r.substr(e,6).toLowerCase()==="reason"?(t=r.substr(e,6),e+=6):(t=null,d('"reason"')),t!==null?(i=se(),i!==null?(l=pr(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){typeof I<"u"&&(M.reason=I)}(h,t[2])),t===null&&(e=h),t===null&&(h=e,f=e,r.substr(e,7).toLowerCase()==="expires"?(t=r.substr(e,7),e+=7):(t=null,d('"expires"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){typeof I<"u"&&(M.expires=I)}(h,t[2])),t===null&&(e=h),t===null&&(h=e,f=e,r.substr(e,11).toLowerCase()==="retry_after"?(t=r.substr(e,11),e+=11):(t=null,d('"retry_after"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){typeof I<"u"&&(M.retry_after=I)}(h,t[2])),t===null&&(e=h),t===null&&(t=gt()))),t}function pr(){var t;return r.substr(e,11).toLowerCase()==="deactivated"?(t=r.substr(e,11),e+=11):(t=null,d('"deactivated"')),t===null&&(r.substr(e,9).toLowerCase()==="probation"?(t=r.substr(e,9),e+=9):(t=null,d('"probation"')),t===null&&(r.substr(e,8).toLowerCase()==="rejected"?(t=r.substr(e,8),e+=8):(t=null,d('"rejected"')),t===null&&(r.substr(e,7).toLowerCase()==="timeout"?(t=r.substr(e,7),e+=7):(t=null,d('"timeout"')),t===null&&(r.substr(e,6).toLowerCase()==="giveup"?(t=r.substr(e,6),e+=6):(t=null,d('"giveup"')),t===null&&(r.substr(e,10).toLowerCase()==="noresource"?(t=r.substr(e,10),e+=10):(t=null,d('"noresource"')),t===null&&(r.substr(e,9).toLowerCase()==="invariant"?(t=r.substr(e,9),e+=9):(t=null,d('"invariant"')),t===null&&(t=J()))))))),t}function yo(){var t;return t=me(),t=t!==null?t:"",t}function vo(){var t,i,l,h,f,v;if(f=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t=t!==null?t:"",t}function To(){var t,i,l,h,f,v,I;if(f=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=bs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=bs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j=M.tag;try{M=new Yn(M.uri,M.display_name,M.params),j&&M.setParam("tag",j)}catch{M=-1}}()),t===null&&(e=f),t}function bs(){var t;return t=ys(),t===null&&(t=gt()),t}function bo(){var t,i,l,h,f,v;if(f=e,t=Ur(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=Ur(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=Ur(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Ur(){var t,i,l,h,f,v,I,q;if(I=e,t=Ji(),t!==null)if(i=Ne(),i!==null)if(l=ea(),l!==null){for(h=[],q=e,f=Ue(),f!==null?(v=ws(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);f!==null;)h.push(f),q=e,f=Ue(),f!==null?(v=ws(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function ws(){var t;return t=Gi(),t===null&&(t=Wi(),t===null&&(t=Ki(),t===null&&(t=qn(),t===null&&(t=Yi(),t===null&&(t=gt()))))),t}function Gi(){var t,i,l,h,f;return h=e,f=e,r.substr(e,3).toLowerCase()==="ttl"?(t=r.substr(e,3),e+=3):(t=null,d('"ttl"')),t!==null?(i=se(),i!==null?(l=Ss(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.ttl=I}(h,t[2])),t===null&&(e=h),t}function Wi(){var t,i,l,h,f;return h=e,f=e,r.substr(e,5).toLowerCase()==="maddr"?(t=r.substr(e,5),e+=5):(t=null,d('"maddr"')),t!==null?(i=se(),i!==null?(l=ar(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.maddr=I}(h,t[2])),t===null&&(e=h),t}function Ki(){var t,i,l,h,f;return h=e,f=e,r.substr(e,8).toLowerCase()==="received"?(t=r.substr(e,8),e+=8):(t=null,d('"received"')),t!==null?(i=se(),i!==null?(l=or(),l===null&&(l=Kr()),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.received=I}(h,t[2])),t===null&&(e=h),t}function qn(){var t,i,l,h,f;return h=e,f=e,r.substr(e,6).toLowerCase()==="branch"?(t=r.substr(e,6),e+=6):(t=null,d('"branch"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.branch=I}(h,t[2])),t===null&&(e=h),t}function Yi(){var t,i,l,h,f;return h=e,r.substr(e,5).toLowerCase()==="rport"?(t=r.substr(e,5),e+=5):(t=null,d('"rport"')),t!==null?(f=e,i=se(),i!==null?(l=Xi(),l!==null?i=[i,l]:(i=null,e=f)):(i=null,e=f),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function Xi(){var t,i,l,h,f,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(f=S(),f=f!==null?f:"",f!==null?t=[t,i,l,h,f]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){M.rport=parseInt(j.join(""))}(v,t)),t===null&&(e=v),t}function Ji(){var t,i,l,h,f,v;return v=e,t=Qi(),t!==null?(i=fe(),i!==null?(l=J(),l!==null?(h=fe(),h!==null?(f=Zi(),f!==null?t=[t,i,l,h,f]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function Qi(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t===null&&(t=J()),t!==null&&(t=function(l,h){M.protocol=h}(i,t)),t===null&&(e=i),t}function Zi(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="udp"?(t=r.substr(e,3),e+=3):(t=null,d('"UDP"')),t===null&&(r.substr(e,3).toLowerCase()==="tcp"?(t=r.substr(e,3),e+=3):(t=null,d('"TCP"')),t===null&&(r.substr(e,3).toLowerCase()==="tls"?(t=r.substr(e,3),e+=3):(t=null,d('"TLS"')),t===null&&(r.substr(e,4).toLowerCase()==="sctp"?(t=r.substr(e,4),e+=4):(t=null,d('"SCTP"')),t===null&&(t=J())))),t!==null&&(t=function(l,h){M.transport=h}(i,t)),t===null&&(e=i),t}function ea(){var t,i,l,h,f;return h=e,t=ta(),t!==null?(f=e,i=wt(),i!==null?(l=na(),l!==null?i=[i,l]:(i=null,e=f)):(i=null,e=f),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function ta(){var t,i;return i=e,t=or(),t===null&&(t=Wr(),t===null&&(t=_n())),t!==null&&(t=function(l){M.host=r.substring(e,l)}(i)),t===null&&(e=i),t}function na(){var t,i,l,h,f,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(f=S(),f=f!==null?f:"",f!==null?t=[t,i,l,h,f]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){M.port=parseInt(j.join(""))}(v,t)),t===null&&(e=v),t}function Ss(){var t,i,l,h,f;return h=e,f=e,t=S(),t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){return parseInt(I.join(""))}(h,t)),t===null&&(e=h),t}function wo(){var t;return t=dr(),t}function Cl(){var t,i,l,h,f,v;if(f=e,t=Hn(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Es(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Es(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Hn(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M.expires=h}(i,t)),t===null&&(e=i),t}function Es(){var t;return t=Cs(),t===null&&(t=gt()),t}function Cs(){var t,i,l,h,f;return h=e,f=e,r.substr(e,9).toLowerCase()==="refresher"?(t=r.substr(e,9),e+=9):(t=null,d('"refresher"')),t!==null?(i=se(),i!==null?(r.substr(e,3).toLowerCase()==="uac"?(l=r.substr(e,3),e+=3):(l=null,d('"uac"')),l===null&&(r.substr(e,3).toLowerCase()==="uas"?(l=r.substr(e,3),e+=3):(l=null,d('"uas"'))),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.refresher=I.toLowerCase()}(h,t[2])),t===null&&(e=h),t}function Ua(){var t,i,l,h;return h=e,t=J(),t!==null?(i=ce(),i!==null?(l=zn(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function zn(){var t,i;for(t=[],i=_e(),i===null&&(i=ye(),i===null&&(i=Ne()));i!==null;)t.push(i),i=_e(),i===null&&(i=ye(),i===null&&(i=Ne()));return t}function So(){var t,i;for(t=[],i=W();i!==null;)t.push(i),i=W();return t}function Eo(){var t,i,l;return l=e,r.substr(e,5)==="uuid:"?(t="uuid:",e+=5):(t=null,d('"uuid:"')),t!==null?(i=ra(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function ra(){var t,i,l,h,f,v,I,q,j,Oe,it;return Oe=e,it=e,t=sa(),t!==null?(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i!==null?(l=sn(),l!==null?(r.charCodeAt(e)===45?(h="-",e++):(h=null,d('"-"')),h!==null?(f=sn(),f!==null?(r.charCodeAt(e)===45?(v="-",e++):(v=null,d('"-"')),v!==null?(I=sn(),I!==null?(r.charCodeAt(e)===45?(q="-",e++):(q=null,d('"-"')),q!==null?(j=ia(),j!==null?t=[t,i,l,h,f,v,I,q,j]:(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it),t!==null&&(t=function(an,Pr){M=r.substring(e+5,an)}(Oe,t[0])),t===null&&(e=Oe),t}function sn(){var t,i,l,h,f;return f=e,t=N(),t!==null?(i=N(),i!==null?(l=N(),l!==null?(h=N(),h!==null?t=[t,i,l,h]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t}function sa(){var t,i,l;return l=e,t=sn(),t!==null?(i=sn(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function ia(){var t,i,l,h;return h=e,t=sn(),t!==null?(i=sn(),i!==null?(l=sn(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Co(){var t,i,l,h,f,v,I;if(f=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){try{M=new Yn(M.uri,M.display_name,M.params)}catch{M=-1}}()),t===null&&(e=f),t}function Ao(){var t,i,l,h,f,v;if(f=e,t=aa(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=As(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=As(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function aa(){var t,i,l,h,f,v;return h=e,f=e,t=zt(),t!==null?(v=e,r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?(l=zt(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){M.call_id=r.substring(e,I)}(h)),t===null&&(e=h),t}function As(){var t;return t=Fn(),t===null&&(t=oa(),t===null&&(t=la(),t===null&&(t=gt()))),t}function Fn(){var t,i,l,h,f;return h=e,f=e,r.substr(e,6)==="to-tag"?(t="to-tag",e+=6):(t=null,d('"to-tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.to_tag=I}(h,t[2])),t===null&&(e=h),t}function oa(){var t,i,l,h,f;return h=e,f=e,r.substr(e,8)==="from-tag"?(t="from-tag",e+=8):(t=null,d('"from-tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.from_tag=I}(h,t[2])),t===null&&(e=h),t}function la(){var t,i;return i=e,r.substr(e,10)==="early-only"?(t="early-only",e+=10):(t=null,d('"early-only"')),t!==null&&(t=function(l){M.early_only=!0}()),t===null&&(e=i),t}function Io(t){t.sort();for(var i=null,l=[],h=0;h<t.length;h++)t[h]!==i&&(l.push(t[h]),i=t[h]);return l}function Ro(){for(var t=1,i=1,l=!1,h=0;h<Math.max(e,_);h++){var f=r.charAt(h);f===`
|
|
4
|
+
`?(l||t++,i=1,l=!1):f==="\r"||f==="\u2028"||f==="\u2029"?(t++,i=1,l=!0):(i++,l=!1)}return{line:t,column:i}}var ua=oi(),Yn=cc(),M={},$o=c[a]();if($o===null||e!==r.length){var Is=Math.max(e,_),xo=Is<r.length?r.charAt(Is):null,ri=Ro();return new this.SyntaxError(Io(g),xo,Is,ri.line,ri.column),-1}return M},toSource:function(){return this._source}};return n.SyntaxError=function(r,a,c,e,_){function g(d,A){var S,R;switch(d.length){case 0:S="end of input";break;case 1:S=d[0];break;default:S=d.slice(0,d.length-1).join(", ")+" or "+d[d.length-1]}return R=A?o(A):"end of input","Expected "+S+" but "+R+" found."}this.name="SyntaxError",this.expected=r,this.found=a,this.message=g(r,a),this.offset=c,this.line=e,this.column=_},n.SyntaxError.prototype=Error.prototype,n}()),Yh}var dc,Jh;function oi(){if(Jh)return dc;Jh=1;function o(A,S){var R;if(typeof Symbol>"u"||A[Symbol.iterator]==null){if(Array.isArray(A)||(R=n(A))||S&&A&&typeof A.length=="number"){R&&(A=R);var N=0,H=function(){};return{s:H,n:function(){return N>=A.length?{done:!0}:{done:!1,value:A[N++]}},e:function(ae){throw ae},f:H}}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 W=!0,G=!1,K;return{s:function(){R=A[Symbol.iterator]()},n:function(){var ae=R.next();return W=ae.done,ae},e:function(ae){G=!0,K=ae},f:function(){try{!W&&R.return!=null&&R.return()}finally{if(G)throw K}}}}function n(A,S){if(A){if(typeof A=="string")return r(A,S);var R=Object.prototype.toString.call(A).slice(8,-1);if(R==="Object"&&A.constructor&&(R=A.constructor.name),R==="Map"||R==="Set")return Array.from(A);if(R==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(R))return r(A,S)}}function r(A,S){(S==null||S>A.length)&&(S=A.length);for(var R=0,N=new Array(S);R<S;R++)N[R]=A[R];return N}function a(A,S){if(!(A instanceof S))throw new TypeError("Cannot call a class as a function")}function c(A,S){for(var R=0;R<S.length;R++){var N=S[R];N.enumerable=N.enumerable||!1,N.configurable=!0,"value"in N&&(N.writable=!0),Object.defineProperty(A,N.key,N)}}function e(A,S,R){return S&&c(A.prototype,S),R&&c(A,R),A}var _=dn,g=Bn(),d=ss();return dc=function(){e(A,null,[{key:"parse",value:function(S){if(S=d.parse(S,"SIP_URI"),S!==-1)return S}}]);function A(S,R,N,H){var W=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},G=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{};if(a(this,A),!N)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=S||_.SIP,this._user=R,this._host=N,this._port=H;for(var K in W)Object.prototype.hasOwnProperty.call(W,K)&&this.setParam(K,W[K]);for(var ae in G)Object.prototype.hasOwnProperty.call(G,ae)&&this.setHeader(ae,G[ae])}return e(A,[{key:"setParam",value:function(S,R){S&&(this._parameters[S.toLowerCase()]=typeof R>"u"||R===null?null:R.toString())}},{key:"getParam",value:function(S){if(S)return this._parameters[S.toLowerCase()]}},{key:"hasParam",value:function(S){if(S)return this._parameters.hasOwnProperty(S.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(S){if(S=S.toLowerCase(),this._parameters.hasOwnProperty(S)){var R=this._parameters[S];return delete this._parameters[S],R}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"setHeader",value:function(S,R){this._headers[g.headerize(S)]=Array.isArray(R)?R:[R]}},{key:"getHeader",value:function(S){if(S)return this._headers[g.headerize(S)]}},{key:"hasHeader",value:function(S){if(S)return this._headers.hasOwnProperty(g.headerize(S))&&!0||!1}},{key:"deleteHeader",value:function(S){if(S=g.headerize(S),this._headers.hasOwnProperty(S)){var R=this._headers[S];return delete this._headers[S],R}}},{key:"clearHeaders",value:function(){this._headers={}}},{key:"clone",value:function(){return new A(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 S=[],R="".concat(this._scheme,":");this._user&&(R+="".concat(g.escapeUser(this._user),"@")),R+=this._host,(this._port||this._port===0)&&(R+=":".concat(this._port));for(var N in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,N)&&(R+=";".concat(N),this._parameters[N]!==null&&(R+="=".concat(this._parameters[N])));for(var H in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,H)){var W=o(this._headers[H]),G;try{for(W.s();!(G=W.n()).done;){var K=G.value;S.push("".concat(H,"=").concat(K))}}catch(ae){W.e(ae)}finally{W.f()}}return S.length>0&&(R+="?".concat(S.join("&"))),R}},{key:"toAor",value:function(S){var R="".concat(this._scheme,":");return this._user&&(R+="".concat(g.escapeUser(this._user),"@")),R+=this._host,S&&(this._port||this._port===0)&&(R+=":".concat(this._port)),R}},{key:"scheme",get:function(){return this._scheme},set:function(S){this._scheme=S.toLowerCase()}},{key:"user",get:function(){return this._user},set:function(S){this._user=S}},{key:"host",get:function(){return this._host},set:function(S){this._host=S.toLowerCase()}},{key:"port",get:function(){return this._port},set:function(S){this._port=S===0?S:parseInt(S,10)||null}}]),A}(),dc}var Qh;function Bn(){if(Qh)return on;Qh=1;function o(S){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?o=function(R){return typeof R}:o=function(R){return R&&typeof Symbol=="function"&&R.constructor===Symbol&&R!==Symbol.prototype?"symbol":typeof R},o(S)}function n(S,R){var N;if(typeof Symbol>"u"||S[Symbol.iterator]==null){if(Array.isArray(S)||(N=r(S))||R&&S&&typeof S.length=="number"){N&&(S=N);var H=0,W=function(){};return{s:W,n:function(){return H>=S.length?{done:!0}:{done:!1,value:S[H++]}},e:function(ee){throw ee},f:W}}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 G=!0,K=!1,ae;return{s:function(){N=S[Symbol.iterator]()},n:function(){var ee=N.next();return G=ee.done,ee},e:function(ee){K=!0,ae=ee},f:function(){try{!G&&N.return!=null&&N.return()}finally{if(K)throw ae}}}}function r(S,R){if(S){if(typeof S=="string")return a(S,R);var N=Object.prototype.toString.call(S).slice(8,-1);if(N==="Object"&&S.constructor&&(N=S.constructor.name),N==="Map"||N==="Set")return Array.from(S);if(N==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(N))return a(S,R)}}function a(S,R){(R==null||R>S.length)&&(R=S.length);for(var N=0,H=new Array(R);N<R;N++)H[N]=S[N];return H}var c=dn,e=oi(),_=ss();on.str_utf8_length=function(S){return unescape(encodeURIComponent(S)).length};var g=on.isFunction=function(S){return S!==void 0?Object.prototype.toString.call(S)==="[object Function]":!1};on.isString=function(S){return S!==void 0?Object.prototype.toString.call(S)==="[object String]":!1},on.isDecimal=function(S){return!isNaN(S)&&parseFloat(S)===parseInt(S,10)},on.isEmpty=function(S){return S===null||S===""||S===void 0||Array.isArray(S)&&S.length===0||typeof S=="number"&&isNaN(S)},on.hasMethods=function(S){for(var R=arguments.length,N=new Array(R>1?R-1:0),H=1;H<R;H++)N[H-1]=arguments[H];for(var W=0,G=N;W<G.length;W++){var K=G[W];if(g(S[K]))return!1}return!0};var d=on.createRandomToken=function(S){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:32,N,H,W="";for(N=0;N<S;N++)H=Math.random()*R|0,W+=H.toString(R);return W};on.newTag=function(){return d(10)},on.newUUID=function(){var S="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(R){var N=Math.random()*16|0,H=R==="x"?N:N&3|8;return H.toString(16)});return S},on.hostType=function(S){if(S){if(S=_.parse(S,"host"),S!==-1)return S.host_type}else return};var A=on.escapeUser=function(S){return encodeURIComponent(decodeURIComponent(S)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/")};return on.normalizeTarget=function(S,R){if(S){if(S instanceof e)return S;if(typeof S=="string"){var N=S.split("@"),H,W;switch(N.length){case 1:if(!R)return;H=S,W=R;break;case 2:H=N[0],W=N[1];break;default:H=N.slice(0,N.length-1).join("@"),W=N[N.length-1]}H=H.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(H)&&(H=H.replace(/[-.()]/g,"")),S="".concat(c.SIP,":").concat(A(H),"@").concat(W);var G;return(G=e.parse(S))?G:void 0}else return}else return},on.headerize=function(S){var R={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},N=S.toLowerCase().replace(/_/g,"-").split("-"),H="",W=N.length,G;for(G=0;G<W;G++)G!==0&&(H+="-"),H+=N[G].charAt(0).toUpperCase()+N[G].substring(1);return R[H]&&(H=R[H]),H},on.sipErrorCause=function(S){for(var R in c.SIP_ERROR_CAUSES)if(c.SIP_ERROR_CAUSES[R].indexOf(S)!==-1)return c.causes[R];return c.causes.SIP_FAILURE_CODE},on.getRandomTestNetIP=function(){function S(R,N){return Math.floor(Math.random()*(N-R+1)+R)}return"192.0.2.".concat(S(1,254))},on.calculateMD5=function(S){function R(Le,Pe){return Le<<Pe|Le>>>32-Pe}function N(Le,Pe){var Ze=Le&2147483648,Tt=Pe&2147483648,qt=Le&1073741824,rn=Pe&1073741824,Dt=(Le&1073741823)+(Pe&1073741823);return qt&rn?Dt^2147483648^Ze^Tt:qt|rn?Dt&1073741824?Dt^3221225472^Ze^Tt:Dt^1073741824^Ze^Tt:Dt^Ze^Tt}function H(Le,Pe,Ze){return Le&Pe|~Le&Ze}function W(Le,Pe,Ze){return Le&Ze|Pe&~Ze}function G(Le,Pe,Ze){return Le^Pe^Ze}function K(Le,Pe,Ze){return Pe^(Le|~Ze)}function ae(Le,Pe,Ze,Tt,qt,rn,Dt){return Le=N(Le,N(N(H(Pe,Ze,Tt),qt),Dt)),N(R(Le,rn),Pe)}function ee(Le,Pe,Ze,Tt,qt,rn,Dt){return Le=N(Le,N(N(W(Pe,Ze,Tt),qt),Dt)),N(R(Le,rn),Pe)}function De(Le,Pe,Ze,Tt,qt,rn,Dt){return Le=N(Le,N(N(G(Pe,Ze,Tt),qt),Dt)),N(R(Le,rn),Pe)}function X(Le,Pe,Ze,Tt,qt,rn,Dt){return Le=N(Le,N(N(K(Pe,Ze,Tt),qt),Dt)),N(R(Le,rn),Pe)}function re(Le){for(var Pe,Ze=Le.length,Tt=Ze+8,qt=(Tt-Tt%64)/64,rn=(qt+1)*16,Dt=new Array(rn-1),Wn=0,Pn=0;Pn<Ze;)Pe=(Pn-Pn%4)/4,Wn=Pn%4*8,Dt[Pe]=Dt[Pe]|Le.charCodeAt(Pn)<<Wn,Pn++;return Pe=(Pn-Pn%4)/4,Wn=Pn%4*8,Dt[Pe]=Dt[Pe]|128<<Wn,Dt[rn-2]=Ze<<3,Dt[rn-1]=Ze>>>29,Dt}function be(Le){var Pe="",Ze="",Tt,qt;for(qt=0;qt<=3;qt++)Tt=Le>>>qt*8&255,Ze="0".concat(Tt.toString(16)),Pe=Pe+Ze.substr(Ze.length-2,2);return Pe}function Ne(Le){for(var Pe="",Ze=0;Ze<Le.length;Ze++){var Tt=Le.charCodeAt(Ze);Tt<128?Pe+=String.fromCharCode(Tt):Tt>127&&Tt<2048?(Pe+=String.fromCharCode(Tt>>6|192),Pe+=String.fromCharCode(Tt&63|128)):(Pe+=String.fromCharCode(Tt>>12|224),Pe+=String.fromCharCode(Tt>>6&63|128),Pe+=String.fromCharCode(Tt&63|128))}return Pe}var Q=[],ce,me,_e,ue,ye,Re,J,Se,$e,zt=7,Ae=12,fe=17,se=22,st=5,We=9,ht=14,It=20,qe=4,Ue=11,wt=16,Yt=23,Xe=6,Je=10,ut=15,_t=21;for(S=Ne(S),Q=re(S),Re=1732584193,J=4023233417,Se=2562383102,$e=271733878,ce=0;ce<Q.length;ce+=16)me=Re,_e=J,ue=Se,ye=$e,Re=ae(Re,J,Se,$e,Q[ce+0],zt,3614090360),$e=ae($e,Re,J,Se,Q[ce+1],Ae,3905402710),Se=ae(Se,$e,Re,J,Q[ce+2],fe,606105819),J=ae(J,Se,$e,Re,Q[ce+3],se,3250441966),Re=ae(Re,J,Se,$e,Q[ce+4],zt,4118548399),$e=ae($e,Re,J,Se,Q[ce+5],Ae,1200080426),Se=ae(Se,$e,Re,J,Q[ce+6],fe,2821735955),J=ae(J,Se,$e,Re,Q[ce+7],se,4249261313),Re=ae(Re,J,Se,$e,Q[ce+8],zt,1770035416),$e=ae($e,Re,J,Se,Q[ce+9],Ae,2336552879),Se=ae(Se,$e,Re,J,Q[ce+10],fe,4294925233),J=ae(J,Se,$e,Re,Q[ce+11],se,2304563134),Re=ae(Re,J,Se,$e,Q[ce+12],zt,1804603682),$e=ae($e,Re,J,Se,Q[ce+13],Ae,4254626195),Se=ae(Se,$e,Re,J,Q[ce+14],fe,2792965006),J=ae(J,Se,$e,Re,Q[ce+15],se,1236535329),Re=ee(Re,J,Se,$e,Q[ce+1],st,4129170786),$e=ee($e,Re,J,Se,Q[ce+6],We,3225465664),Se=ee(Se,$e,Re,J,Q[ce+11],ht,643717713),J=ee(J,Se,$e,Re,Q[ce+0],It,3921069994),Re=ee(Re,J,Se,$e,Q[ce+5],st,3593408605),$e=ee($e,Re,J,Se,Q[ce+10],We,38016083),Se=ee(Se,$e,Re,J,Q[ce+15],ht,3634488961),J=ee(J,Se,$e,Re,Q[ce+4],It,3889429448),Re=ee(Re,J,Se,$e,Q[ce+9],st,568446438),$e=ee($e,Re,J,Se,Q[ce+14],We,3275163606),Se=ee(Se,$e,Re,J,Q[ce+3],ht,4107603335),J=ee(J,Se,$e,Re,Q[ce+8],It,1163531501),Re=ee(Re,J,Se,$e,Q[ce+13],st,2850285829),$e=ee($e,Re,J,Se,Q[ce+2],We,4243563512),Se=ee(Se,$e,Re,J,Q[ce+7],ht,1735328473),J=ee(J,Se,$e,Re,Q[ce+12],It,2368359562),Re=De(Re,J,Se,$e,Q[ce+5],qe,4294588738),$e=De($e,Re,J,Se,Q[ce+8],Ue,2272392833),Se=De(Se,$e,Re,J,Q[ce+11],wt,1839030562),J=De(J,Se,$e,Re,Q[ce+14],Yt,4259657740),Re=De(Re,J,Se,$e,Q[ce+1],qe,2763975236),$e=De($e,Re,J,Se,Q[ce+4],Ue,1272893353),Se=De(Se,$e,Re,J,Q[ce+7],wt,4139469664),J=De(J,Se,$e,Re,Q[ce+10],Yt,3200236656),Re=De(Re,J,Se,$e,Q[ce+13],qe,681279174),$e=De($e,Re,J,Se,Q[ce+0],Ue,3936430074),Se=De(Se,$e,Re,J,Q[ce+3],wt,3572445317),J=De(J,Se,$e,Re,Q[ce+6],Yt,76029189),Re=De(Re,J,Se,$e,Q[ce+9],qe,3654602809),$e=De($e,Re,J,Se,Q[ce+12],Ue,3873151461),Se=De(Se,$e,Re,J,Q[ce+15],wt,530742520),J=De(J,Se,$e,Re,Q[ce+2],Yt,3299628645),Re=X(Re,J,Se,$e,Q[ce+0],Xe,4096336452),$e=X($e,Re,J,Se,Q[ce+7],Je,1126891415),Se=X(Se,$e,Re,J,Q[ce+14],ut,2878612391),J=X(J,Se,$e,Re,Q[ce+5],_t,4237533241),Re=X(Re,J,Se,$e,Q[ce+12],Xe,1700485571),$e=X($e,Re,J,Se,Q[ce+3],Je,2399980690),Se=X(Se,$e,Re,J,Q[ce+10],ut,4293915773),J=X(J,Se,$e,Re,Q[ce+1],_t,2240044497),Re=X(Re,J,Se,$e,Q[ce+8],Xe,1873313359),$e=X($e,Re,J,Se,Q[ce+15],Je,4264355552),Se=X(Se,$e,Re,J,Q[ce+6],ut,2734768916),J=X(J,Se,$e,Re,Q[ce+13],_t,1309151649),Re=X(Re,J,Se,$e,Q[ce+4],Xe,4149444226),$e=X($e,Re,J,Se,Q[ce+11],Je,3174756917),Se=X(Se,$e,Re,J,Q[ce+2],ut,718787259),J=X(J,Se,$e,Re,Q[ce+9],_t,3951481745),Re=N(Re,me),J=N(J,_e),Se=N(Se,ue),$e=N($e,ye);var mt=be(Re)+be(J)+be(Se)+be($e);return mt.toLowerCase()},on.closeMediaStream=function(S){if(S)try{var R;if(S.getTracks){R=S.getTracks();var N=n(R),H;try{for(N.s();!(H=N.n()).done;){var W=H.value;W.stop()}}catch(re){N.e(re)}finally{N.f()}}else{R=S.getAudioTracks();var G=n(R),K;try{for(G.s();!(K=G.n()).done;){var ae=K.value;ae.stop()}}catch(re){G.e(re)}finally{G.f()}R=S.getVideoTracks();var ee=n(R),De;try{for(ee.s();!(De=ee.n()).done;){var X=De.value;X.stop()}}catch(re){ee.e(re)}finally{ee.f()}}}catch{(typeof S.stop=="function"||o(S.stop)==="object")&&S.stop()}},on.cloneArray=function(S){return S&&S.slice()||[]},on.cloneObject=function(S){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return S&&Object.assign({},S)||R},on}var hc={exports:{}},Ga=typeof Reflect=="object"?Reflect:null,Zh=Ga&&typeof Ga.apply=="function"?Ga.apply:function(o,n,r){return Function.prototype.apply.call(o,n,r)},Bl;Ga&&typeof Ga.ownKeys=="function"?Bl=Ga.ownKeys:Object.getOwnPropertySymbols?Bl=function(o){return Object.getOwnPropertyNames(o).concat(Object.getOwnPropertySymbols(o))}:Bl=function(o){return Object.getOwnPropertyNames(o)};function Gb(o){console&&console.warn&&console.warn(o)}var ep=Number.isNaN||function(o){return o!==o};function Lt(){Lt.init.call(this)}hc.exports=Lt,hc.exports.once=Xb,Lt.EventEmitter=Lt,Lt.prototype._events=void 0,Lt.prototype._eventsCount=0,Lt.prototype._maxListeners=void 0;var tp=10;function Vl(o){if(typeof o!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof o)}Object.defineProperty(Lt,"defaultMaxListeners",{enumerable:!0,get:function(){return tp},set:function(o){if(typeof o!="number"||o<0||ep(o))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+o+".");tp=o}}),Lt.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},Lt.prototype.setMaxListeners=function(o){if(typeof o!="number"||o<0||ep(o))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+o+".");return this._maxListeners=o,this};function np(o){return o._maxListeners===void 0?Lt.defaultMaxListeners:o._maxListeners}Lt.prototype.getMaxListeners=function(){return np(this)},Lt.prototype.emit=function(o){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var a=o==="error",c=this._events;if(c!==void 0)a=a&&c.error===void 0;else if(!a)return!1;if(a){var e;if(n.length>0&&(e=n[0]),e instanceof Error)throw e;var _=new Error("Unhandled error."+(e?" ("+e.message+")":""));throw _.context=e,_}var g=c[o];if(g===void 0)return!1;if(typeof g=="function")Zh(g,this,n);else for(var d=g.length,A=op(g,d),r=0;r<d;++r)Zh(A[r],this,n);return!0};function rp(o,n,r,a){var c,e,_;if(Vl(r),e=o._events,e===void 0?(e=o._events=Object.create(null),o._eventsCount=0):(e.newListener!==void 0&&(o.emit("newListener",n,r.listener?r.listener:r),e=o._events),_=e[n]),_===void 0)_=e[n]=r,++o._eventsCount;else if(typeof _=="function"?_=e[n]=a?[r,_]:[_,r]:a?_.unshift(r):_.push(r),c=np(o),c>0&&_.length>c&&!_.warned){_.warned=!0;var g=new Error("Possible EventEmitter memory leak detected. "+_.length+" "+String(n)+" listeners added. Use emitter.setMaxListeners() to increase limit");g.name="MaxListenersExceededWarning",g.emitter=o,g.type=n,g.count=_.length,Gb(g)}return o}Lt.prototype.addListener=function(o,n){return rp(this,o,n,!1)},Lt.prototype.on=Lt.prototype.addListener,Lt.prototype.prependListener=function(o,n){return rp(this,o,n,!0)};function Wb(){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 sp(o,n,r){var a={fired:!1,wrapFn:void 0,target:o,type:n,listener:r},c=Wb.bind(a);return c.listener=r,a.wrapFn=c,c}Lt.prototype.once=function(o,n){return Vl(n),this.on(o,sp(this,o,n)),this},Lt.prototype.prependOnceListener=function(o,n){return Vl(n),this.prependListener(o,sp(this,o,n)),this},Lt.prototype.removeListener=function(o,n){var r,a,c,e,_;if(Vl(n),a=this._events,a===void 0)return this;if(r=a[o],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete a[o],a.removeListener&&this.emit("removeListener",o,r.listener||n));else if(typeof r!="function"){for(c=-1,e=r.length-1;e>=0;e--)if(r[e]===n||r[e].listener===n){_=r[e].listener,c=e;break}if(c<0)return this;c===0?r.shift():Kb(r,c),r.length===1&&(a[o]=r[0]),a.removeListener!==void 0&&this.emit("removeListener",o,_||n)}return this},Lt.prototype.off=Lt.prototype.removeListener,Lt.prototype.removeAllListeners=function(o){var n,r,a;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[o]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[o]),this;if(arguments.length===0){var c=Object.keys(r),e;for(a=0;a<c.length;++a)e=c[a],e!=="removeListener"&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[o],typeof n=="function")this.removeListener(o,n);else if(n!==void 0)for(a=n.length-1;a>=0;a--)this.removeListener(o,n[a]);return this};function ip(o,n,r){var a=o._events;if(a===void 0)return[];var c=a[n];return c===void 0?[]:typeof c=="function"?r?[c.listener||c]:[c]:r?Yb(c):op(c,c.length)}Lt.prototype.listeners=function(o){return ip(this,o,!0)},Lt.prototype.rawListeners=function(o){return ip(this,o,!1)},Lt.listenerCount=function(o,n){return typeof o.listenerCount=="function"?o.listenerCount(n):ap.call(o,n)},Lt.prototype.listenerCount=ap;function ap(o){var n=this._events;if(n!==void 0){var r=n[o];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Lt.prototype.eventNames=function(){return this._eventsCount>0?Bl(this._events):[]};function op(o,n){for(var r=new Array(n),a=0;a<n;++a)r[a]=o[a];return r}function Kb(o,n){for(;n+1<o.length;n++)o[n]=o[n+1];o.pop()}function Yb(o){for(var n=new Array(o.length),r=0;r<n.length;++r)n[r]=o[r].listener||o[r];return n}function Xb(o,n){return new Promise(function(r,a){function c(_){o.removeListener(n,e),a(_)}function e(){typeof o.removeListener=="function"&&o.removeListener("error",c),r([].slice.call(arguments))}lp(o,n,e,{once:!0}),n!=="error"&&Jb(o,c,{once:!0})})}function Jb(o,n,r){typeof o.on=="function"&&lp(o,"error",n,r)}function lp(o,n,r,a){if(typeof o.on=="function")a.once?o.once(n,r):o.on(n,r);else if(typeof o.addEventListener=="function")o.addEventListener(n,function c(e){a.once&&o.removeEventListener(n,c),r(e)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof o)}var Tn=hc.exports,pc={exports:{}},_c,up;function Qb(){if(up)return _c;up=1;var o=1e3,n=o*60,r=n*60,a=r*24,c=a*7,e=a*365.25;_c=function(S,R){R=R||{};var N=typeof S;if(N==="string"&&S.length>0)return _(S);if(N==="number"&&isFinite(S))return R.long?d(S):g(S);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(S))};function _(S){if(S=String(S),!(S.length>100)){var R=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(S);if(R){var N=parseFloat(R[1]),H=(R[2]||"ms").toLowerCase();switch(H){case"years":case"year":case"yrs":case"yr":case"y":return N*e;case"weeks":case"week":case"w":return N*c;case"days":case"day":case"d":return N*a;case"hours":case"hour":case"hrs":case"hr":case"h":return N*r;case"minutes":case"minute":case"mins":case"min":case"m":return N*n;case"seconds":case"second":case"secs":case"sec":case"s":return N*o;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return N;default:return}}}}function g(S){var R=Math.abs(S);return R>=a?Math.round(S/a)+"d":R>=r?Math.round(S/r)+"h":R>=n?Math.round(S/n)+"m":R>=o?Math.round(S/o)+"s":S+"ms"}function d(S){var R=Math.abs(S);return R>=a?A(S,R,a,"day"):R>=r?A(S,R,r,"hour"):R>=n?A(S,R,n,"minute"):R>=o?A(S,R,o,"second"):S+" ms"}function A(S,R,N,H){var W=R>=N*1.5;return Math.round(S/N)+" "+H+(W?"s":"")}return _c}function Zb(o){r.debug=r,r.default=r,r.coerce=d,r.disable=e,r.enable=c,r.enabled=_,r.humanize=Qb(),r.destroy=A,Object.keys(o).forEach(S=>{r[S]=o[S]}),r.names=[],r.skips=[],r.formatters={};function n(S){let R=0;for(let N=0;N<S.length;N++)R=(R<<5)-R+S.charCodeAt(N),R|=0;return r.colors[Math.abs(R)%r.colors.length]}r.selectColor=n;function r(S){let R,N=null,H,W;function G(...K){if(!G.enabled)return;const ae=G,ee=Number(new Date),De=ee-(R||ee);ae.diff=De,ae.prev=R,ae.curr=ee,R=ee,K[0]=r.coerce(K[0]),typeof K[0]!="string"&&K.unshift("%O");let X=0;K[0]=K[0].replace(/%([a-zA-Z%])/g,(re,be)=>{if(re==="%%")return"%";X++;const Ne=r.formatters[be];if(typeof Ne=="function"){const Q=K[X];re=Ne.call(ae,Q),K.splice(X,1),X--}return re}),r.formatArgs.call(ae,K),(ae.log||r.log).apply(ae,K)}return G.namespace=S,G.useColors=r.useColors(),G.color=r.selectColor(S),G.extend=a,G.destroy=r.destroy,Object.defineProperty(G,"enabled",{enumerable:!0,configurable:!1,get:()=>N!==null?N:(H!==r.namespaces&&(H=r.namespaces,W=r.enabled(S)),W),set:K=>{N=K}}),typeof r.init=="function"&&r.init(G),G}function a(S,R){const N=r(this.namespace+(typeof R>"u"?":":R)+S);return N.log=this.log,N}function c(S){r.save(S),r.namespaces=S,r.names=[],r.skips=[];let R;const N=(typeof S=="string"?S:"").split(/[\s,]+/),H=N.length;for(R=0;R<H;R++)N[R]&&(S=N[R].replace(/\*/g,".*?"),S[0]==="-"?r.skips.push(new RegExp("^"+S.slice(1)+"$")):r.names.push(new RegExp("^"+S+"$")))}function e(){const S=[...r.names.map(g),...r.skips.map(g).map(R=>"-"+R)].join(",");return r.enable(""),S}function _(S){if(S[S.length-1]==="*")return!0;let R,N;for(R=0,N=r.skips.length;R<N;R++)if(r.skips[R].test(S))return!1;for(R=0,N=r.names.length;R<N;R++)if(r.names[R].test(S))return!0;return!1}function g(S){return S.toString().substring(2,S.toString().length-2).replace(/\.\*\?$/,"*")}function d(S){return S instanceof Error?S.stack||S.message:S}function A(){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 r.enable(r.load()),r}var e0=Zb;(function(o,n){n.formatArgs=a,n.save=c,n.load=e,n.useColors=r,n.storage=_(),n.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`."))}})(),n.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 r(){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 a(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+o.exports.humanize(this.diff),!this.useColors)return;const A="color: "+this.color;d.splice(1,0,A,"color: inherit");let S=0,R=0;d[0].replace(/%[a-zA-Z%]/g,N=>{N!=="%%"&&(S++,N==="%c"&&(R=S))}),d.splice(R,0,A)}n.log=console.debug||console.log||(()=>{});function c(d){try{d?n.storage.setItem("debug",d):n.storage.removeItem("debug")}catch{}}function e(){let d;try{d=n.storage.getItem("debug")}catch{}return!d&&typeof process<"u"&&"env"in process&&(d=process.env.DEBUG),d}function _(){try{return localStorage}catch{}}o.exports=e0(n);const{formatters:g}=o.exports;g.j=function(d){try{return JSON.stringify(d)}catch(A){return"[UnexpectedJSONParseError]: "+A.message}}})(pc,pc.exports);var Wa=pc.exports;function t0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function cp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function n0(o,n,r){return n&&cp(o.prototype,n),r&&cp(o,r),o}var Ka=Wa,Ya="JsSIP",bn=function(){function o(n){t0(this,o),n?(this._debug=Ka.default("".concat(Ya,":").concat(n)),this._warn=Ka.default("".concat(Ya,":WARN:").concat(n)),this._error=Ka.default("".concat(Ya,":ERROR:").concat(n))):(this._debug=Ka.default(Ya),this._warn=Ka.default("".concat(Ya,":WARN")),this._error=Ka.default("".concat(Ya,":ERROR"))),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}return n0(o,[{key:"debug",get:function(){return this._debug}},{key:"warn",get:function(){return this._warn}},{key:"error",get:function(){return this._error}}]),o}(),nr={},dp={},hp={exports:{}},pp=hp.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(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.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(o){return o.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(o){return o.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(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.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(o){var n="candidate:%s %d %s %d %s %d typ %s";return n+=o.raddr!=null?" raddr %s rport %d":"%v%v",n+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(n+=" generation %d"),n+=o["network-id"]!=null?" network-id %d":"%v",n+=o["network-cost"]!=null?" network-cost %d":"%v",n}},{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(o){var n="ssrc:%d";return o.attribute!=null&&(n+=" %s",o.value!=null&&(n+=":%s")),n}},{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(o){return o.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(o){return o.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(o){return"imageattr:%s %s %s"+(o.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(o){return"simulcast:%s %s"+(o.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(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var n="mediaclk:";return n+=o.id!=null?"id=%s %s":"%v%s",n+=o.mediaClockValue!=null?"=%s":"",n+=o.rateNumerator!=null?" rate=%s":"",n+=o.rateDenominator!=null?"/%s":"",n}},{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(pp).forEach(function(o){var n=pp[o];n.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})});var _p=hp.exports;(function(o){var n=function(g){return String(Number(g))===g?Number(g):g},r=function(g,d,A,S){if(S&&!A)d[S]=n(g[1]);else for(var R=0;R<A.length;R+=1)g[R+1]!=null&&(d[A[R]]=n(g[R+1]))},a=function(g,d,A){var S=g.name&&g.names;g.push&&!d[g.push]?d[g.push]=[]:S&&!d[g.name]&&(d[g.name]={});var R=g.push?{}:S?d[g.name]:d;r(A.match(g.reg),R,g.names,g.name),g.push&&d[g.push].push(R)},c=_p,e=RegExp.prototype.test.bind(/^([a-z])=(.*)/);o.parse=function(g){var d={},A=[],S=d;return g.split(/(\r\n|\r|\n)/).filter(e).forEach(function(R){var N=R[0],H=R.slice(2);N==="m"&&(A.push({rtp:[],fmtp:[]}),S=A[A.length-1]);for(var W=0;W<(c[N]||[]).length;W+=1){var G=c[N][W];if(G.reg.test(H))return a(G,S,H)}}),d.media=A,d};var _=function(g,d){var A=d.split(/=(.+)/,2);return A.length===2?g[A[0]]=n(A[1]):A.length===1&&d.length>1&&(g[A[0]]=void 0),g};o.parseParams=function(g){return g.split(/;\s?/).reduce(_,{})},o.parseFmtpConfig=o.parseParams,o.parsePayloads=function(g){return g.toString().split(" ").map(Number)},o.parseRemoteCandidates=function(g){for(var d=[],A=g.split(" ").map(n),S=0;S<A.length;S+=3)d.push({component:A[S],ip:A[S+1],port:A[S+2]});return d},o.parseImageAttributes=function(g){return g.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(_,{})})},o.parseSimulcastStreamList=function(g){return g.split(";").map(function(d){return d.split(",").map(function(A){var S,R=!1;return A[0]!=="~"?S=n(A):(S=n(A.substring(1,A.length)),R=!0),{scid:S,paused:R}})})}})(dp);var fc=_p,r0=/%[sdv%]/g,s0=function(o){var n=1,r=arguments,a=r.length;return o.replace(r0,function(c){if(n>=a)return c;var e=r[n];switch(n+=1,c){case"%%":return"%";case"%s":return String(e);case"%d":return Number(e);case"%v":return""}})},Mo=function(o,n,r){var a=n.format instanceof Function?n.format(n.push?r:r[n.name]):n.format,c=[o+"="+a];if(n.names)for(var e=0;e<n.names.length;e+=1){var _=n.names[e];n.name?c.push(r[n.name][_]):c.push(r[n.names[e]])}else c.push(r[n.name]);return s0.apply(null,c)},i0=["v","o","s","i","u","e","p","c","b","t","r","z","a"],a0=["i","c","b","a"],o0=function(o,n){n=n||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(e){e.payloads==null&&(e.payloads="")});var r=n.outerOrder||i0,a=n.innerOrder||a0,c=[];return r.forEach(function(e){fc[e].forEach(function(_){_.name in o&&o[_.name]!=null?c.push(Mo(e,_,o)):_.push in o&&o[_.push]!=null&&o[_.push].forEach(function(g){c.push(Mo(e,_,g))})})}),o.media.forEach(function(e){c.push(Mo("m",fc.m[0],e)),a.forEach(function(_){fc[_].forEach(function(g){g.name in e&&e[g.name]!=null?c.push(Mo(_,g,e)):g.push in e&&e[g.push]!=null&&e[g.push].forEach(function(d){c.push(Mo(_,g,d))})})})}),c.join(`\r
|
|
7
7
|
`)+`\r
|
|
8
8
|
`},ha=dp,l0=o0;nr.write=l0,nr.parse=ha.parse,nr.parseParams=ha.parseParams,nr.parseFmtpConfig=ha.parseFmtpConfig,nr.parsePayloads=ha.parsePayloads,nr.parseRemoteCandidates=ha.parseRemoteCandidates,nr.parseImageAttributes=ha.parseImageAttributes,nr.parseSimulcastStreamList=ha.parseSimulcastStreamList;function jl(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?jl=function(n){return typeof n}:jl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},jl(o)}function mc(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&gc(o,n)}function gc(o,n){return gc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},gc(o,n)}function yc(o){var n=d0();return function(){var r=Gl(o),a;if(n){var c=Gl(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return u0(this,a)}}function u0(o,n){return n&&(jl(n)==="object"||typeof n=="function")?n:c0(o)}function c0(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function d0(){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 Gl(o){return Gl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Gl(o)}function Cr(o,n){var r;if(typeof Symbol>"u"||o[Symbol.iterator]==null){if(Array.isArray(o)||(r=h0(o))||n&&o&&typeof o.length=="number"){r&&(o=r);var a=0,c=function(){};return{s:c,n:function(){return a>=o.length?{done:!0}:{done:!1,value:o[a++]}},e:function(d){throw d},f:c}}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 e=!0,
|
|
9
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var e=!0,_=!1,g;return{s:function(){r=o[Symbol.iterator]()},n:function(){var d=r.next();return e=d.done,d},e:function(d){_=!0,g=d},f:function(){try{!e&&r.return!=null&&r.return()}finally{if(_)throw g}}}}function h0(o,n){if(o){if(typeof o=="string")return fp(o,n);var r=Object.prototype.toString.call(o).slice(8,-1);if(r==="Object"&&o.constructor&&(r=o.constructor.name),r==="Map"||r==="Set")return Array.from(o);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return fp(o,n)}}function fp(o,n){(n==null||n>o.length)&&(n=o.length);for(var r=0,a=new Array(n);r<n;r++)a[r]=o[r];return a}function Uo(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function mp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Wl(o,n,r){return n&&mp(o.prototype,n),r&&mp(o,r),o}var gp=nr,p0=bn,An=dn,hn=Bn(),yp=cc(),_0=ss(),vc=new p0("SIPMessage"),vp=function(){function o(n,r,a,c,e,_){if(Uo(this,o),!n||!r||!a)return null;c=c||{},this.ua=a,this.headers={},this.method=n,this.ruri=r,this.body=_,this.extraHeaders=hn.cloneArray(e),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),c.route_set?this.setHeader("route",c.route_set):a.configuration.use_preloaded_route&&this.setHeader("route","<".concat(a.transport.sip_uri,";lr>")),this.setHeader("via",""),this.setHeader("max-forwards",An.MAX_FORWARDS);var g=c.to_uri||r,d=c.to_tag?{tag:c.to_tag}:null,A=typeof c.to_display_name<"u"?c.to_display_name:null;this.to=new yp(g,A,d),this.setHeader("to",this.to.toString());var S=c.from_uri||a.configuration.uri,R={tag:c.from_tag||hn.newTag()},N;typeof c.from_display_name<"u"?N=c.from_display_name:a.configuration.display_name?N=a.configuration.display_name:N=null,this.from=new yp(S,N,R),this.setHeader("from",this.from.toString());var H=c.call_id||a.configuration.jssip_id+hn.createRandomToken(15);this.call_id=H,this.setHeader("call-id",H);var W=c.cseq||Math.floor(Math.random()*1e4);this.cseq=W,this.setHeader("cseq","".concat(W," ").concat(n))}return Wl(o,[{key:"setHeader",value:function(n,r){for(var a=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),c=0;c<this.extraHeaders.length;c++)a.test(this.extraHeaders[c])&&this.extraHeaders.splice(c,1);this.headers[hn.headerize(n)]=Array.isArray(r)?r:[r]}},{key:"getHeader",value:function(n){var r=this.headers[hn.headerize(n)];if(r){if(r[0])return r[0]}else{var a=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),c=Cr(this.extraHeaders),e;try{for(c.s();!(e=c.n()).done;){var _=e.value;if(a.test(_))return _.substring(_.indexOf(":")+1).trim()}}catch(g){c.e(g)}finally{c.f()}}}},{key:"getHeaders",value:function(n){var r=this.headers[hn.headerize(n)],a=[];if(r){var c=Cr(r),e;try{for(c.s();!(e=c.n()).done;){var _=e.value;a.push(_)}}catch(R){c.e(R)}finally{c.f()}return a}else{var g=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),d=Cr(this.extraHeaders),A;try{for(d.s();!(A=d.n()).done;){var S=A.value;g.test(S)&&a.push(S.substring(S.indexOf(":")+1).trim())}}catch(R){d.e(R)}finally{d.f()}return a}}},{key:"hasHeader",value:function(n){if(this.headers[hn.headerize(n)])return!0;var r=new RegExp("^\\s*".concat(n,"\\s*:"),"i"),a=Cr(this.extraHeaders),c;try{for(a.s();!(c=a.n()).done;){var e=c.value;if(r.test(e))return!0}}catch(_){a.e(_)}finally{a.f()}return!1}},{key:"parseSDP",value:function(n){return!n&&this.sdp?this.sdp:(this.sdp=gp.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 r in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,r)){var a=Cr(this.headers[r]),c;try{for(a.s();!(c=a.n()).done;){var e=c.value;n+="".concat(r,": ").concat(e,`\r
|
|
11
|
-
`)}}catch(N){a.e(N)}finally{a.f()}}var
|
|
12
|
-
`)}}catch(N){
|
|
11
|
+
`)}}catch(N){a.e(N)}finally{a.f()}}var _=Cr(this.extraHeaders),g;try{for(_.s();!(g=_.n()).done;){var d=g.value;n+="".concat(d.trim(),`\r
|
|
12
|
+
`)}}catch(N){_.e(N)}finally{_.f()}var A=[];switch(this.method){case An.REGISTER:A.push("path","gruu");break;case An.INVITE:this.ua.configuration.session_timers&&A.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&A.push("gruu"),A.push("ice","replaces");break;case An.UPDATE:this.ua.configuration.session_timers&&A.push("timer"),A.push("ice");break}A.push("outbound");var S=this.ua.configuration.user_agent||An.USER_AGENT;if(n+="Allow: ".concat(An.ALLOWED_METHODS,`\r
|
|
13
13
|
`),n+="Supported: ".concat(A,`\r
|
|
14
14
|
`),n+="User-Agent: ".concat(S,`\r
|
|
15
15
|
`),this.body){var R=hn.str_utf8_length(this.body);n+="Content-Length: ".concat(R,`\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 o(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){n.headers[r]=this.headers[r].slice()},this),n.body=this.body,n.extraHeaders=hn.cloneArray(this.extraHeaders),n.to=this.to,n.from=this.from,n.call_id=this.call_id,n.cseq=this.cseq,n}}]),o}(),f0=function(o){mc(r,o);var n=yc(r);function r(a,c,e,
|
|
19
|
+
`;return n}},{key:"clone",value:function(){var n=new o(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){n.headers[r]=this.headers[r].slice()},this),n.body=this.body,n.extraHeaders=hn.cloneArray(this.extraHeaders),n.to=this.to,n.from=this.from,n.call_id=this.call_id,n.cseq=this.cseq,n}}]),o}(),f0=function(o){mc(r,o);var n=yc(r);function r(a,c,e,_,g){var d;return Uo(this,r),d=n.call(this,An.INVITE,a,c,e,_,g),d.transaction=null,d}return Wl(r,[{key:"cancel",value:function(a){this.transaction.cancel(a)}},{key:"clone",value:function(){var a=new r(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(c){a.headers[c]=this.headers[c].slice()},this),a.body=this.body,a.extraHeaders=hn.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}}]),r}(vp),Tp=function(){function o(){Uo(this,o),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(o,[{key:"addHeader",value:function(n,r){var a={raw:r};n=hn.headerize(n),this.headers[n]?this.headers[n].push(a):this.headers[n]=[a]}},{key:"getHeader",value:function(n){var r=this.headers[hn.headerize(n)];if(r){if(r[0])return r[0].raw}else return}},{key:"getHeaders",value:function(n){var r=this.headers[hn.headerize(n)],a=[];if(!r)return[];var c=Cr(r),e;try{for(c.s();!(e=c.n()).done;){var _=e.value;a.push(_.raw)}}catch(g){c.e(g)}finally{c.f()}return a}},{key:"hasHeader",value:function(n){return!!this.headers[hn.headerize(n)]}},{key:"parseHeader",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(n=hn.headerize(n),this.headers[n]){if(r>=this.headers[n].length){vc.debug('not so many "'.concat(n,'" headers present'));return}}else{vc.debug('header "'.concat(n,'" not present'));return}var a=this.headers[n][r],c=a.raw;if(a.parsed)return a.parsed;var e=_0.parse(c,n.replace(/-/g,"_"));if(e===-1){this.headers[n].splice(r,1),vc.debug('error parsing "'.concat(n,'" header field with value "').concat(c,'"'));return}else return a.parsed=e,e}},{key:"s",value:function(n,r){return this.parseHeader(n,r)}},{key:"setHeader",value:function(n,r){var a={raw:r};this.headers[hn.headerize(n)]=[a]}},{key:"parseSDP",value:function(n){return!n&&this.sdp?this.sdp:(this.sdp=gp.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){return this.data}}]),o}(),m0=function(o){mc(r,o);var n=yc(r);function r(a){var c;return Uo(this,r),c=n.call(this),c.ua=a,c.headers={},c.ruri=null,c.transport=null,c.server_transaction=null,c}return Wl(r,[{key:"reply",value:function(a,c,e,_,g,d){var A=[],S=this.getHeader("To");if(a=a||null,c=c||null,!a||a<100||a>699)throw new TypeError("Invalid status_code: ".concat(a));if(c&&typeof c!="string"&&!(c instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(c));c=c||An.REASON_PHRASE[a]||"",e=hn.cloneArray(e),this.ua.configuration.extra_headers&&(e=e.concat(this.ua.configuration.extra_headers));var R="SIP/2.0 ".concat(a," ").concat(c,`\r
|
|
20
20
|
`);if(this.method===An.INVITE&&a>100&&a<=200){var N=this.getHeaders("record-route"),H=Cr(N),W;try{for(H.s();!(W=H.n()).done;){var G=W.value;R+="Record-Route: ".concat(G,`\r
|
|
21
21
|
`)}}catch(Q){H.e(Q)}finally{H.f()}}var K=this.getHeaders("via"),ae=Cr(K),ee;try{for(ae.s();!(ee=ae.n()).done;){var De=ee.value;R+="Via: ".concat(De,`\r
|
|
22
22
|
`)}}catch(Q){ae.e(Q)}finally{ae.f()}!this.to_tag&&a>100?S+=";tag=".concat(hn.newTag()):this.to_tag&&!this.s("to").hasParam("tag")&&(S+=";tag=".concat(this.to_tag)),R+="To: ".concat(S,`\r
|
|
@@ -24,30 +24,30 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
24
24
|
`),R+="Call-ID: ".concat(this.call_id,`\r
|
|
25
25
|
`),R+="CSeq: ".concat(this.cseq," ").concat(this.method,`\r
|
|
26
26
|
`);var X=Cr(e),re;try{for(X.s();!(re=X.n()).done;){var be=re.value;R+="".concat(be.trim(),`\r
|
|
27
|
-
`)}}catch(Q){X.e(Q)}finally{X.f()}switch(this.method){case An.INVITE:this.ua.configuration.session_timers&&A.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&A.push("gruu"),A.push("ice","replaces");break;case An.UPDATE:this.ua.configuration.session_timers&&A.push("timer"),
|
|
27
|
+
`)}}catch(Q){X.e(Q)}finally{X.f()}switch(this.method){case An.INVITE:this.ua.configuration.session_timers&&A.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&A.push("gruu"),A.push("ice","replaces");break;case An.UPDATE:this.ua.configuration.session_timers&&A.push("timer"),_&&A.push("ice"),A.push("replaces")}if(A.push("outbound"),this.method===An.OPTIONS?(R+="Allow: ".concat(An.ALLOWED_METHODS,`\r
|
|
28
28
|
`),R+="Accept: ".concat(An.ACCEPTED_BODY_TYPES,`\r
|
|
29
29
|
`)):a===405?R+="Allow: ".concat(An.ALLOWED_METHODS,`\r
|
|
30
30
|
`):a===415&&(R+="Accept: ".concat(An.ACCEPTED_BODY_TYPES,`\r
|
|
31
31
|
`)),R+="Supported: ".concat(A,`\r
|
|
32
|
-
`),
|
|
32
|
+
`),_){var Ne=hn.str_utf8_length(_);R+=`Content-Type: application/sdp\r
|
|
33
33
|
`,R+="Content-Length: ".concat(Ne,`\r
|
|
34
34
|
\r
|
|
35
|
-
`),R+=
|
|
35
|
+
`),R+=_}else R+="Content-Length: ".concat(0,`\r
|
|
36
36
|
\r
|
|
37
|
-
`);this.server_transaction.receiveResponse(a,R,g,d)}},{key:"reply_sl",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,e=this.getHeaders("via");if(!a||a<100||a>699)throw new TypeError("Invalid status_code: ".concat(a));if(c&&typeof c!="string"&&!(c instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(c));c=c||An.REASON_PHRASE[a]||"";var
|
|
38
|
-
`),g=Cr(e),d;try{for(g.s();!(d=g.n()).done;){var A=d.value;
|
|
39
|
-
`)}}catch(W){g.e(W)}finally{g.f()}var S=this.getHeader("To");if(!this.to_tag&&a>100?S+=";tag=".concat(hn.newTag()):this.to_tag&&!this.s("to").hasParam("tag")&&(S+=";tag=".concat(this.to_tag)),
|
|
40
|
-
`),
|
|
41
|
-
`),
|
|
42
|
-
`),
|
|
43
|
-
`),this.ua.configuration.extra_headers){var R=Cr(this.ua.configuration.extra_headers),N;try{for(R.s();!(N=R.n()).done;){var H=N.value;
|
|
44
|
-
`)}}catch(W){R.e(W)}finally{R.f()}}
|
|
37
|
+
`);this.server_transaction.receiveResponse(a,R,g,d)}},{key:"reply_sl",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,e=this.getHeaders("via");if(!a||a<100||a>699)throw new TypeError("Invalid status_code: ".concat(a));if(c&&typeof c!="string"&&!(c instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(c));c=c||An.REASON_PHRASE[a]||"";var _="SIP/2.0 ".concat(a," ").concat(c,`\r
|
|
38
|
+
`),g=Cr(e),d;try{for(g.s();!(d=g.n()).done;){var A=d.value;_+="Via: ".concat(A,`\r
|
|
39
|
+
`)}}catch(W){g.e(W)}finally{g.f()}var S=this.getHeader("To");if(!this.to_tag&&a>100?S+=";tag=".concat(hn.newTag()):this.to_tag&&!this.s("to").hasParam("tag")&&(S+=";tag=".concat(this.to_tag)),_+="To: ".concat(S,`\r
|
|
40
|
+
`),_+="From: ".concat(this.getHeader("From"),`\r
|
|
41
|
+
`),_+="Call-ID: ".concat(this.call_id,`\r
|
|
42
|
+
`),_+="CSeq: ".concat(this.cseq," ").concat(this.method,`\r
|
|
43
|
+
`),this.ua.configuration.extra_headers){var R=Cr(this.ua.configuration.extra_headers),N;try{for(R.s();!(N=R.n()).done;){var H=N.value;_+="".concat(H.trim(),`\r
|
|
44
|
+
`)}}catch(W){R.e(W)}finally{R.f()}}_+="Content-Length: ".concat(0,`\r
|
|
45
45
|
\r
|
|
46
|
-
`),this.transport.send(f)}}]),r}(Tp),g0=function(o){mc(r,o);var n=yc(r);function r(){var a;return Uo(this,r),a=n.call(this),a.headers={},a.status_code=null,a.reason_phrase=null,a}return r}(Tp),Os={OutgoingRequest:vp,InitialOutgoingInviteRequest:f0,IncomingRequest:m0,IncomingResponse:g0};function y0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function bp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function v0(o,n,r){return n&&bp(o.prototype,n),r&&bp(o,r),o}var T0=bn,ks=Bn(),qr=new T0("DigestAuthentication"),b0=function(){function o(n){y0(this,o),this._credentials=n,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 v0(o,[{key:"get",value:function(n){switch(n){case"realm":return this._realm;case"ha1":return this._ha1;default:qr.warn('get() | cannot get "%s" parameter',n);return}}},{key:"authenticate",value:function(n,r){var a=n.method,c=n.ruri,e=n.body,f=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this._algorithm=r.algorithm,this._realm=r.realm,this._nonce=r.nonce,this._opaque=r.opaque,this._stale=r.stale,this._algorithm){if(this._algorithm!=="MD5")return qr.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return qr.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return qr.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return qr.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return qr.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(r.qop)if(r.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(r.qop.indexOf("auth")>-1)this._qop="auth";else return qr.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=a,this._uri=c,this._cnonce=f||ks.createRandomToken(12),this._nc+=1;var g=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-g.length)+g,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=ks.calculateMD5("".concat(this._credentials.username,":").concat(this._realm,":").concat(this._credentials.password)):this._ha1=this._credentials.ha1;var d,A;return this._qop==="auth"?(d="".concat(this._method,":").concat(this._uri),A=ks.calculateMD5(d),qr.debug('authenticate() | using qop=auth [a2:"%s"]',d),this._response=ks.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth:").concat(A))):this._qop==="auth-int"?(d="".concat(this._method,":").concat(this._uri,":").concat(ks.calculateMD5(e||"")),A=ks.calculateMD5(d),qr.debug('authenticate() | using qop=auth-int [a2:"%s"]',d),this._response=ks.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth-int:").concat(A))):this._qop===null&&(d="".concat(this._method,":").concat(this._uri),A=ks.calculateMD5(d),qr.debug('authenticate() | using qop=null [a2:"%s"]',d),this._response=ks.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(A))),qr.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(", "))}}]),o}(),Ds=500,w0=4e3,wp=5e3,Sp={T1:Ds,T2:w0,T4:wp,TIMER_B:64*Ds,TIMER_D:0*Ds,TIMER_F:64*Ds,TIMER_H:64*Ds,TIMER_I:0*Ds,TIMER_J:0*Ds,TIMER_K:0*wp,TIMER_L:64*Ds,TIMER_M:64*Ds,PROVISIONAL_RESPONSE_INTERVAL:6e4};function Kl(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Kl=function(n){return typeof n}:Kl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Kl(o)}function Po(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Ep(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Lo(o,n,r){return n&&Ep(o.prototype,n),r&&Ep(o,r),o}function qo(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Tc(o,n)}function Tc(o,n){return Tc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Tc(o,n)}function Ho(o){var n=E0();return function(){var r=Yl(o),a;if(n){var c=Yl(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return S0(this,a)}}function S0(o,n){return n&&(Kl(n)==="object"||typeof n=="function")?n:li(o)}function li(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function E0(){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 Yl(o){return Yl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Yl(o)}var zo=Tn.EventEmitter,Fo=bn,Bo=dn,Cp=Os,is=Sp,Ap=new Fo("NonInviteClientTransaction"),Xl=new Fo("InviteClientTransaction"),C0=new Fo("AckClientTransaction"),Ip=new Fo("NonInviteServerTransaction"),Jl=new Fo("InviteServerTransaction"),ze={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"},A0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e,f){var g;Po(this,r),g=n.call(this),g.type=ze.NON_INVITE_CLIENT,g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.ua=a,g.transport=c,g.request=e,g.eventHandlers=f;var d="SIP/2.0/".concat(c.via_transport);return d+=" ".concat(a.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",d),g.ua.newTransaction(li(g)),g}return Lo(r,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(ze.STATUS_TRYING),this.F=setTimeout(function(){a.timer_F()},is.TIMER_F),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){Ap.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}},{key:"timer_F",value:function(){Ap.debug("Timer F expired for transaction ".concat(this.id)),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}},{key:"timer_K",value:function(){this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"receiveResponse",value:function(a){var c=this,e=a.status_code;if(e<200)switch(this.state){case ze.STATUS_TRYING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break}else switch(this.state){case ze.STATUS_TRYING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_COMPLETED),clearTimeout(this.F),e===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(a),this.K=setTimeout(function(){c.timer_K()},is.TIMER_K);break;case ze.STATUS_COMPLETED:break}}},{key:"C",get:function(){return ze}}]),r}(zo),I0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e,f){var g;Po(this,r),g=n.call(this),g.type=ze.INVITE_CLIENT,g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.ua=a,g.transport=c,g.request=e,g.eventHandlers=f,e.transaction=li(g);var d="SIP/2.0/".concat(c.via_transport);return d+=" ".concat(a.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",d),g.ua.newTransaction(li(g)),g}return Lo(r,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(ze.STATUS_CALLING),this.B=setTimeout(function(){a.timer_B()},is.TIMER_B),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==ze.STATUS_ACCEPTED&&(Xl.debug("transport error occurred, deleting transaction ".concat(this.id)),this.eventHandlers.onTransportError()),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_M",value:function(){Xl.debug("Timer M expired for transaction ".concat(this.id)),this.state===ze.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"timer_B",value:function(){Xl.debug("Timer B expired for transaction ".concat(this.id)),this.state===ze.STATUS_CALLING&&(this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}},{key:"timer_D",value:function(){Xl.debug("Timer D expired for transaction ".concat(this.id)),clearTimeout(this.B),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"sendACK",value:function(a){var c=this,e=new Cp.OutgoingRequest(Bo.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});e.setHeader("from",this.request.getHeader("from")),e.setHeader("via",this.request.getHeader("via")),e.setHeader("to",a.getHeader("to")),this.D=setTimeout(function(){c.timer_D()},is.TIMER_D),this.transport.send(e)}},{key:"cancel",value:function(a){if(this.state===ze.STATUS_PROCEEDING){var c=new Cp.OutgoingRequest(Bo.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});c.setHeader("from",this.request.getHeader("from")),c.setHeader("via",this.request.getHeader("via")),c.setHeader("to",this.request.getHeader("to")),a&&c.setHeader("reason",a),this.transport.send(c)}}},{key:"receiveResponse",value:function(a){var c=this,e=a.status_code;if(e>=100&&e<=199)switch(this.state){case ze.STATUS_CALLING:this.stateChanged(ze.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break;case ze.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(a);break}else if(e>=200&&e<=299)switch(this.state){case ze.STATUS_CALLING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_ACCEPTED),this.M=setTimeout(function(){c.timer_M()},is.TIMER_M),this.eventHandlers.onReceiveResponse(a);break;case ze.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(a);break}else if(e>=300&&e<=699)switch(this.state){case ze.STATUS_CALLING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_COMPLETED),this.sendACK(a),this.eventHandlers.onReceiveResponse(a);break;case ze.STATUS_COMPLETED:this.sendACK(a);break}}},{key:"C",get:function(){return ze}}]),r}(zo),R0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e,f){var g;Po(this,r),g=n.call(this),g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.transport=c,g.request=e,g.eventHandlers=f;var d="SIP/2.0/".concat(c.via_transport);return d+=" ".concat(a.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",d),g}return Lo(r,[{key:"send",value:function(){this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){C0.debug("transport error occurred for transaction ".concat(this.id)),this.eventHandlers.onTransportError()}},{key:"C",get:function(){return ze}}]),r}(zo),$0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e){var f;return Po(this,r),f=n.call(this),f.type=ze.NON_INVITE_SERVER,f.id=e.via_branch,f.ua=a,f.transport=c,f.request=e,f.last_response="",e.server_transaction=li(f),f.state=ze.STATUS_TRYING,a.newTransaction(li(f)),f}return Lo(r,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_J",value:function(){Ip.debug("Timer J expired for transaction ".concat(this.id)),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,Ip.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.J),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"receiveResponse",value:function(a,c,e,f){var g=this;if(a===100)switch(this.state){case ze.STATUS_TRYING:this.stateChanged(ze.STATUS_PROCEEDING),this.transport.send(c)||this.onTransportError();break;case ze.STATUS_PROCEEDING:this.last_response=c,this.transport.send(c)?e&&e():(this.onTransportError(),f&&f());break}else if(a>=200&&a<=699)switch(this.state){case ze.STATUS_TRYING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_COMPLETED),this.last_response=c,this.J=setTimeout(function(){g.timer_J()},is.TIMER_J),this.transport.send(c)?e&&e():(this.onTransportError(),f&&f());break;case ze.STATUS_COMPLETED:break}}},{key:"C",get:function(){return ze}}]),r}(zo),x0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e){var f;return Po(this,r),f=n.call(this),f.type=ze.INVITE_SERVER,f.id=e.via_branch,f.ua=a,f.transport=c,f.request=e,f.last_response="",e.server_transaction=li(f),f.state=ze.STATUS_PROCEEDING,a.newTransaction(li(f)),f.resendProvisionalTimer=null,e.reply(100),f}return Lo(r,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_H",value:function(){Jl.debug("Timer H expired for transaction ".concat(this.id)),this.state===ze.STATUS_COMPLETED&&Jl.debug("ACK not received, dialog will be terminated"),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_I",value:function(){this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_L",value:function(){Jl.debug("Timer L expired for transaction ".concat(this.id)),this.state===ze.STATUS_ACCEPTED&&(this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,Jl.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(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"resend_provisional",value:function(){this.transport.send(this.last_response)||this.onTransportError()}},{key:"receiveResponse",value:function(a,c,e,f){var g=this;if(a>=100&&a<=199)switch(this.state){case ze.STATUS_PROCEEDING:this.transport.send(c)||this.onTransportError(),this.last_response=c;break}if(a>100&&a<=199&&this.state===ze.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(function(){g.resend_provisional()},is.PROVISIONAL_RESPONSE_INTERVAL));else if(a>=200&&a<=299)switch(this.state){case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_ACCEPTED),this.last_response=c,this.L=setTimeout(function(){g.timer_L()},is.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case ze.STATUS_ACCEPTED:this.transport.send(c)?e&&e():(this.onTransportError(),f&&f());break}else if(a>=300&&a<=699)switch(this.state){case ze.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(c)?(this.stateChanged(ze.STATUS_COMPLETED),this.H=setTimeout(function(){g.timer_H()},is.TIMER_H),e&&e()):(this.onTransportError(),f&&f());break}}},{key:"C",get:function(){return ze}}]),r}(zo);function O0(o,n){var r=o._transactions,a;switch(n.method){case Bo.INVITE:if(a=r.ist[n.via_branch],a){switch(a.state){case ze.STATUS_PROCEEDING:a.transport.send(a.last_response);break;case ze.STATUS_ACCEPTED:break}return!0}break;case Bo.ACK:if(a=r.ist[n.via_branch],a){if(a.state===ze.STATUS_ACCEPTED)return!1;if(a.state===ze.STATUS_COMPLETED)return a.state=ze.STATUS_CONFIRMED,a.I=setTimeout(function(){a.timer_I()},is.TIMER_I),!0}else return!1;break;case Bo.CANCEL:return a=r.ist[n.via_branch],a?(n.reply_sl(200),a.state!==ze.STATUS_PROCEEDING):(n.reply_sl(481),!0);default:if(a=r.nist[n.via_branch],a){switch(a.state){case ze.STATUS_TRYING:break;case ze.STATUS_PROCEEDING:case ze.STATUS_COMPLETED:a.transport.send(a.last_response);break}return!0}break}}var Vo={C:ze,NonInviteClientTransaction:A0,InviteClientTransaction:I0,AckClientTransaction:R0,NonInviteServerTransaction:$0,InviteServerTransaction:x0,checkTransaction:O0};function k0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Rp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function D0(o,n,r){return n&&Rp(o.prototype,n),r&&Rp(o,r),o}var N0=bn,$p=dn,M0=b0,bc=Vo,U0=new N0("RequestSender"),wc={onRequestTimeout:function(){},onTransportError:function(){},onReceiveResponse:function(){},onAuthenticated:function(){}},jo=function(){function o(n,r,a){k0(this,o),this._ua=n,this._eventHandlers=a,this._method=r.method,this._request=r,this._auth=null,this._challenged=!1,this._staled=!1;for(var c in wc)Object.prototype.hasOwnProperty.call(wc,c)&&(this._eventHandlers[c]||(this._eventHandlers[c]=wc[c]));n.status===n.C.STATUS_USER_CLOSED&&(this._method!==$p.BYE||this._method!==$p.ACK)&&this._eventHandlers.onTransportError()}return D0(o,[{key:"send",value:function(){var n=this,r={onRequestTimeout:function(){n._eventHandlers.onRequestTimeout()},onTransportError:function(){n._eventHandlers.onTransportError()},onReceiveResponse:function(a){n._receiveResponse(a)}};switch(this._method){case"INVITE":this.clientTransaction=new bc.InviteClientTransaction(this._ua,this._ua.transport,this._request,r);break;case"ACK":this.clientTransaction=new bc.AckClientTransaction(this._ua,this._ua.transport,this._request,r);break;default:this.clientTransaction=new bc.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,r)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}},{key:"_receiveResponse",value:function(n){var r,a,c=n.status_code;if((c===401||c===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(n.status_code===401?(r=n.parseHeader("www-authenticate"),a="authorization"):(r=n.parseHeader("proxy-authenticate"),a="proxy-authorization"),!r){U0.debug("".concat(n.status_code," with wrong or missing challenge, cannot authenticate")),this._eventHandlers.onReceiveResponse(n);return}if(!this._challenged||!this._staled&&r.stale===!0){if(this._auth||(this._auth=new M0({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,r)){this._eventHandlers.onReceiveResponse(n);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),r.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)}}]),o}();function P0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function xp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function L0(o,n,r){return n&&xp(o.prototype,n),r&&xp(o,r),o}var q0=bn,Sc=Bn(),pa=dn,Op=Os,kp=jo,Go=new q0("Registrator"),Ql=10,H0=function(){function o(n,r){P0(this,o),this._reg_id=1,this._ua=n,this._transport=r,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=Sc.createRandomToken(22),this._cseq=0,this._to_uri=n.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 L0(o,[{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 r in n)if(Object.prototype.hasOwnProperty.call(n,r)){var a=n[r];this._extraContactParams+=";".concat(r),a&&(this._extraContactParams+="=".concat(a))}}},{key:"register",value:function(){var n=this;if(this._registering){Go.debug("Register request in progress...");return}var r=this._extraHeaders.slice();r.push("Contact: ".concat(this._contact,";expires=").concat(this._expires).concat(this._extraContactParams)),r.push("Expires: ".concat(this._expires));var a=new Op.OutgoingRequest(pa.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r),c=new kp(this._ua,a,{onRequestTimeout:function(){n._registrationFailure(null,pa.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._registrationFailure(null,pa.causes.CONNECTION_ERROR)},onAuthenticated:function(){n._cseq+=1},onReceiveResponse:function(e){if(e.cseq===n._cseq)switch(n._registrationTimer!==null&&(clearTimeout(n._registrationTimer),n._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):{if(n._registering=!1,!e.hasHeader("Contact")){Go.debug("no Contact header in response to REGISTER, response ignored");break}var f=e.headers.Contact.reduce(function(R,N){return R.concat(N.parsed)},[]),g=f.find(function(R){return n._sipInstance===R.getParam("+sip.instance")&&n._reg_id===parseInt(R.getParam("reg-id"))});if(g||(g=f.find(function(R){return R.uri.user===n._ua.contact.uri.user})),!g){Go.debug("no Contact header pointing to us, response ignored");break}var d=g.getParam("expires");!d&&e.hasHeader("expires")&&(d=e.getHeader("expires")),d||(d=n._expires),d=Number(d),d<Ql&&(d=Ql);var A=d>64?d*1e3/2+Math.floor((d/2-32)*1e3*Math.random()):d*1e3-5e3;n._registrationTimer=setTimeout(function(){n._registrationTimer=null,n._ua.listeners("registrationExpiring").length===0?n.register():n._ua.emit("registrationExpiring")},A),g.hasParam("temp-gruu")&&(n._ua.contact.temp_gruu=g.getParam("temp-gruu").replace(/"/g,"")),g.hasParam("pub-gruu")&&(n._ua.contact.pub_gruu=g.getParam("pub-gruu").replace(/"/g,"")),n._registered||(n._registered=!0,n._ua.registered({response:e}));break}case/^423$/.test(e.status_code):{e.hasHeader("min-expires")?(n._expires=Number(e.getHeader("min-expires")),n._expires<Ql&&(n._expires=Ql),n.register()):(Go.debug("423 response received for REGISTER without Min-Expires"),n._registrationFailure(e,pa.causes.SIP_FAILURE_CODE));break}default:{var S=Sc.sipErrorCause(e.status_code);n._registrationFailure(e,S)}}}});this._registering=!0,c.send()}},{key:"unregister",value:function(){var n=this,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._registered){Go.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);var a=this._extraHeaders.slice();r.all?a.push("Contact: *".concat(this._extraContactParams)):a.push("Contact: ".concat(this._contact,";expires=0").concat(this._extraContactParams)),a.push("Expires: 0");var c=new Op.OutgoingRequest(pa.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},a),e=new kp(this._ua,c,{onRequestTimeout:function(){n._unregistered(null,pa.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._unregistered(null,pa.causes.CONNECTION_ERROR)},onAuthenticated:function(){n._cseq+=1},onReceiveResponse:function(f){switch(!0){case/^1[0-9]{2}$/.test(f.status_code):break;case/^2[0-9]{2}$/.test(f.status_code):n._unregistered(f);break;default:{var g=Sc.sipErrorCause(f.status_code);n._unregistered(f,g)}}}});e.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,r){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:r}))}},{key:"_unregistered",value:function(n,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:r||null})}},{key:"registered",get:function(){return this._registered}}]),o}();function z0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Dp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function F0(o,n,r){return n&&Dp(o.prototype,n),r&&Dp(o,r),o}var Ec=dn,Zl=Vo,B0=jo,Cc={onRequestTimeout:function(){},onTransportError:function(){},onSuccessResponse:function(){},onErrorResponse:function(){},onAuthenticated:function(){},onDialogError:function(){}},V0=function(){function o(n,r,a){z0(this,o),this._dialog=n,this._ua=n._ua,this._request=r,this._eventHandlers=a,this._reattempt=!1,this._reattemptTimer=null;for(var c in Cc)Object.prototype.hasOwnProperty.call(Cc,c)&&(this._eventHandlers[c]||(this._eventHandlers[c]=Cc[c]))}return F0(o,[{key:"send",value:function(){var n=this,r=new B0(this._ua,this._request,{onRequestTimeout:function(){n._eventHandlers.onRequestTimeout()},onTransportError:function(){n._eventHandlers.onTransportError()},onAuthenticated:function(c){n._eventHandlers.onAuthenticated(c)},onReceiveResponse:function(c){n._receiveResponse(c)}});if(r.send(),(this._request.method===Ec.INVITE||this._request.method===Ec.UPDATE&&this._request.body)&&r.clientTransaction.state!==Zl.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;var a=function c(){(r.clientTransaction.state===Zl.C.STATUS_ACCEPTED||r.clientTransaction.state===Zl.C.STATUS_COMPLETED||r.clientTransaction.state===Zl.C.STATUS_TERMINATED)&&(r.clientTransaction.removeListener("stateChanged",c),n._dialog.uac_pending_reply=!1)};r.clientTransaction.on("stateChanged",a)}}},{key:"_receiveResponse",value:function(n){var r=this;n.status_code===408||n.status_code===481?this._eventHandlers.onDialogError(n):n.method===Ec.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(){r._dialog.isTerminated()||(r._reattempt=!0,r.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}}]),o}();function j0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Np(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Mp(o,n,r){return n&&Np(o.prototype,n),r&&Np(o,r),o}var G0=bn,Up=Os,ui=dn,Wo=Vo,W0=V0,Ac=Bn(),Ic=new G0("Dialog"),ci={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3},K0=function(){Mp(o,null,[{key:"C",get:function(){return ci}}]);function o(n,r,a){var c=arguments.length>3&&arguments[3]!==void 0?arguments[3]:ci.STATUS_CONFIRMED;if(j0(this,o),this._owner=n,this._ua=n._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!r.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};r instanceof Up.IncomingResponse&&(c=r.status_code<200?ci.STATUS_EARLY:ci.STATUS_CONFIRMED);var e=r.parseHeader("contact");a==="UAS"?(this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=c,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri,this._remote_target=e.uri,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):a==="UAC"&&(this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=c,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri,this._remote_target=e.uri,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),Ic.debug("new ".concat(a," dialog created with status ").concat(this._state===ci.STATUS_EARLY?"EARLY":"CONFIRMED"))}return Mp(o,[{key:"isTerminated",value:function(){return this._status===ci.STATUS_TERMINATED}},{key:"update",value:function(n,r){this._state=ci.STATUS_CONFIRMED,Ic.debug("dialog ".concat(this._id.toString()," changed to CONFIRMED state")),r==="UAC"&&(this._route_set=n.getHeaders("record-route").reverse())}},{key:"terminate",value:function(){Ic.debug("dialog ".concat(this._id.toString()," deleted")),this._ua.destroyDialog(this),this._state=ci.STATUS_TERMINATED}},{key:"sendRequest",value:function(n){var r=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c=Ac.cloneArray(a.extraHeaders),e=Ac.cloneObject(a.eventHandlers),f=a.body||null,g=this._createRequest(n,c,f);e.onAuthenticated=function(){r._local_seqnum+=1};var d=new W0(this,g,e);return d.send(),g}},{key:"receiveRequest",value:function(n){this._checkInDialogRequest(n)&&(n.method===ui.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:n.method===ui.INVITE&&(this._ack_seqnum=n.cseq),this._owner.receiveRequest(n))}},{key:"_createRequest",value:function(n,r,a){r=Ac.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));var c=n===ui.CANCEL||n===ui.ACK?this._local_seqnum:this._local_seqnum+=1,e=new Up.OutgoingRequest(n,this._remote_target,this._ua,{cseq:c,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},r,a);return e}},{key:"_checkInDialogRequest",value:function(n){var r=this;if(!this._remote_seqnum)this._remote_seqnum=n.cseq;else if(n.cseq<this._remote_seqnum)if(n.method===ui.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===ui.INVITE||n.method===ui.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 c=function e(){(n.server_transaction.state===Wo.C.STATUS_ACCEPTED||n.server_transaction.state===Wo.C.STATUS_COMPLETED||n.server_transaction.state===Wo.C.STATUS_TERMINATED)&&(n.server_transaction.removeListener("stateChanged",e),r._uas_pending_reply=!1)};n.server_transaction.on("stateChanged",c)}n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Wo.C.STATUS_ACCEPTED&&(r._remote_target=n.parseHeader("contact").uri)})}else n.method===ui.NOTIFY&&n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Wo.C.STATUS_COMPLETED&&(r._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}}]),o}(),Rc={exports:{}};function eu(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?eu=function(n){return typeof n}:eu=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},eu(o)}function Y0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Pp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function X0(o,n,r){return n&&Pp(o.prototype,n),r&&Pp(o,r),o}function J0(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&$c(o,n)}function $c(o,n){return $c=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},$c(o,n)}function Q0(o){var n=tw();return function(){var r=tu(o),a;if(n){var c=tu(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return Z0(this,a)}}function Z0(o,n){return n&&(eu(n)==="object"||typeof n=="function")?n:ew(o)}function ew(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function tw(){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 tu(o){return tu=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},tu(o)}var nw=Tn.EventEmitter,rw=bn,sw=dn,iw=ai,Lp=Bn(),aw=new rw("RTCSession:DTMF"),qp={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};Rc.exports=function(o){J0(r,o);var n=Q0(r);function r(a){var c;return Y0(this,r),c=n.call(this),c._session=a,c._direction=null,c._tone=null,c._duration=null,c._request=null,c}return X0(r,[{key:"send",value:function(a){var c=this,e=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 iw.InvalidStateError(this._session.status);var f=Lp.cloneArray(e.extraHeaders);if(this.eventHandlers=Lp.cloneObject(e.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=e.duration,f.push("Content-Type: application/dtmf-relay");var g="Signal=".concat(this._tone,`\r
|
|
47
|
-
`);g+="Duration=".concat(this._duration),this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(sw.INFO,{extraHeaders:
|
|
48
|
-
`);
|
|
46
|
+
`),this.transport.send(_)}}]),r}(Tp),g0=function(o){mc(r,o);var n=yc(r);function r(){var a;return Uo(this,r),a=n.call(this),a.headers={},a.status_code=null,a.reason_phrase=null,a}return r}(Tp),Os={OutgoingRequest:vp,InitialOutgoingInviteRequest:f0,IncomingRequest:m0,IncomingResponse:g0};function y0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function bp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function v0(o,n,r){return n&&bp(o.prototype,n),r&&bp(o,r),o}var T0=bn,ks=Bn(),qr=new T0("DigestAuthentication"),b0=function(){function o(n){y0(this,o),this._credentials=n,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 v0(o,[{key:"get",value:function(n){switch(n){case"realm":return this._realm;case"ha1":return this._ha1;default:qr.warn('get() | cannot get "%s" parameter',n);return}}},{key:"authenticate",value:function(n,r){var a=n.method,c=n.ruri,e=n.body,_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this._algorithm=r.algorithm,this._realm=r.realm,this._nonce=r.nonce,this._opaque=r.opaque,this._stale=r.stale,this._algorithm){if(this._algorithm!=="MD5")return qr.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return qr.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return qr.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return qr.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return qr.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(r.qop)if(r.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(r.qop.indexOf("auth")>-1)this._qop="auth";else return qr.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=a,this._uri=c,this._cnonce=_||ks.createRandomToken(12),this._nc+=1;var g=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-g.length)+g,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=ks.calculateMD5("".concat(this._credentials.username,":").concat(this._realm,":").concat(this._credentials.password)):this._ha1=this._credentials.ha1;var d,A;return this._qop==="auth"?(d="".concat(this._method,":").concat(this._uri),A=ks.calculateMD5(d),qr.debug('authenticate() | using qop=auth [a2:"%s"]',d),this._response=ks.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth:").concat(A))):this._qop==="auth-int"?(d="".concat(this._method,":").concat(this._uri,":").concat(ks.calculateMD5(e||"")),A=ks.calculateMD5(d),qr.debug('authenticate() | using qop=auth-int [a2:"%s"]',d),this._response=ks.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth-int:").concat(A))):this._qop===null&&(d="".concat(this._method,":").concat(this._uri),A=ks.calculateMD5(d),qr.debug('authenticate() | using qop=null [a2:"%s"]',d),this._response=ks.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(A))),qr.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(", "))}}]),o}(),Ds=500,w0=4e3,wp=5e3,Sp={T1:Ds,T2:w0,T4:wp,TIMER_B:64*Ds,TIMER_D:0*Ds,TIMER_F:64*Ds,TIMER_H:64*Ds,TIMER_I:0*Ds,TIMER_J:0*Ds,TIMER_K:0*wp,TIMER_L:64*Ds,TIMER_M:64*Ds,PROVISIONAL_RESPONSE_INTERVAL:6e4};function Kl(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Kl=function(n){return typeof n}:Kl=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Kl(o)}function Po(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Ep(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Lo(o,n,r){return n&&Ep(o.prototype,n),r&&Ep(o,r),o}function qo(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Tc(o,n)}function Tc(o,n){return Tc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Tc(o,n)}function Ho(o){var n=E0();return function(){var r=Yl(o),a;if(n){var c=Yl(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return S0(this,a)}}function S0(o,n){return n&&(Kl(n)==="object"||typeof n=="function")?n:li(o)}function li(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function E0(){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 Yl(o){return Yl=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Yl(o)}var zo=Tn.EventEmitter,Fo=bn,Bo=dn,Cp=Os,is=Sp,Ap=new Fo("NonInviteClientTransaction"),Xl=new Fo("InviteClientTransaction"),C0=new Fo("AckClientTransaction"),Ip=new Fo("NonInviteServerTransaction"),Jl=new Fo("InviteServerTransaction"),ze={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"},A0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e,_){var g;Po(this,r),g=n.call(this),g.type=ze.NON_INVITE_CLIENT,g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.ua=a,g.transport=c,g.request=e,g.eventHandlers=_;var d="SIP/2.0/".concat(c.via_transport);return d+=" ".concat(a.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",d),g.ua.newTransaction(li(g)),g}return Lo(r,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(ze.STATUS_TRYING),this.F=setTimeout(function(){a.timer_F()},is.TIMER_F),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){Ap.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}},{key:"timer_F",value:function(){Ap.debug("Timer F expired for transaction ".concat(this.id)),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}},{key:"timer_K",value:function(){this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"receiveResponse",value:function(a){var c=this,e=a.status_code;if(e<200)switch(this.state){case ze.STATUS_TRYING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break}else switch(this.state){case ze.STATUS_TRYING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_COMPLETED),clearTimeout(this.F),e===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(a),this.K=setTimeout(function(){c.timer_K()},is.TIMER_K);break;case ze.STATUS_COMPLETED:break}}},{key:"C",get:function(){return ze}}]),r}(zo),I0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e,_){var g;Po(this,r),g=n.call(this),g.type=ze.INVITE_CLIENT,g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.ua=a,g.transport=c,g.request=e,g.eventHandlers=_,e.transaction=li(g);var d="SIP/2.0/".concat(c.via_transport);return d+=" ".concat(a.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",d),g.ua.newTransaction(li(g)),g}return Lo(r,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"send",value:function(){var a=this;this.stateChanged(ze.STATUS_CALLING),this.B=setTimeout(function(){a.timer_B()},is.TIMER_B),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==ze.STATUS_ACCEPTED&&(Xl.debug("transport error occurred, deleting transaction ".concat(this.id)),this.eventHandlers.onTransportError()),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_M",value:function(){Xl.debug("Timer M expired for transaction ".concat(this.id)),this.state===ze.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"timer_B",value:function(){Xl.debug("Timer B expired for transaction ".concat(this.id)),this.state===ze.STATUS_CALLING&&(this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}},{key:"timer_D",value:function(){Xl.debug("Timer D expired for transaction ".concat(this.id)),clearTimeout(this.B),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"sendACK",value:function(a){var c=this,e=new Cp.OutgoingRequest(Bo.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});e.setHeader("from",this.request.getHeader("from")),e.setHeader("via",this.request.getHeader("via")),e.setHeader("to",a.getHeader("to")),this.D=setTimeout(function(){c.timer_D()},is.TIMER_D),this.transport.send(e)}},{key:"cancel",value:function(a){if(this.state===ze.STATUS_PROCEEDING){var c=new Cp.OutgoingRequest(Bo.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});c.setHeader("from",this.request.getHeader("from")),c.setHeader("via",this.request.getHeader("via")),c.setHeader("to",this.request.getHeader("to")),a&&c.setHeader("reason",a),this.transport.send(c)}}},{key:"receiveResponse",value:function(a){var c=this,e=a.status_code;if(e>=100&&e<=199)switch(this.state){case ze.STATUS_CALLING:this.stateChanged(ze.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(a);break;case ze.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(a);break}else if(e>=200&&e<=299)switch(this.state){case ze.STATUS_CALLING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_ACCEPTED),this.M=setTimeout(function(){c.timer_M()},is.TIMER_M),this.eventHandlers.onReceiveResponse(a);break;case ze.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(a);break}else if(e>=300&&e<=699)switch(this.state){case ze.STATUS_CALLING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_COMPLETED),this.sendACK(a),this.eventHandlers.onReceiveResponse(a);break;case ze.STATUS_COMPLETED:this.sendACK(a);break}}},{key:"C",get:function(){return ze}}]),r}(zo),R0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e,_){var g;Po(this,r),g=n.call(this),g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.transport=c,g.request=e,g.eventHandlers=_;var d="SIP/2.0/".concat(c.via_transport);return d+=" ".concat(a.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",d),g}return Lo(r,[{key:"send",value:function(){this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){C0.debug("transport error occurred for transaction ".concat(this.id)),this.eventHandlers.onTransportError()}},{key:"C",get:function(){return ze}}]),r}(zo),$0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e){var _;return Po(this,r),_=n.call(this),_.type=ze.NON_INVITE_SERVER,_.id=e.via_branch,_.ua=a,_.transport=c,_.request=e,_.last_response="",e.server_transaction=li(_),_.state=ze.STATUS_TRYING,a.newTransaction(li(_)),_}return Lo(r,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_J",value:function(){Ip.debug("Timer J expired for transaction ".concat(this.id)),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,Ip.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.J),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"receiveResponse",value:function(a,c,e,_){var g=this;if(a===100)switch(this.state){case ze.STATUS_TRYING:this.stateChanged(ze.STATUS_PROCEEDING),this.transport.send(c)||this.onTransportError();break;case ze.STATUS_PROCEEDING:this.last_response=c,this.transport.send(c)?e&&e():(this.onTransportError(),_&&_());break}else if(a>=200&&a<=699)switch(this.state){case ze.STATUS_TRYING:case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_COMPLETED),this.last_response=c,this.J=setTimeout(function(){g.timer_J()},is.TIMER_J),this.transport.send(c)?e&&e():(this.onTransportError(),_&&_());break;case ze.STATUS_COMPLETED:break}}},{key:"C",get:function(){return ze}}]),r}(zo),x0=function(o){qo(r,o);var n=Ho(r);function r(a,c,e){var _;return Po(this,r),_=n.call(this),_.type=ze.INVITE_SERVER,_.id=e.via_branch,_.ua=a,_.transport=c,_.request=e,_.last_response="",e.server_transaction=li(_),_.state=ze.STATUS_PROCEEDING,a.newTransaction(li(_)),_.resendProvisionalTimer=null,e.reply(100),_}return Lo(r,[{key:"stateChanged",value:function(a){this.state=a,this.emit("stateChanged")}},{key:"timer_H",value:function(){Jl.debug("Timer H expired for transaction ".concat(this.id)),this.state===ze.STATUS_COMPLETED&&Jl.debug("ACK not received, dialog will be terminated"),this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_I",value:function(){this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_L",value:function(){Jl.debug("Timer L expired for transaction ".concat(this.id)),this.state===ze.STATUS_ACCEPTED&&(this.stateChanged(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,Jl.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(ze.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"resend_provisional",value:function(){this.transport.send(this.last_response)||this.onTransportError()}},{key:"receiveResponse",value:function(a,c,e,_){var g=this;if(a>=100&&a<=199)switch(this.state){case ze.STATUS_PROCEEDING:this.transport.send(c)||this.onTransportError(),this.last_response=c;break}if(a>100&&a<=199&&this.state===ze.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(function(){g.resend_provisional()},is.PROVISIONAL_RESPONSE_INTERVAL));else if(a>=200&&a<=299)switch(this.state){case ze.STATUS_PROCEEDING:this.stateChanged(ze.STATUS_ACCEPTED),this.last_response=c,this.L=setTimeout(function(){g.timer_L()},is.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case ze.STATUS_ACCEPTED:this.transport.send(c)?e&&e():(this.onTransportError(),_&&_());break}else if(a>=300&&a<=699)switch(this.state){case ze.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(c)?(this.stateChanged(ze.STATUS_COMPLETED),this.H=setTimeout(function(){g.timer_H()},is.TIMER_H),e&&e()):(this.onTransportError(),_&&_());break}}},{key:"C",get:function(){return ze}}]),r}(zo);function O0(o,n){var r=o._transactions,a;switch(n.method){case Bo.INVITE:if(a=r.ist[n.via_branch],a){switch(a.state){case ze.STATUS_PROCEEDING:a.transport.send(a.last_response);break;case ze.STATUS_ACCEPTED:break}return!0}break;case Bo.ACK:if(a=r.ist[n.via_branch],a){if(a.state===ze.STATUS_ACCEPTED)return!1;if(a.state===ze.STATUS_COMPLETED)return a.state=ze.STATUS_CONFIRMED,a.I=setTimeout(function(){a.timer_I()},is.TIMER_I),!0}else return!1;break;case Bo.CANCEL:return a=r.ist[n.via_branch],a?(n.reply_sl(200),a.state!==ze.STATUS_PROCEEDING):(n.reply_sl(481),!0);default:if(a=r.nist[n.via_branch],a){switch(a.state){case ze.STATUS_TRYING:break;case ze.STATUS_PROCEEDING:case ze.STATUS_COMPLETED:a.transport.send(a.last_response);break}return!0}break}}var Vo={C:ze,NonInviteClientTransaction:A0,InviteClientTransaction:I0,AckClientTransaction:R0,NonInviteServerTransaction:$0,InviteServerTransaction:x0,checkTransaction:O0};function k0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Rp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function D0(o,n,r){return n&&Rp(o.prototype,n),r&&Rp(o,r),o}var N0=bn,$p=dn,M0=b0,bc=Vo,U0=new N0("RequestSender"),wc={onRequestTimeout:function(){},onTransportError:function(){},onReceiveResponse:function(){},onAuthenticated:function(){}},jo=function(){function o(n,r,a){k0(this,o),this._ua=n,this._eventHandlers=a,this._method=r.method,this._request=r,this._auth=null,this._challenged=!1,this._staled=!1;for(var c in wc)Object.prototype.hasOwnProperty.call(wc,c)&&(this._eventHandlers[c]||(this._eventHandlers[c]=wc[c]));n.status===n.C.STATUS_USER_CLOSED&&(this._method!==$p.BYE||this._method!==$p.ACK)&&this._eventHandlers.onTransportError()}return D0(o,[{key:"send",value:function(){var n=this,r={onRequestTimeout:function(){n._eventHandlers.onRequestTimeout()},onTransportError:function(){n._eventHandlers.onTransportError()},onReceiveResponse:function(a){n._receiveResponse(a)}};switch(this._method){case"INVITE":this.clientTransaction=new bc.InviteClientTransaction(this._ua,this._ua.transport,this._request,r);break;case"ACK":this.clientTransaction=new bc.AckClientTransaction(this._ua,this._ua.transport,this._request,r);break;default:this.clientTransaction=new bc.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,r)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}},{key:"_receiveResponse",value:function(n){var r,a,c=n.status_code;if((c===401||c===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(n.status_code===401?(r=n.parseHeader("www-authenticate"),a="authorization"):(r=n.parseHeader("proxy-authenticate"),a="proxy-authorization"),!r){U0.debug("".concat(n.status_code," with wrong or missing challenge, cannot authenticate")),this._eventHandlers.onReceiveResponse(n);return}if(!this._challenged||!this._staled&&r.stale===!0){if(this._auth||(this._auth=new M0({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,r)){this._eventHandlers.onReceiveResponse(n);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),r.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)}}]),o}();function P0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function xp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function L0(o,n,r){return n&&xp(o.prototype,n),r&&xp(o,r),o}var q0=bn,Sc=Bn(),pa=dn,Op=Os,kp=jo,Go=new q0("Registrator"),Ql=10,H0=function(){function o(n,r){P0(this,o),this._reg_id=1,this._ua=n,this._transport=r,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=Sc.createRandomToken(22),this._cseq=0,this._to_uri=n.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 L0(o,[{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 r in n)if(Object.prototype.hasOwnProperty.call(n,r)){var a=n[r];this._extraContactParams+=";".concat(r),a&&(this._extraContactParams+="=".concat(a))}}},{key:"register",value:function(){var n=this;if(this._registering){Go.debug("Register request in progress...");return}var r=this._extraHeaders.slice();r.push("Contact: ".concat(this._contact,";expires=").concat(this._expires).concat(this._extraContactParams)),r.push("Expires: ".concat(this._expires));var a=new Op.OutgoingRequest(pa.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r),c=new kp(this._ua,a,{onRequestTimeout:function(){n._registrationFailure(null,pa.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._registrationFailure(null,pa.causes.CONNECTION_ERROR)},onAuthenticated:function(){n._cseq+=1},onReceiveResponse:function(e){if(e.cseq===n._cseq)switch(n._registrationTimer!==null&&(clearTimeout(n._registrationTimer),n._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):{if(n._registering=!1,!e.hasHeader("Contact")){Go.debug("no Contact header in response to REGISTER, response ignored");break}var _=e.headers.Contact.reduce(function(R,N){return R.concat(N.parsed)},[]),g=_.find(function(R){return n._sipInstance===R.getParam("+sip.instance")&&n._reg_id===parseInt(R.getParam("reg-id"))});if(g||(g=_.find(function(R){return R.uri.user===n._ua.contact.uri.user})),!g){Go.debug("no Contact header pointing to us, response ignored");break}var d=g.getParam("expires");!d&&e.hasHeader("expires")&&(d=e.getHeader("expires")),d||(d=n._expires),d=Number(d),d<Ql&&(d=Ql);var A=d>64?d*1e3/2+Math.floor((d/2-32)*1e3*Math.random()):d*1e3-5e3;n._registrationTimer=setTimeout(function(){n._registrationTimer=null,n._ua.listeners("registrationExpiring").length===0?n.register():n._ua.emit("registrationExpiring")},A),g.hasParam("temp-gruu")&&(n._ua.contact.temp_gruu=g.getParam("temp-gruu").replace(/"/g,"")),g.hasParam("pub-gruu")&&(n._ua.contact.pub_gruu=g.getParam("pub-gruu").replace(/"/g,"")),n._registered||(n._registered=!0,n._ua.registered({response:e}));break}case/^423$/.test(e.status_code):{e.hasHeader("min-expires")?(n._expires=Number(e.getHeader("min-expires")),n._expires<Ql&&(n._expires=Ql),n.register()):(Go.debug("423 response received for REGISTER without Min-Expires"),n._registrationFailure(e,pa.causes.SIP_FAILURE_CODE));break}default:{var S=Sc.sipErrorCause(e.status_code);n._registrationFailure(e,S)}}}});this._registering=!0,c.send()}},{key:"unregister",value:function(){var n=this,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._registered){Go.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);var a=this._extraHeaders.slice();r.all?a.push("Contact: *".concat(this._extraContactParams)):a.push("Contact: ".concat(this._contact,";expires=0").concat(this._extraContactParams)),a.push("Expires: 0");var c=new Op.OutgoingRequest(pa.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},a),e=new kp(this._ua,c,{onRequestTimeout:function(){n._unregistered(null,pa.causes.REQUEST_TIMEOUT)},onTransportError:function(){n._unregistered(null,pa.causes.CONNECTION_ERROR)},onAuthenticated:function(){n._cseq+=1},onReceiveResponse:function(_){switch(!0){case/^1[0-9]{2}$/.test(_.status_code):break;case/^2[0-9]{2}$/.test(_.status_code):n._unregistered(_);break;default:{var g=Sc.sipErrorCause(_.status_code);n._unregistered(_,g)}}}});e.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,r){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:r}))}},{key:"_unregistered",value:function(n,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:r||null})}},{key:"registered",get:function(){return this._registered}}]),o}();function z0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Dp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function F0(o,n,r){return n&&Dp(o.prototype,n),r&&Dp(o,r),o}var Ec=dn,Zl=Vo,B0=jo,Cc={onRequestTimeout:function(){},onTransportError:function(){},onSuccessResponse:function(){},onErrorResponse:function(){},onAuthenticated:function(){},onDialogError:function(){}},V0=function(){function o(n,r,a){z0(this,o),this._dialog=n,this._ua=n._ua,this._request=r,this._eventHandlers=a,this._reattempt=!1,this._reattemptTimer=null;for(var c in Cc)Object.prototype.hasOwnProperty.call(Cc,c)&&(this._eventHandlers[c]||(this._eventHandlers[c]=Cc[c]))}return F0(o,[{key:"send",value:function(){var n=this,r=new B0(this._ua,this._request,{onRequestTimeout:function(){n._eventHandlers.onRequestTimeout()},onTransportError:function(){n._eventHandlers.onTransportError()},onAuthenticated:function(c){n._eventHandlers.onAuthenticated(c)},onReceiveResponse:function(c){n._receiveResponse(c)}});if(r.send(),(this._request.method===Ec.INVITE||this._request.method===Ec.UPDATE&&this._request.body)&&r.clientTransaction.state!==Zl.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;var a=function c(){(r.clientTransaction.state===Zl.C.STATUS_ACCEPTED||r.clientTransaction.state===Zl.C.STATUS_COMPLETED||r.clientTransaction.state===Zl.C.STATUS_TERMINATED)&&(r.clientTransaction.removeListener("stateChanged",c),n._dialog.uac_pending_reply=!1)};r.clientTransaction.on("stateChanged",a)}}},{key:"_receiveResponse",value:function(n){var r=this;n.status_code===408||n.status_code===481?this._eventHandlers.onDialogError(n):n.method===Ec.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(){r._dialog.isTerminated()||(r._reattempt=!0,r.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}}]),o}();function j0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Np(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Mp(o,n,r){return n&&Np(o.prototype,n),r&&Np(o,r),o}var G0=bn,Up=Os,ui=dn,Wo=Vo,W0=V0,Ac=Bn(),Ic=new G0("Dialog"),ci={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3},K0=function(){Mp(o,null,[{key:"C",get:function(){return ci}}]);function o(n,r,a){var c=arguments.length>3&&arguments[3]!==void 0?arguments[3]:ci.STATUS_CONFIRMED;if(j0(this,o),this._owner=n,this._ua=n._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!r.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};r instanceof Up.IncomingResponse&&(c=r.status_code<200?ci.STATUS_EARLY:ci.STATUS_CONFIRMED);var e=r.parseHeader("contact");a==="UAS"?(this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=c,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri,this._remote_target=e.uri,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):a==="UAC"&&(this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=c,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri,this._remote_target=e.uri,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),Ic.debug("new ".concat(a," dialog created with status ").concat(this._state===ci.STATUS_EARLY?"EARLY":"CONFIRMED"))}return Mp(o,[{key:"isTerminated",value:function(){return this._status===ci.STATUS_TERMINATED}},{key:"update",value:function(n,r){this._state=ci.STATUS_CONFIRMED,Ic.debug("dialog ".concat(this._id.toString()," changed to CONFIRMED state")),r==="UAC"&&(this._route_set=n.getHeaders("record-route").reverse())}},{key:"terminate",value:function(){Ic.debug("dialog ".concat(this._id.toString()," deleted")),this._ua.destroyDialog(this),this._state=ci.STATUS_TERMINATED}},{key:"sendRequest",value:function(n){var r=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c=Ac.cloneArray(a.extraHeaders),e=Ac.cloneObject(a.eventHandlers),_=a.body||null,g=this._createRequest(n,c,_);e.onAuthenticated=function(){r._local_seqnum+=1};var d=new W0(this,g,e);return d.send(),g}},{key:"receiveRequest",value:function(n){this._checkInDialogRequest(n)&&(n.method===ui.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:n.method===ui.INVITE&&(this._ack_seqnum=n.cseq),this._owner.receiveRequest(n))}},{key:"_createRequest",value:function(n,r,a){r=Ac.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));var c=n===ui.CANCEL||n===ui.ACK?this._local_seqnum:this._local_seqnum+=1,e=new Up.OutgoingRequest(n,this._remote_target,this._ua,{cseq:c,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},r,a);return e}},{key:"_checkInDialogRequest",value:function(n){var r=this;if(!this._remote_seqnum)this._remote_seqnum=n.cseq;else if(n.cseq<this._remote_seqnum)if(n.method===ui.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===ui.INVITE||n.method===ui.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 c=function e(){(n.server_transaction.state===Wo.C.STATUS_ACCEPTED||n.server_transaction.state===Wo.C.STATUS_COMPLETED||n.server_transaction.state===Wo.C.STATUS_TERMINATED)&&(n.server_transaction.removeListener("stateChanged",e),r._uas_pending_reply=!1)};n.server_transaction.on("stateChanged",c)}n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Wo.C.STATUS_ACCEPTED&&(r._remote_target=n.parseHeader("contact").uri)})}else n.method===ui.NOTIFY&&n.hasHeader("contact")&&n.server_transaction.on("stateChanged",function(){n.server_transaction.state===Wo.C.STATUS_COMPLETED&&(r._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}}]),o}(),Rc={exports:{}};function eu(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?eu=function(n){return typeof n}:eu=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},eu(o)}function Y0(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Pp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function X0(o,n,r){return n&&Pp(o.prototype,n),r&&Pp(o,r),o}function J0(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&$c(o,n)}function $c(o,n){return $c=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},$c(o,n)}function Q0(o){var n=tw();return function(){var r=tu(o),a;if(n){var c=tu(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return Z0(this,a)}}function Z0(o,n){return n&&(eu(n)==="object"||typeof n=="function")?n:ew(o)}function ew(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function tw(){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 tu(o){return tu=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},tu(o)}var nw=Tn.EventEmitter,rw=bn,sw=dn,iw=ai,Lp=Bn(),aw=new rw("RTCSession:DTMF"),qp={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};Rc.exports=function(o){J0(r,o);var n=Q0(r);function r(a){var c;return Y0(this,r),c=n.call(this),c._session=a,c._direction=null,c._tone=null,c._duration=null,c._request=null,c}return X0(r,[{key:"send",value:function(a){var c=this,e=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 iw.InvalidStateError(this._session.status);var _=Lp.cloneArray(e.extraHeaders);if(this.eventHandlers=Lp.cloneObject(e.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=e.duration,_.push("Content-Type: application/dtmf-relay");var g="Signal=".concat(this._tone,`\r
|
|
47
|
+
`);g+="Duration=".concat(this._duration),this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(sw.INFO,{extraHeaders:_,eventHandlers:{onSuccessResponse:function(d){c.emit("succeeded",{originator:"remote",response:d})},onErrorResponse:function(d){c.eventHandlers.onFailed&&c.eventHandlers.onFailed(),c.emit("failed",{originator:"remote",response:d})},onRequestTimeout:function(){c._session.onRequestTimeout()},onTransportError:function(){c._session.onTransportError()},onDialogError:function(){c._session.onDialogError()}},body:g})}},{key:"init_incoming",value:function(a){var c=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,e=/^(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&&c.test(_[0])&&(this._tone=_[0].replace(c,"$2")),_.length>=2&&e.test(_[1])&&(this._duration=parseInt(_[1].replace(e,"$2"),10))}this._duration||(this._duration=qp.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:a}):aw.debug("invalid INFO DTMF received, discarded")}},{key:"tone",get:function(){return this._tone}},{key:"duration",get:function(){return this._duration}}]),r}(nw),Rc.exports.C=qp;var ow=Rc.exports;function nu(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?nu=function(n){return typeof n}:nu=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},nu(o)}function lw(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Hp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function uw(o,n,r){return n&&Hp(o.prototype,n),r&&Hp(o,r),o}function cw(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&xc(o,n)}function xc(o,n){return xc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},xc(o,n)}function dw(o){var n=_w();return function(){var r=ru(o),a;if(n){var c=ru(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return hw(this,a)}}function hw(o,n){return n&&(nu(n)==="object"||typeof n=="function")?n:pw(o)}function pw(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function _w(){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 ru(o){return ru=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},ru(o)}var fw=Tn.EventEmitter,mw=dn,gw=ai,yw=Bn(),vw=function(o){cw(r,o);var n=dw(r);function r(a){var c;return lw(this,r),c=n.call(this),c._session=a,c._direction=null,c._contentType=null,c._body=null,c}return uw(r,[{key:"send",value:function(a,c){var e=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 gw.InvalidStateError(this._session.status);this._contentType=a,this._body=c;var g=yw.cloneArray(_.extraHeaders);g.push("Content-Type: ".concat(a)),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(mw.INFO,{extraHeaders:g,eventHandlers:{onSuccessResponse:function(d){e.emit("succeeded",{originator:"remote",response:d})},onErrorResponse:function(d){e.emit("failed",{originator:"remote",response:d})},onTransportError:function(){e._session.onTransportError()},onRequestTimeout:function(){e._session.onRequestTimeout()},onDialogError:function(){e._session.onDialogError()}},body:c})}},{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}}]),r}(fw);function Tw(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function zp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function bw(o,n,r){return n&&zp(o.prototype,n),r&&zp(o,r),o}var ww=bn,Fp=dn,Sw=new ww("RTCSession:ReferNotifier"),Oc={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300},Ew=function(){function o(n,r,a){Tw(this,o),this._session=n,this._id=r,this._expires=a||Oc.expires,this._active=!0,this.notify(100)}return bw(o,[{key:"notify",value:function(n,r){if(Sw.debug("notify()"),this._active!==!1){r=r||Fp.REASON_PHRASE[n]||"";var a;n>=200?a="terminated;reason=noresource":a="active;expires=".concat(this._expires),this._session.sendRequest(Fp.NOTIFY,{extraHeaders:["Event: ".concat(Oc.event_type,";id=").concat(this._id),"Subscription-State: ".concat(a),"Content-Type: ".concat(Oc.body_type)],body:"SIP/2.0 ".concat(n," ").concat(r),eventHandlers:{onErrorResponse:function(){this._active=!1}}})}}}]),o}();function su(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?su=function(n){return typeof n}:su=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},su(o)}function Cw(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Bp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Aw(o,n,r){return n&&Bp(o.prototype,n),r&&Bp(o,r),o}function Iw(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&kc(o,n)}function kc(o,n){return kc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},kc(o,n)}function Rw(o){var n=Ow();return function(){var r=iu(o),a;if(n){var c=iu(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return $w(this,a)}}function $w(o,n){return n&&(su(n)==="object"||typeof n=="function")?n:xw(o)}function xw(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function Ow(){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 iu(o){return iu=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},iu(o)}var kw=Tn.EventEmitter,Dw=bn,Ko=dn,Nw=ss(),Vp=Bn(),_a=new Dw("RTCSession:ReferSubscriber"),Mw=function(o){Iw(r,o);var n=Rw(r);function r(a){var c;return Cw(this,r),c=n.call(this),c._id=null,c._session=a,c}return Aw(r,[{key:"sendRefer",value:function(a){var c=this,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};_a.debug("sendRefer()");var _=Vp.cloneArray(e.extraHeaders),g=Vp.cloneObject(e.eventHandlers);for(var d in g)Object.prototype.hasOwnProperty.call(g,d)&&this.on(d,g[d]);var A=null;e.replaces&&(A=e.replaces._request.call_id,A+=";to-tag=".concat(e.replaces._to_tag),A+=";from-tag=".concat(e.replaces._from_tag),A=encodeURIComponent(A));var S="Refer-To: <".concat(a).concat(A?"?Replaces=".concat(A):"",">");if(_.push(S),!_.some(function(H){return H.toLowerCase().startsWith("referred-by:")})){var R="Referred-By: <".concat(this._session._ua._configuration.uri._scheme,":").concat(this._session._ua._configuration.uri._user,"@").concat(this._session._ua._configuration.uri._host,">");_.push(R)}_.push("Contact: ".concat(this._session.contact));var N=this._session.sendRequest(Ko.REFER,{extraHeaders:_,eventHandlers:{onSuccessResponse:function(H){c._requestSucceeded(H)},onErrorResponse:function(H){c._requestFailed(H,Ko.causes.REJECTED)},onTransportError:function(){c._requestFailed(null,Ko.causes.CONNECTION_ERROR)},onRequestTimeout:function(){c._requestFailed(null,Ko.causes.REQUEST_TIMEOUT)},onDialogError:function(){c._requestFailed(null,Ko.causes.DIALOG_ERROR)}}});this._id=N.cseq}},{key:"receiveNotify",value:function(a){if(_a.debug("receiveNotify()"),!!a.body){var c=Nw.parse(a.body.trim().split(`\r
|
|
49
49
|
`,1)[0],"Status_Line");if(c===-1){_a.debug('receiveNotify() | error parsing NOTIFY body: "'.concat(a.body,'"'));return}switch(!0){case/^100$/.test(c.status_code):this.emit("trying",{request:a,status_line:c});break;case/^1[0-9]{2}$/.test(c.status_code):this.emit("progress",{request:a,status_line:c});break;case/^2[0-9]{2}$/.test(c.status_code):this.emit("accepted",{request:a,status_line:c});break;default:this.emit("failed",{request:a,status_line:c});break}}}},{key:"_requestSucceeded",value:function(a){_a.debug("REFER succeeded"),_a.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:a})}},{key:"_requestFailed",value:function(a,c){_a.debug("REFER failed"),_a.debug('emit "requestFailed"'),this.emit("requestFailed",{response:a||null,cause:c})}},{key:"id",get:function(){return this._id}}]),r}(kw);function au(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?au=function(n){return typeof n}:au=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},au(o)}function Ns(o,n){var r;if(typeof Symbol>"u"||o[Symbol.iterator]==null){if(Array.isArray(o)||(r=Uw(o))||n&&o&&typeof o.length=="number"){r&&(o=r);var a=0,c=function(){};return{s:c,n:function(){return a>=o.length?{done:!0}:{done:!1,value:o[a++]}},e:function(d){throw d},f:c}}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 e=!0,f=!1,g;return{s:function(){r=o[Symbol.iterator]()},n:function(){var d=r.next();return e=d.done,d},e:function(d){f=!0,g=d},f:function(){try{!e&&r.return!=null&&r.return()}finally{if(f)throw g}}}}function Uw(o,n){if(o){if(typeof o=="string")return jp(o,n);var r=Object.prototype.toString.call(o).slice(8,-1);if(r==="Object"&&o.constructor&&(r=o.constructor.name),r==="Map"||r==="Set")return Array.from(o);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return jp(o,n)}}function jp(o,n){(n==null||n>o.length)&&(n=o.length);for(var r=0,a=new Array(n);r<n;r++)a[r]=o[r];return a}function Pw(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Gp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Wp(o,n,r){return n&&Gp(o.prototype,n),r&&Gp(o,r),o}function Lw(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Dc(o,n)}function Dc(o,n){return Dc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Dc(o,n)}function qw(o){var n=Fw();return function(){var r=ou(o),a;if(n){var c=ou(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return Hw(this,a)}}function Hw(o,n){return n&&(au(n)==="object"||typeof n=="function")?n:zw(o)}function zw(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function Fw(){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 ou(o){return ou=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},ou(o)}var Bw=Tn.EventEmitter,Kp=nr,Vw=bn,Fe=dn,fa=ai,Yp=Vo,Xt=Bn(),Yo=Sp,jw=Os,lu=K0,Gw=jo,_r=ow,Xp=vw,Ww=Ew,Kw=Mw,Jp=oi(),ve=new Vw("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},uu=["audio","video"],Yw=function(o){Lw(r,o);var n=qw(r);Wp(r,null,[{key:"C",get:function(){return Ee}}]);function r(a){var c;return Pw(this,r),ve.debug("new"),c=n.call(this),c._id=null,c._ua=a,c._status=Ee.STATUS_NULL,c._dialog=null,c._earlyDialogs={},c._contact=null,c._from_tag=null,c._to_tag=null,c._connection=null,c._connectionPromiseQueue=Promise.resolve(),c._request=null,c._is_canceled=!1,c._cancel_reason="",c._is_confirmed=!1,c._late_sdp=!1,c._rtcOfferConstraints=null,c._rtcAnswerConstraints=null,c._localMediaStream=null,c._localMediaStreamLocallyGenerated=!1,c._rtcReady=!0,c._iceReady=!1,c._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},c._direction=null,c._local_identity=null,c._remote_identity=null,c._start_time=null,c._end_time=null,c._tones=null,c._audioMuted=!1,c._videoMuted=!1,c._localHold=!1,c._remoteHold=!1,c._sessionTimers={enabled:c._ua.configuration.session_timers,refreshMethod:c._ua.configuration.session_timers_refresh_method,defaultExpires:Fe.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},c._referSubscribers={},c._data={},c}return Wp(r,[{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 c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},e=arguments.length>2?arguments[2]:void 0;ve.debug("connect()");var f=a,g=Xt.cloneObject(c.eventHandlers),d=Xt.cloneArray(c.extraHeaders),A=Xt.cloneObject(c.mediaConstraints,{audio:!0,video:!0}),S=c.mediaStream||null,R=Xt.cloneObject(c.pcConfig,{iceServers:[]}),N=c.rtcConstraints||null,H=c.rtcOfferConstraints||null;if(this._rtcOfferConstraints=H,this._rtcAnswerConstraints=c.rtcAnswerConstraints||null,this._data=c.data||this._data,a===void 0)throw new TypeError("Not enough arguments");if(this._status!==Ee.STATUS_NULL)throw new fa.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new fa.NotSupportedError("WebRTC not supported");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(f));this._sessionTimers.enabled&&Xt.isDecimal(c.sessionTimersExpires)&&(c.sessionTimersExpires>=Fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=c.sessionTimersExpires:this._sessionTimers.defaultExpires=Fe.SESSION_EXPIRES);for(var W in g)Object.prototype.hasOwnProperty.call(g,W)&&this.on(W,g[W]);this._from_tag=Xt.newTag();var G=c.anonymous||!1,K={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:G,outbound:!0}),G?(K.from_display_name="Anonymous",K.from_uri=new Jp("sip","anonymous","anonymous.invalid"),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),d.push("Privacy: id")):c.fromUserName&&(K.from_uri=new Jp("sip",c.fromUserName,this._ua.configuration.uri.host),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),c.fromDisplayName&&(K.from_display_name=c.fromDisplayName),d.push("Contact: ".concat(this._contact)),d.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&d.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new jw.InitialOutgoingInviteRequest(a,this._ua,K,d),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(R,N),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,e&&e(this),this._newRTCSession("local",this._request),this._sendInitialRequest(A,H,S)}},{key:"init_incoming",value:function(a,c){var e=this;ve.debug("init_incoming()");var f,g=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;if(a.body&&g!=="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")&&(f=a.getHeader("expires")*1e3),a.to_tag=Xt.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),e._failed("local",null,Fe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),f&&(this._timers.expiresTimer=setTimeout(function(){e._status===Ee.STATUS_WAITING_FOR_ANSWER&&(a.reply(487),e._failed("system",null,Fe.causes.EXPIRES))},f)),this._direction="incoming",this._local_identity=a.to,this._remote_identity=a.from,c&&c(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,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ve.debug("answer()");var e=this._request,f=Xt.cloneArray(c.extraHeaders),g=Xt.cloneObject(c.mediaConstraints),d=c.mediaStream||null,A=Xt.cloneObject(c.pcConfig,{iceServers:[]}),S=c.rtcConstraints||null,R=c.rtcAnswerConstraints||null,N=Xt.cloneObject(c.rtcOfferConstraints),H,W=!1,G=!1,K=!1,ae=!1;if(this._rtcAnswerConstraints=R,this._rtcOfferConstraints=c.rtcOfferConstraints||null,this._data=c.data||this._data,this._direction!=="incoming")throw new fa.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==Ee.STATUS_WAITING_FOR_ANSWER)throw new fa.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Xt.isDecimal(c.sessionTimersExpires)&&(c.sessionTimersExpires>=Fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=c.sessionTimersExpires:this._sessionTimers.defaultExpires=Fe.SESSION_EXPIRES),this._status=Ee.STATUS_ANSWERED,!this._createDialog(e,"UAS")){e.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),f.unshift("Contact: ".concat(this._contact));var ee=e.parseSDP();Array.isArray(ee.media)||(ee.media=[ee.media]);var De=Ns(ee.media),X;try{for(De.s();!(X=De.n()).done;){var re=X.value;re.type==="audio"&&(W=!0,(!re.direction||re.direction==="sendrecv")&&(K=!0)),re.type==="video"&&(G=!0,(!re.direction||re.direction==="sendrecv")&&(ae=!0))}}catch(ue){De.e(ue)}finally{De.f()}if(d&&g.audio===!1){H=d.getAudioTracks();var be=Ns(H),Ne;try{for(be.s();!(Ne=be.n()).done;){var Q=Ne.value;d.removeTrack(Q)}}catch(ue){be.e(ue)}finally{be.f()}}if(d&&g.video===!1){H=d.getVideoTracks();var ce=Ns(H),me;try{for(ce.s();!(me=ce.n()).done;){var _e=me.value;d.removeTrack(_e)}}catch(ue){ce.e(ue)}finally{ce.f()}}!d&&g.audio===void 0&&(g.audio=K),!d&&g.video===void 0&&(g.video=ae),!d&&!W&&!N.offerToReceiveAudio&&(g.audio=!1),!d&&!G&&!N.offerToReceiveVideo&&(g.video=!1),this._createRTCConnection(A,S),Promise.resolve().then(function(){if(d)return d;if(g.audio||g.video)return a._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(g).catch(function(ue){throw a._status===Ee.STATUS_TERMINATED?new Error("terminated"):(e.reply(480),a._failed("local",null,Fe.causes.USER_DENIED_MEDIA_ACCESS),ve.warn('emit "getusermediafailed" [error:%o]',ue),a.emit("getusermediafailed",ue),new Error("getUserMedia() failed"))})}).then(function(ue){if(a._status===Ee.STATUS_TERMINATED)throw new Error("terminated");a._localMediaStream=ue,ue&&ue.getTracks().forEach(function(ye){a._connection.addTrack(ye,ue)})}).then(function(){if(!a._late_sdp){var ue={originator:"remote",type:"offer",sdp:e.body};ve.debug('emit "sdp"'),a.emit("sdp",ue);var ye=new RTCSessionDescription({type:"offer",sdp:ue.sdp});return a._connectionPromiseQueue=a._connectionPromiseQueue.then(function(){return a._connection.setRemoteDescription(ye)}).catch(function(Re){throw e.reply(488),a._failed("system",null,Fe.causes.WEBRTC_ERROR),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',Re),a.emit("peerconnection:setremotedescriptionfailed",Re),new Error("peerconnection.setRemoteDescription() failed")}),a._connectionPromiseQueue}}).then(function(){if(a._status===Ee.STATUS_TERMINATED)throw new Error("terminated");return a._connecting(e),a._late_sdp?a._createLocalDescription("offer",a._rtcOfferConstraints).catch(function(){throw e.reply(500),new Error("_createLocalDescription() failed")}):a._createLocalDescription("answer",R).catch(function(){throw e.reply(500),new Error("_createLocalDescription() failed")})}).then(function(ue){if(a._status===Ee.STATUS_TERMINATED)throw new Error("terminated");a._handleSessionTimersInIncomingRequest(e,f),e.reply(200,null,f,ue,function(){a._status=Ee.STATUS_WAITING_FOR_ACK,a._setInvite2xxTimer(e,ue),a._setACKTimer(),a._accepted("local")},function(){a._failed("system",null,Fe.causes.CONNECTION_ERROR)})}).catch(function(ue){a._status!==Ee.STATUS_TERMINATED&&ve.warn(ue)})}},{key:"terminate",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ve.debug("terminate()");var e=c.cause||Fe.causes.BYE,f=Xt.cloneArray(c.extraHeaders),g=c.body,d,A=c.status_code,S=c.reason_phrase;if(this._status===Ee.STATUS_TERMINATED)throw new fa.InvalidStateError(this._status);switch(this._status){case Ee.STATUS_NULL:case Ee.STATUS_INVITE_SENT:case Ee.STATUS_1XX_RECEIVED:if(ve.debug("canceling session"),A&&(A<200||A>=700))throw new TypeError("Invalid status_code: ".concat(A));A&&(S=S||Fe.REASON_PHRASE[A]||"",d="SIP ;cause=".concat(A,' ;text="').concat(S,'"')),this._status===Ee.STATUS_NULL||this._status===Ee.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=d):this._status===Ee.STATUS_1XX_RECEIVED&&this._request.cancel(d),this._status=Ee.STATUS_CANCELED,this._failed("local",null,Fe.causes.CANCELED);break;case Ee.STATUS_WAITING_FOR_ANSWER:case Ee.STATUS_ANSWERED:if(ve.debug("rejecting session"),A=A||480,A<300||A>=700)throw new TypeError("Invalid status_code: ".concat(A));this._request.reply(A,S,f,g),this._failed("local",null,Fe.causes.REJECTED);break;case Ee.STATUS_WAITING_FOR_ACK:case Ee.STATUS_CONFIRMED:if(ve.debug("terminating session"),S=c.reason_phrase||Fe.REASON_PHRASE[A]||"",A&&(A<200||A>=700))throw new TypeError("Invalid status_code: ".concat(A));if(A&&f.push("Reason: SIP ;cause=".concat(A,'; text="').concat(S,'"')),this._status===Ee.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Yp.C.STATUS_TERMINATED){var R=this._dialog;this.receiveRequest=function(N){var H=N.method;H===Fe.ACK&&(a.sendRequest(Fe.BYE,{extraHeaders:f,body:g}),R.terminate())},this._request.server_transaction.on("stateChanged",function(){a._request.server_transaction.state===Yp.C.STATUS_TERMINATED&&(a.sendRequest(Fe.BYE,{extraHeaders:f,body:g}),R.terminate())}),this._ended("local",null,e),this._dialog=R,this._ua.newDialog(R)}else this.sendRequest(Fe.BYE,{extraHeaders:f,body:g}),this._ended("local",null,e)}}},{key:"sendDTMF",value:function(a){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};ve.debug("sendDTMF() | tones: %s",a);var e=0,f=c.duration||null,g=c.interToneGap||null,d=c.transportType||Fe.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 fa.InvalidStateError(this._status);if(d!==Fe.DTMF_TRANSPORT.INFO&&d!==Fe.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(d));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(f&&!Xt.isDecimal(f))throw new TypeError("Invalid tone duration: ".concat(f));if(f?f<_r.C.MIN_DURATION?(ve.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(_r.C.MIN_DURATION," milliseconds")),f=_r.C.MIN_DURATION):f>_r.C.MAX_DURATION?(ve.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(_r.C.MAX_DURATION," milliseconds")),f=_r.C.MAX_DURATION):f=Math.abs(f):f=_r.C.DEFAULT_DURATION,c.duration=f,g&&!Xt.isDecimal(g))throw new TypeError("Invalid interToneGap: ".concat(g));if(g?g<_r.C.MIN_INTER_TONE_GAP?(ve.debug('"interToneGap" value is lower than the minimum allowed, setting it to '.concat(_r.C.MIN_INTER_TONE_GAP," milliseconds")),g=_r.C.MIN_INTER_TONE_GAP):g=Math.abs(g):g=_r.C.DEFAULT_INTER_TONE_GAP,d===Fe.DTMF_TRANSPORT.RFC2833){var A=this._getDTMFRTPSender();A&&(a=A.toneBuffer+a,A.insertDTMF(a,f,g));return}if(this._tones){this._tones+=a;return}this._tones=a,S.call(this);function S(){var R=this,N;if(this._status===Ee.STATUS_TERMINATED||!this._tones||e>=this._tones.length){this._tones=null;return}var H=this._tones[e];if(e+=1,H===",")N=2e3;else{var W=new _r(this);c.eventHandlers={onFailed:function(){R._tones=null}},W.send(H,c),N=f+g}setTimeout(S.bind(this),N)}}},{key:"sendInfo",value:function(a,c){var e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(ve.debug("sendInfo()"),this._status!==Ee.STATUS_CONFIRMED&&this._status!==Ee.STATUS_WAITING_FOR_ACK&&this._status!==Ee.STATUS_1XX_RECEIVED)throw new fa.InvalidStateError(this._status);var f=new Xp(this);f.send(a,c,e)}},{key:"mute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};ve.debug("mute()");var c=!1,e=!1;this._audioMuted===!1&&a.audio&&(c=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&a.video&&(e=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(c===!0||e===!0)&&this._onmute({audio:c,video:e})}},{key:"unmute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!0};ve.debug("unmute()");var c=!1,e=!1;this._audioMuted===!0&&a.audio&&(c=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&a.video&&(e=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(c===!0||e===!0)&&this._onunmute({audio:c,video:e})}},{key:"hold",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;if(ve.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 f={succeeded:function(){e&&e()},failed:function(){a.terminate({cause:Fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return c.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:f,extraHeaders:c.extraHeaders}):this._sendReinvite({eventHandlers:f,extraHeaders:c.extraHeaders}),!0}},{key:"unhold",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;if(ve.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 f={succeeded:function(){e&&e()},failed:function(){a.terminate({cause:Fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return c.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:f,extraHeaders:c.extraHeaders}):this._sendReinvite({eventHandlers:f,extraHeaders:c.extraHeaders}),!0}},{key:"renegotiate",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;ve.debug("renegotiate()");var f=c.rtcOfferConstraints||null;if(this._status!==Ee.STATUS_WAITING_FOR_ACK&&this._status!==Ee.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;var g={succeeded:function(){e&&e()},failed:function(){a.terminate({cause:Fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),c.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:g,rtcOfferConstraints:f,extraHeaders:c.extraHeaders}):this._sendReinvite({eventHandlers:g,rtcOfferConstraints:f,extraHeaders:c.extraHeaders}),!0}},{key:"refer",value:function(a,c){var e=this;ve.debug("refer()");var f=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(f));var g=new Kw(this);g.sendRefer(a,c);var d=g.id;return this._referSubscribers[d]=g,g.on("requestFailed",function(){delete e._referSubscribers[d]}),g.on("accepted",function(){delete e._referSubscribers[d]}),g.on("failed",function(){delete e._referSubscribers[d]}),g}},{key:"sendRequest",value:function(a,c){return ve.debug("sendRequest()"),this._dialog.sendRequest(a,c)}},{key:"receiveRequest",value:function(a){var c=this;if(ve.debug("receiveRequest()"),a.method===Fe.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,Fe.causes.CANCELED));else switch(a.method){case Fe.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:Fe.causes.MISSING_SDP,status_code:400});break}var e={originator:"remote",type:"answer",sdp:a.body};ve.debug('emit "sdp"'),this.emit("sdp",e);var f=new RTCSessionDescription({type:"answer",sdp:e.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return c._connection.setRemoteDescription(f)}).then(function(){c._is_confirmed||c._confirmed("remote",a)}).catch(function(d){c.terminate({cause:Fe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',d),c.emit("peerconnection:setremotedescriptionfailed",d)})}else this._is_confirmed||this._confirmed("remote",a);break;case Fe.BYE:this._status===Ee.STATUS_CONFIRMED||this._status===Ee.STATUS_WAITING_FOR_ACK?(a.reply(200),this._ended("remote",a,Fe.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,Fe.causes.BYE)):a.reply(403,"Wrong Status");break;case Fe.INVITE:this._status===Ee.STATUS_CONFIRMED?a.hasHeader("replaces")?this._receiveReplaces(a):this._receiveReinvite(a):a.reply(403,"Wrong Status");break;case Fe.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 g=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;g&&g.match(/^application\/dtmf-relay/i)?new _r(this).init_incoming(a):g!==void 0?new Xp(this).init_incoming(a):a.reply(415)}else a.reply(403,"Wrong Status");break;case Fe.UPDATE:this._status===Ee.STATUS_CONFIRMED?this._receiveUpdate(a):a.reply(403,"Wrong Status");break;case Fe.REFER:this._status===Ee.STATUS_CONFIRMED?this._receiveRefer(a):a.reply(403,"Wrong Status");break;case Fe.NOTIFY:this._status===Ee.STATUS_CONFIRMED?this._receiveNotify(a):a.reply(403,"Wrong Status");break;default:a.reply(501)}}},{key:"onTransportError",value:function(){ve.warn("onTransportError()"),this._status!==Ee.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Fe.causes.CONNECTION_ERROR,cause:Fe.causes.CONNECTION_ERROR})}},{key:"onRequestTimeout",value:function(){ve.warn("onRequestTimeout()"),this._status!==Ee.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Fe.causes.REQUEST_TIMEOUT,cause:Fe.causes.REQUEST_TIMEOUT})}},{key:"onDialogError",value:function(){ve.warn("onDialogError()"),this._status!==Ee.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Fe.causes.DIALOG_ERROR,cause:Fe.causes.DIALOG_ERROR})}},{key:"newDTMF",value:function(a){ve.debug("newDTMF()"),this.emit("newDTMF",a)}},{key:"newInfo",value:function(a){ve.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?(ve.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(ve.debug("_isReadyToReOffer() | session not established yet"),!1):(ve.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(ve.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(ve.debug("close() | closing local MediaStream"),Xt.closeMediaStream(this._localMediaStream)),this._status!==Ee.STATUS_TERMINATED){if(this._status=Ee.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(f){ve.warn("close() | error closing the RTCPeerConnection: %o",f)}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 c in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,c)&&(this._earlyDialogs[c].terminate(),delete this._earlyDialogs[c]);for(var e in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,e)&&delete this._referSubscribers[e];this._ua.destroyRTCSession(this)}}},{key:"_setInvite2xxTimer",value:function(a,c){var e=Yo.T1;function f(){this._status===Ee.STATUS_WAITING_FOR_ACK&&(a.reply(200,null,["Contact: ".concat(this._contact)],c),e<Yo.T2&&(e=e*2,e>Yo.T2&&(e=Yo.T2)),this._timers.invite2xxTimer=setTimeout(f.bind(this),e))}this._timers.invite2xxTimer=setTimeout(f.bind(this),e)}},{key:"_setACKTimer",value:function(){var a=this;this._timers.ackTimer=setTimeout(function(){a._status===Ee.STATUS_WAITING_FOR_ACK&&(ve.debug("no ACK received, terminating the session"),clearTimeout(a._timers.invite2xxTimer),a.sendRequest(Fe.BYE),a._ended("remote",null,Fe.causes.NO_ACK))},Yo.TIMER_H)}},{key:"_createRTCConnection",value:function(a,c){var e=this;this._connection=new RTCPeerConnection(a,c),this._connection.addEventListener("iceconnectionstatechange",function(){var f=e._connection.iceConnectionState;f==="failed"&&e.terminate({cause:Fe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:Fe.causes.RTP_TIMEOUT})}),ve.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(a,c){var e=this;if(ve.debug("createLocalDescription()"),a!=="offer"&&a!=="answer")throw new Error('createLocalDescription() | invalid type "'.concat(a,'"'));var f=this._connection;return this._rtcReady=!1,Promise.resolve().then(function(){return a==="offer"?f.createOffer(c).catch(function(g){return ve.warn('emit "peerconnection:createofferfailed" [error:%o]',g),e.emit("peerconnection:createofferfailed",g),Promise.reject(g)}):f.createAnswer(c).catch(function(g){return ve.warn('emit "peerconnection:createanswerfailed" [error:%o]',g),e.emit("peerconnection:createanswerfailed",g),Promise.reject(g)})}).then(function(g){return f.setLocalDescription(g).catch(function(d){return e._rtcReady=!0,ve.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',d),e.emit("peerconnection:setlocaldescriptionfailed",d),Promise.reject(d)})}).then(function(){var g=c&&c.iceRestart;if(f.iceGatheringState==="complete"&&!g||f.iceGatheringState==="gathering"&&e._iceReady){e._rtcReady=!0;var d={originator:"local",type:a,sdp:f.localDescription.sdp};return ve.debug('emit "sdp"'),e.emit("sdp",d),Promise.resolve(d.sdp)}return new Promise(function(A){var S=!1,R,N;e._iceReady=!1;var H=function(){f.removeEventListener("icecandidate",R),f.removeEventListener("icegatheringstatechange",N),S=!0,e._rtcReady=!0,e._iceReady=!0;var W={originator:"local",type:a,sdp:f.localDescription.sdp};ve.debug('emit "sdp"'),e.emit("sdp",W),A(W.sdp)};f.addEventListener("icecandidate",R=function(W){var G=W.candidate;G?e.emit("icecandidate",{candidate:G,ready:H}):S||H()}),f.addEventListener("icegatheringstatechange",N=function(){f.iceGatheringState==="complete"&&!S&&H()})})})}},{key:"_createDialog",value:function(a,c,e){var f=c==="UAS"?a.to_tag:a.from_tag,g=c==="UAS"?a.from_tag:a.to_tag,d=a.call_id+f+g,A=this._earlyDialogs[d];if(e)return A?!0:(A=new lu(this,a,c,lu.C.STATUS_EARLY),A.error?(ve.debug(A.error),this._failed("remote",a,Fe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[d]=A,!0));if(this._from_tag=a.from_tag,this._to_tag=a.to_tag,A)return A.update(a,c),this._dialog=A,delete this._earlyDialogs[d],!0;var S=new lu(this,a,c);return S.error?(ve.debug(S.error),this._failed("remote",a,Fe.causes.INTERNAL_ERROR),!1):(this._dialog=S,!0)}},{key:"_receiveReinvite",value:function(a){var c=this;ve.debug("receiveReinvite()");var e=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,f={request:a,callback:void 0,reject:d.bind(this)},g=!1;function d(){var S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};g=!0;var R=S.status_code||403,N=S.reason_phrase||"",H=Xt.cloneArray(S.extraHeaders);if(this._status!==Ee.STATUS_CONFIRMED)return!1;if(R<300||R>=700)throw new TypeError("Invalid status_code: ".concat(R));a.reply(R,N,H)}if(this.emit("reinvite",f),g)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 c._createLocalDescription("offer",c._rtcOfferConstraints)}).then(function(S){A.call(c,S)}).catch(function(){a.reply(500)});return}if(e!=="application/sdp"){ve.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(S){c._status!==Ee.STATUS_TERMINATED&&A.call(c,S)}).catch(function(S){ve.warn(S)});function A(S){var R=this,N=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,N),this._late_sdp&&(S=this._mangleOffer(S)),a.reply(200,null,N,S,function(){R._status=Ee.STATUS_WAITING_FOR_ACK,R._setInvite2xxTimer(a,S),R._setACKTimer()}),typeof f.callback=="function"&&f.callback()}}},{key:"_receiveUpdate",value:function(a){var c=this;ve.debug("receiveUpdate()");var e=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,f={request:a,callback:void 0,reject:d.bind(this)},g=!1;function d(){var S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};g=!0;var R=S.status_code||403,N=S.reason_phrase||"",H=Xt.cloneArray(S.extraHeaders);if(this._status!==Ee.STATUS_CONFIRMED)return!1;if(R<300||R>=700)throw new TypeError("Invalid status_code: ".concat(R));a.reply(R,N,H)}if(this.emit("update",f),g)return;if(!a.body){A.call(this,null);return}if(e!=="application/sdp"){ve.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(S){c._status!==Ee.STATUS_TERMINATED&&A.call(c,S)}).catch(function(S){ve.warn(S)});function A(S){var R=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,R),a.reply(200,null,R,S),typeof f.callback=="function"&&f.callback()}}},{key:"_processInDialogSdpOffer",value:function(a){var c=this;ve.debug("_processInDialogSdpOffer()");var e=a.parseSDP(),f=!1,g=Ns(e.media),d;try{for(g.s();!(d=g.n()).done;){var A=d.value;if(uu.indexOf(A.type)!==-1){var S=A.direction||e.direction||"sendrecv";if(S==="sendonly"||S==="inactive")f=!0;else{f=!1;break}}}}catch(H){g.e(H)}finally{g.f()}var R={originator:"remote",type:"offer",sdp:a.body};ve.debug('emit "sdp"'),this.emit("sdp",R);var N=new RTCSessionDescription({type:"offer",sdp:R.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(c._status===Ee.STATUS_TERMINATED)throw new Error("terminated");return c._connection.setRemoteDescription(N).catch(function(H){throw a.reply(488),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',H),c.emit("peerconnection:setremotedescriptionfailed",H),H})}).then(function(){if(c._status===Ee.STATUS_TERMINATED)throw new Error("terminated");c._remoteHold===!0&&f===!1?(c._remoteHold=!1,c._onunhold("remote")):c._remoteHold===!1&&f===!0&&(c._remoteHold=!0,c._onhold("remote"))}).then(function(){if(c._status===Ee.STATUS_TERMINATED)throw new Error("terminated");return c._createLocalDescription("answer",c._rtcAnswerConstraints).catch(function(H){throw a.reply(500),ve.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',H),H})}).catch(function(H){ve.warn("_processInDialogSdpOffer() failed [error: %o]",H)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(a){var c=this;if(ve.debug("receiveRefer()"),!a.refer_to){ve.debug("no Refer-To header field present in REFER"),a.reply(400);return}if(a.refer_to.uri.scheme!==Fe.SIP){ve.debug("Refer-To header field points to a non-SIP URI scheme"),a.reply(416);return}a.reply(202);var e=new Ww(this,a.cseq);ve.debug('emit "refer"'),this.emit("refer",{request:a,accept:function(d,A){f.call(c,d,A)},reject:function(){g.call(c)}});function f(d){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(d=typeof d=="function"?d:null,this._status!==Ee.STATUS_WAITING_FOR_ACK&&this._status!==Ee.STATUS_CONFIRMED)return!1;var S=new r(this._ua);if(S.on("progress",function(N){var H=N.response;e.notify(H.status_code,H.reason_phrase)}),S.on("accepted",function(N){var H=N.response;e.notify(H.status_code,H.reason_phrase)}),S.on("_failed",function(N){var H=N.message,W=N.cause;H?e.notify(H.status_code,H.reason_phrase):e.notify(487,W)}),a.refer_to.uri.hasHeader("replaces")){var R=decodeURIComponent(a.refer_to.uri.getHeader("replaces"));A.extraHeaders=Xt.cloneArray(A.extraHeaders),A.extraHeaders.push("Replaces: ".concat(R))}S.connect(a.refer_to.uri.toAor(),A,d)}function g(){e.notify(603)}}},{key:"_receiveNotify",value:function(a){switch(ve.debug("receiveNotify()"),a.event||a.reply(400),a.event.event){case"refer":{var c,e;if(a.event.params&&a.event.params.id)c=a.event.params.id,e=this._referSubscribers[c];else if(Object.keys(this._referSubscribers).length===1)e=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{a.reply(400,"Missing event id parameter");return}if(!e){a.reply(481,"Subscription does not exist");return}e.receiveNotify(a),a.reply(200);break}default:a.reply(489)}}},{key:"_receiveReplaces",value:function(a){var c=this;ve.debug("receiveReplaces()");function e(g){var d=this;if(this._status!==Ee.STATUS_WAITING_FOR_ACK&&this._status!==Ee.STATUS_CONFIRMED)return!1;var A=new r(this._ua);A.on("confirmed",function(){d.terminate()}),A.init_incoming(a,g)}function f(){ve.debug("Replaced INVITE rejected by the user"),a.reply(486)}this.emit("replaces",{request:a,accept:function(g){e.call(c,g)},reject:function(){f.call(c)}})}},{key:"_sendInitialRequest",value:function(a,c,e){var f=this,g=new Gw(this._ua,this._request,{onRequestTimeout:function(){f.onRequestTimeout()},onTransportError:function(){f.onTransportError()},onAuthenticated:function(d){f._request=d},onReceiveResponse:function(d){f._receiveInviteResponse(d)}});Promise.resolve().then(function(){if(e)return e;if(a.audio||a.video)return f._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(function(d){throw f._status===Ee.STATUS_TERMINATED?new Error("terminated"):(f._failed("local",null,Fe.causes.USER_DENIED_MEDIA_ACCESS),ve.warn('emit "getusermediafailed" [error:%o]',d),f.emit("getusermediafailed",d),d)})}).then(function(d){if(f._status===Ee.STATUS_TERMINATED)throw new Error("terminated");return f._localMediaStream=d,d&&d.getTracks().forEach(function(A){f._connection.addTrack(A,d)}),f._connecting(f._request),f._createLocalDescription("offer",c).catch(function(A){throw f._failed("local",null,Fe.causes.WEBRTC_ERROR),A})}).then(function(d){if(f._is_canceled||f._status===Ee.STATUS_TERMINATED)throw new Error("terminated");f._request.body=d,f._status=Ee.STATUS_INVITE_SENT,ve.debug('emit "sending" [request:%o]',f._request),f.emit("sending",{request:f._request}),g.send()}).catch(function(d){f._status!==Ee.STATUS_TERMINATED&&ve.warn(d)})}},{key:"_getDTMFRTPSender",value:function(){var a=this._connection.getSenders().find(function(c){return c.track&&c.track.kind==="audio"});if(!(a&&a.dtmf)){ve.warn("sendDTMF() | no local audio track to send DTMF with");return}return a.dtmf}},{key:"_receiveInviteResponse",value:function(a){var c=this;if(ve.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(Fe.ACK);return}else{var e=new lu(this,a,"UAC");if(e.error!==void 0){ve.debug(e.error);return}this.sendRequest(Fe.ACK),this.sendRequest(Fe.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){ve.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 f={originator:"remote",type:"answer",sdp:a.body};ve.debug('emit "sdp"'),this.emit("sdp",f);var g=new RTCSessionDescription({type:"answer",sdp:f.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return c._connection.setRemoteDescription(g)}).then(function(){return c._progress("remote",a)}).catch(function(R){ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),c.emit("peerconnection:setremotedescriptionfailed",R)});break}case/^2[0-9]{2}$/.test(a.status_code):{if(this._status=Ee.STATUS_CONFIRMED,!a.body){this._acceptAndTerminate(a,400,Fe.causes.MISSING_SDP),this._failed("remote",a,Fe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(a,"UAC"))break;var d={originator:"remote",type:"answer",sdp:a.body};ve.debug('emit "sdp"'),this.emit("sdp",d);var A=new RTCSessionDescription({type:"answer",sdp:d.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(c._connection.signalingState==="stable")return c._connection.createOffer(c._rtcOfferConstraints).then(function(R){return c._connection.setLocalDescription(R)}).catch(function(R){c._acceptAndTerminate(a,500,R.toString()),c._failed("local",a,Fe.causes.WEBRTC_ERROR)})}).then(function(){c._connection.setRemoteDescription(A).then(function(){c._handleSessionTimersInIncomingResponse(a),c._accepted("remote",a),c.sendRequest(Fe.ACK),c._confirmed("local",null)}).catch(function(R){c._acceptAndTerminate(a,488,"Not Acceptable Here"),c._failed("remote",a,Fe.causes.BAD_MEDIA_DESCRIPTION),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),c.emit("peerconnection:setremotedescriptionfailed",R)})});break}default:{var S=Xt.sipErrorCause(a.status_code);this._failed("remote",a,S)}}}},{key:"_sendReinvite",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ve.debug("sendReinvite()");var e=Xt.cloneArray(c.extraHeaders),f=Xt.cloneObject(c.eventHandlers),g=c.rtcOfferConstraints||this._rtcOfferConstraints||null,d=!1;e.push("Contact: ".concat(this._contact)),e.push("Content-Type: application/sdp"),this._sessionTimers.running&&e.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",g)}).then(function(R){R=a._mangleOffer(R);var N={originator:"local",type:"offer",sdp:R};ve.debug('emit "sdp"'),a.emit("sdp",N),a.sendRequest(Fe.INVITE,{extraHeaders:e,body:R,eventHandlers:{onSuccessResponse:function(H){A.call(a,H),d=!0},onErrorResponse:function(H){S.call(a,H)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){S()});function A(R){var N=this;if(this._status!==Ee.STATUS_TERMINATED&&(this.sendRequest(Fe.ACK),!d)){if(this._handleSessionTimersInIncomingResponse(R),R.body){if(!R.hasHeader("Content-Type")||R.getHeader("Content-Type").toLowerCase()!=="application/sdp"){S.call(this);return}}else{S.call(this);return}var H={originator:"remote",type:"answer",sdp:R.body};ve.debug('emit "sdp"'),this.emit("sdp",H);var W=new RTCSessionDescription({type:"answer",sdp:H.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return N._connection.setRemoteDescription(W)}).then(function(){f.succeeded&&f.succeeded(R)}).catch(function(G){S.call(N),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',G),N.emit("peerconnection:setremotedescriptionfailed",G)})}}function S(R){f.failed&&f.failed(R)}}},{key:"_sendUpdate",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ve.debug("sendUpdate()");var e=Xt.cloneArray(c.extraHeaders),f=Xt.cloneObject(c.eventHandlers),g=c.rtcOfferConstraints||this._rtcOfferConstraints||null,d=c.sdpOffer||!1,A=!1;e.push("Contact: ".concat(this._contact)),this._sessionTimers.running&&e.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),d?(e.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",g)}).then(function(N){N=a._mangleOffer(N);var H={originator:"local",type:"offer",sdp:N};ve.debug('emit "sdp"'),a.emit("sdp",H),a.sendRequest(Fe.UPDATE,{extraHeaders:e,body:N,eventHandlers:{onSuccessResponse:function(W){S.call(a,W),A=!0},onErrorResponse:function(W){R.call(a,W)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){R.call(a)})):this.sendRequest(Fe.UPDATE,{extraHeaders:e,eventHandlers:{onSuccessResponse:function(N){S.call(a,N)},onErrorResponse:function(N){R.call(a,N)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}});function S(N){var H=this;if(this._status!==Ee.STATUS_TERMINATED&&!A)if(this._handleSessionTimersInIncomingResponse(N),d){if(N.body){if(!N.hasHeader("Content-Type")||N.getHeader("Content-Type").toLowerCase()!=="application/sdp"){R.call(this);return}}else{R.call(this);return}var W={originator:"remote",type:"answer",sdp:N.body};ve.debug('emit "sdp"'),this.emit("sdp",W);var G=new RTCSessionDescription({type:"answer",sdp:W.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return H._connection.setRemoteDescription(G)}).then(function(){f.succeeded&&f.succeeded(N)}).catch(function(K){R.call(H),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',K),H.emit("peerconnection:setremotedescriptionfailed",K)})}else f.succeeded&&f.succeeded(N)}function R(N){f.failed&&f.failed(N)}}},{key:"_acceptAndTerminate",value:function(a,c,e){ve.debug("acceptAndTerminate()");var f=[];c&&(e=e||Fe.REASON_PHRASE[c]||"",f.push("Reason: SIP ;cause=".concat(c,'; text="').concat(e,'"'))),(this._dialog||this._createDialog(a,"UAC"))&&(this.sendRequest(Fe.ACK),this.sendRequest(Fe.BYE,{extraHeaders:f})),this._status=Ee.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(a){if(!this._localHold&&!this._remoteHold)return a;if(a=Kp.parse(a),this._localHold&&!this._remoteHold){ve.debug("mangleOffer() | me on hold, mangling offer");var c=Ns(a.media),e;try{for(c.s();!(e=c.n()).done;){var f=e.value;uu.indexOf(f.type)!==-1&&(f.direction?f.direction==="sendrecv"?f.direction="sendonly":f.direction==="recvonly"&&(f.direction="inactive"):f.direction="sendonly")}}catch(H){c.e(H)}finally{c.f()}}else if(this._localHold&&this._remoteHold){ve.debug("mangleOffer() | both on hold, mangling offer");var g=Ns(a.media),d;try{for(g.s();!(d=g.n()).done;){var A=d.value;uu.indexOf(A.type)!==-1&&(A.direction="inactive")}}catch(H){g.e(H)}finally{g.f()}}else if(this._remoteHold){ve.debug("mangleOffer() | remote on hold, mangling offer");var S=Ns(a.media),R;try{for(S.s();!(R=S.n()).done;){var N=R.value;uu.indexOf(N.type)!==-1&&(N.direction?N.direction==="sendrecv"?N.direction="recvonly":N.direction==="recvonly"&&(N.direction="inactive"):N.direction="recvonly")}}catch(H){S.e(H)}finally{S.f()}}return Kp.write(a)}},{key:"_setLocalMediaStatus",value:function(){var a=!0,c=!0;(this._localHold||this._remoteHold)&&(a=!1,c=!1),this._audioMuted&&(a=!1),this._videoMuted&&(c=!1),this._toggleMuteAudio(!a),this._toggleMuteVideo(!c)}},{key:"_handleSessionTimersInIncomingRequest",value:function(a,c){if(this._sessionTimers.enabled){var e;a.session_expires&&a.session_expires>=Fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,e=a.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,e="uas"),c.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(e)),this._sessionTimers.refresher=e==="uas",this._runSessionTimer()}}},{key:"_handleSessionTimersInIncomingResponse",value:function(a){if(this._sessionTimers.enabled){var c;a.session_expires&&a.session_expires>=Fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,c=a.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,c="uac"),this._sessionTimers.refresher=c==="uac",this._runSessionTimer()}}},{key:"_runSessionTimer",value:function(){var a=this,c=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()&&(ve.debug("runSessionTimer() | sending session refresh request"),a._sessionTimers.refreshMethod===Fe.UPDATE?a._sendUpdate():a._sendReinvite())},c*500):this._sessionTimers.timer=setTimeout(function(){a._status!==Ee.STATUS_TERMINATED&&(ve.warn("runSessionTimer() | timer expired, terminating the session"),a.terminate({cause:Fe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},c*1100)}},{key:"_toggleMuteAudio",value:function(a){var c=this._connection.getSenders().filter(function(d){return d.track&&d.track.kind==="audio"}),e=Ns(c),f;try{for(e.s();!(f=e.n()).done;){var g=f.value;g.track.enabled=!a}}catch(d){e.e(d)}finally{e.f()}}},{key:"_toggleMuteVideo",value:function(a){var c=this._connection.getSenders().filter(function(d){return d.track&&d.track.kind==="video"}),e=Ns(c),f;try{for(e.s();!(f=e.n()).done;){var g=f.value;g.track.enabled=!a}}catch(d){e.e(d)}finally{e.f()}}},{key:"_newRTCSession",value:function(a,c){ve.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:a,session:this,request:c})}},{key:"_connecting",value:function(a){ve.debug("session connecting"),ve.debug('emit "connecting"'),this.emit("connecting",{request:a})}},{key:"_progress",value:function(a,c){ve.debug("session progress"),ve.debug('emit "progress"'),this.emit("progress",{originator:a,response:c||null})}},{key:"_accepted",value:function(a,c){ve.debug("session accepted"),this._start_time=new Date,ve.debug('emit "accepted"'),this.emit("accepted",{originator:a,response:c||null})}},{key:"_confirmed",value:function(a,c){ve.debug("session confirmed"),this._is_confirmed=!0,ve.debug('emit "confirmed"'),this.emit("confirmed",{originator:a,ack:c||null})}},{key:"_ended",value:function(a,c,e){ve.debug("session ended"),this._end_time=new Date,this._close(),ve.debug('emit "ended"'),this.emit("ended",{originator:a,message:c||null,cause:e})}},{key:"_failed",value:function(a,c,e){ve.debug("session failed"),ve.debug('emit "_failed"'),this.emit("_failed",{originator:a,message:c||null,cause:e}),this._close(),ve.debug('emit "failed"'),this.emit("failed",{originator:a,message:c||null,cause:e})}},{key:"_onhold",value:function(a){ve.debug("session onhold"),this._setLocalMediaStatus(),ve.debug('emit "hold"'),this.emit("hold",{originator:a})}},{key:"_onunhold",value:function(a){ve.debug("session onunhold"),this._setLocalMediaStatus(),ve.debug('emit "unhold"'),this.emit("unhold",{originator:a})}},{key:"_onmute",value:function(a){var c=a.audio,e=a.video;ve.debug("session onmute"),this._setLocalMediaStatus(),ve.debug('emit "muted"'),this.emit("muted",{audio:c,video:e})}},{key:"_onunmute",value:function(a){var c=a.audio,e=a.video;ve.debug("session onunmute"),this._setLocalMediaStatus(),ve.debug('emit "unmuted"'),this.emit("unmuted",{audio:c,video:e})}},{key:"C",get:function(){return Ee}},{key:"causes",get:function(){return Fe.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}}]),r}(Bw);function cu(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?cu=function(n){return typeof n}:cu=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},cu(o)}function Xw(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Qp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Jw(o,n,r){return n&&Qp(o.prototype,n),r&&Qp(o,r),o}function Qw(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Nc(o,n)}function Nc(o,n){return Nc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Nc(o,n)}function Zw(o){var n=nS();return function(){var r=du(o),a;if(n){var c=du(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return eS(this,a)}}function eS(o,n){return n&&(cu(n)==="object"||typeof n=="function")?n:tS(o)}function tS(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function nS(){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 du(o){return du=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},du(o)}var rS=Tn.EventEmitter,sS=bn,Mc=dn,iS=Os,Xo=Bn(),aS=jo,Zp=ai,oS=oi(),hu=new sS("Message"),lS=function(o){Qw(r,o);var n=Zw(r);function r(a){var c;return Xw(this,r),c=n.call(this),c._ua=a,c._request=null,c._closed=!1,c._direction=null,c._local_identity=null,c._remote_identity=null,c._is_replied=!1,c._data={},c}return Jw(r,[{key:"send",value:function(a,c){var e=this,f=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},g=a;if(a===void 0||c===void 0)throw new TypeError("Not enough arguments");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(g));var d=Xo.cloneArray(f.extraHeaders),A=Xo.cloneObject(f.eventHandlers),S=f.contentType||"text/plain",R={};f.fromUserName&&(R.from_uri=new oS("sip",f.fromUserName,this._ua.configuration.uri.host),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),f.fromDisplayName&&(R.from_display_name=f.fromDisplayName);for(var N in A)Object.prototype.hasOwnProperty.call(A,N)&&this.on(N,A[N]);d.push("Content-Type: ".concat(S)),this._request=new iS.OutgoingRequest(Mc.MESSAGE,a,this._ua,R,d),c&&(this._request.body=c);var H=new aS(this._ua,this._request,{onRequestTimeout:function(){e._onRequestTimeout()},onTransportError:function(){e._onTransportError()},onReceiveResponse:function(W){e._receiveResponse(W)}});this._newMessage("local",this._request),H.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]:{},c=Xo.cloneArray(a.extraHeaders),e=a.body;if(this._direction!=="incoming")throw new Zp.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,c,e)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},c=a.status_code||480,e=a.reason_phrase,f=Xo.cloneArray(a.extraHeaders),g=a.body;if(this._direction!=="incoming")throw new Zp.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(c<300||c>=700)throw new TypeError("Invalid status_code: ".concat(c));this._is_replied=!0,this._request.reply(c,e,f,g)}},{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 c=Xo.sipErrorCause(a.status_code);this._failed("remote",a,c);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Mc.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Mc.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newMessage",value:function(a,c){a==="remote"?(this._direction="incoming",this._local_identity=c.to,this._remote_identity=c.from):a==="local"&&(this._direction="outgoing",this._local_identity=c.from,this._remote_identity=c.to),this._ua.newMessage(this,{originator:a,message:this,request:c})}},{key:"_failed",value:function(a,c,e){hu.debug("MESSAGE failed"),this._close(),hu.debug('emit "failed"'),this.emit("failed",{originator:a,response:c||null,cause:e})}},{key:"_succeeded",value:function(a,c){hu.debug("MESSAGE succeeded"),this._close(),hu.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:c})}},{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}}]),r}(rS);function pu(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?pu=function(n){return typeof n}:pu=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},pu(o)}function uS(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function e_(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function cS(o,n,r){return n&&e_(o.prototype,n),r&&e_(o,r),o}function dS(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Uc(o,n)}function Uc(o,n){return Uc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Uc(o,n)}function hS(o){var n=fS();return function(){var r=_u(o),a;if(n){var c=_u(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return pS(this,a)}}function pS(o,n){return n&&(pu(n)==="object"||typeof n=="function")?n:_S(o)}function _S(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function fS(){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 _u(o){return _u=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},_u(o)}var mS=Tn.EventEmitter,gS=bn,Pc=dn,yS=Os,Jo=Bn(),vS=jo,t_=ai,fu=new gS("Options"),TS=function(o){dS(r,o);var n=hS(r);function r(a){var c;return uS(this,r),c=n.call(this),c._ua=a,c._request=null,c._closed=!1,c._direction=null,c._local_identity=null,c._remote_identity=null,c._is_replied=!1,c._data={},c}return cS(r,[{key:"send",value:function(a,c){var e=this,f=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},g=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(g));var d=Jo.cloneArray(f.extraHeaders),A=Jo.cloneObject(f.eventHandlers),S=f.contentType||"application/sdp";for(var R in A)Object.prototype.hasOwnProperty.call(A,R)&&this.on(R,A[R]);d.push("Content-Type: ".concat(S)),this._request=new yS.OutgoingRequest(Pc.OPTIONS,a,this._ua,null,d),c&&(this._request.body=c);var N=new vS(this._ua,this._request,{onRequestTimeout:function(){e._onRequestTimeout()},onTransportError:function(){e._onTransportError()},onReceiveResponse:function(H){e._receiveResponse(H)}});this._newOptions("local",this._request),N.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]:{},c=Jo.cloneArray(a.extraHeaders),e=a.body;if(this._direction!=="incoming")throw new t_.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,c,e)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},c=a.status_code||480,e=a.reason_phrase,f=Jo.cloneArray(a.extraHeaders),g=a.body;if(this._direction!=="incoming")throw new t_.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(c<300||c>=700)throw new TypeError("Invalid status_code: ".concat(c));this._is_replied=!0,this._request.reply(c,e,f,g)}},{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 c=Jo.sipErrorCause(a.status_code);this._failed("remote",a,c);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Pc.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Pc.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newOptions",value:function(a,c){a==="remote"?(this._direction="incoming",this._local_identity=c.to,this._remote_identity=c.from):a==="local"&&(this._direction="outgoing",this._local_identity=c.from,this._remote_identity=c.to),this._ua.newOptions(this,{originator:a,message:this,request:c})}},{key:"_failed",value:function(a,c,e){fu.debug("OPTIONS failed"),this._close(),fu.debug('emit "failed"'),this.emit("failed",{originator:a,response:c||null,cause:e})}},{key:"_succeeded",value:function(a,c){fu.debug("OPTIONS succeeded"),this._close(),fu.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:c})}},{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}}]),r}(mS),Lc={},bS=bn,qc=Bn(),wS=ss(),Qo=new bS("Socket");Lc.isSocket=function(o){if(Array.isArray(o))return!1;if(typeof o>"u")return Qo.warn("undefined JsSIP.Socket instance"),!1;try{if(!qc.isString(o.url))throw Qo.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!qc.isString(o.via_transport))throw Qo.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(wS.parse(o.sip_uri,"SIP_URI")===-1)throw Qo.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(n){if(!qc.isFunction(o[n]))throw Qo.warn("missing or invalid JsSIP.Socket method: ".concat(n)),new Error("Missing or invalid JsSIP.Socket method: ".concat(n))})}catch{return!1}return!0};function SS(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function n_(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function ES(o,n,r){return n&&n_(o.prototype,n),r&&n_(o,r),o}var CS=bn,AS=Lc,r_=dn,rr=new CS("Transport"),Ar={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:r_.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:r_.CONNECTION_RECOVERY_MAX_INTERVAL}},IS=function(){function o(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ar.recovery_options;SS(this,o),rr.debug("new()"),this.status=Ar.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=r,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(a){rr.warn("cannot use TextDecoder: ".concat(a))}if(typeof n>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");n instanceof Array||(n=[n]),n.forEach(function(a){if(!AS.isSocket(a.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(a.weight&&!Number(a.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:a.socket,weight:a.weight||0,status:Ar.SOCKET_STATUS_READY})},this),this._getSocket()}return ES(o,[{key:"connect",value:function(){if(rr.debug("connect()"),this.isConnected()){rr.debug("Transport is already connected");return}else if(this.isConnecting()){rr.debug("Transport is connecting");return}this.close_requested=!1,this.status=Ar.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(){rr.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=Ar.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(rr.debug("send()"),!this.isConnected())return rr.warn("unable to send message, transport is not connected"),!1;var r=n.toString();return rr.debug(`sending message:
|
|
50
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var e=!0,_=!1,g;return{s:function(){r=o[Symbol.iterator]()},n:function(){var d=r.next();return e=d.done,d},e:function(d){_=!0,g=d},f:function(){try{!e&&r.return!=null&&r.return()}finally{if(_)throw g}}}}function Uw(o,n){if(o){if(typeof o=="string")return jp(o,n);var r=Object.prototype.toString.call(o).slice(8,-1);if(r==="Object"&&o.constructor&&(r=o.constructor.name),r==="Map"||r==="Set")return Array.from(o);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return jp(o,n)}}function jp(o,n){(n==null||n>o.length)&&(n=o.length);for(var r=0,a=new Array(n);r<n;r++)a[r]=o[r];return a}function Pw(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Gp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Wp(o,n,r){return n&&Gp(o.prototype,n),r&&Gp(o,r),o}function Lw(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Dc(o,n)}function Dc(o,n){return Dc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Dc(o,n)}function qw(o){var n=Fw();return function(){var r=ou(o),a;if(n){var c=ou(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return Hw(this,a)}}function Hw(o,n){return n&&(au(n)==="object"||typeof n=="function")?n:zw(o)}function zw(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function Fw(){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 ou(o){return ou=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},ou(o)}var Bw=Tn.EventEmitter,Kp=nr,Vw=bn,Fe=dn,fa=ai,Yp=Vo,Xt=Bn(),Yo=Sp,jw=Os,lu=K0,Gw=jo,_r=ow,Xp=vw,Ww=Ew,Kw=Mw,Jp=oi(),ve=new Vw("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},uu=["audio","video"],Yw=function(o){Lw(r,o);var n=qw(r);Wp(r,null,[{key:"C",get:function(){return Ee}}]);function r(a){var c;return Pw(this,r),ve.debug("new"),c=n.call(this),c._id=null,c._ua=a,c._status=Ee.STATUS_NULL,c._dialog=null,c._earlyDialogs={},c._contact=null,c._from_tag=null,c._to_tag=null,c._connection=null,c._connectionPromiseQueue=Promise.resolve(),c._request=null,c._is_canceled=!1,c._cancel_reason="",c._is_confirmed=!1,c._late_sdp=!1,c._rtcOfferConstraints=null,c._rtcAnswerConstraints=null,c._localMediaStream=null,c._localMediaStreamLocallyGenerated=!1,c._rtcReady=!0,c._iceReady=!1,c._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},c._direction=null,c._local_identity=null,c._remote_identity=null,c._start_time=null,c._end_time=null,c._tones=null,c._audioMuted=!1,c._videoMuted=!1,c._localHold=!1,c._remoteHold=!1,c._sessionTimers={enabled:c._ua.configuration.session_timers,refreshMethod:c._ua.configuration.session_timers_refresh_method,defaultExpires:Fe.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},c._referSubscribers={},c._data={},c}return Wp(r,[{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 c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},e=arguments.length>2?arguments[2]:void 0;ve.debug("connect()");var _=a,g=Xt.cloneObject(c.eventHandlers),d=Xt.cloneArray(c.extraHeaders),A=Xt.cloneObject(c.mediaConstraints,{audio:!0,video:!0}),S=c.mediaStream||null,R=Xt.cloneObject(c.pcConfig,{iceServers:[]}),N=c.rtcConstraints||null,H=c.rtcOfferConstraints||null;if(this._rtcOfferConstraints=H,this._rtcAnswerConstraints=c.rtcAnswerConstraints||null,this._data=c.data||this._data,a===void 0)throw new TypeError("Not enough arguments");if(this._status!==Ee.STATUS_NULL)throw new fa.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new fa.NotSupportedError("WebRTC not supported");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(_));this._sessionTimers.enabled&&Xt.isDecimal(c.sessionTimersExpires)&&(c.sessionTimersExpires>=Fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=c.sessionTimersExpires:this._sessionTimers.defaultExpires=Fe.SESSION_EXPIRES);for(var W in g)Object.prototype.hasOwnProperty.call(g,W)&&this.on(W,g[W]);this._from_tag=Xt.newTag();var G=c.anonymous||!1,K={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:G,outbound:!0}),G?(K.from_display_name="Anonymous",K.from_uri=new Jp("sip","anonymous","anonymous.invalid"),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),d.push("Privacy: id")):c.fromUserName&&(K.from_uri=new Jp("sip",c.fromUserName,this._ua.configuration.uri.host),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),c.fromDisplayName&&(K.from_display_name=c.fromDisplayName),d.push("Contact: ".concat(this._contact)),d.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&d.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new jw.InitialOutgoingInviteRequest(a,this._ua,K,d),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(R,N),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,e&&e(this),this._newRTCSession("local",this._request),this._sendInitialRequest(A,H,S)}},{key:"init_incoming",value:function(a,c){var e=this;ve.debug("init_incoming()");var _,g=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;if(a.body&&g!=="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=Xt.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),e._failed("local",null,Fe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),_&&(this._timers.expiresTimer=setTimeout(function(){e._status===Ee.STATUS_WAITING_FOR_ANSWER&&(a.reply(487),e._failed("system",null,Fe.causes.EXPIRES))},_)),this._direction="incoming",this._local_identity=a.to,this._remote_identity=a.from,c&&c(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,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ve.debug("answer()");var e=this._request,_=Xt.cloneArray(c.extraHeaders),g=Xt.cloneObject(c.mediaConstraints),d=c.mediaStream||null,A=Xt.cloneObject(c.pcConfig,{iceServers:[]}),S=c.rtcConstraints||null,R=c.rtcAnswerConstraints||null,N=Xt.cloneObject(c.rtcOfferConstraints),H,W=!1,G=!1,K=!1,ae=!1;if(this._rtcAnswerConstraints=R,this._rtcOfferConstraints=c.rtcOfferConstraints||null,this._data=c.data||this._data,this._direction!=="incoming")throw new fa.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==Ee.STATUS_WAITING_FOR_ANSWER)throw new fa.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Xt.isDecimal(c.sessionTimersExpires)&&(c.sessionTimersExpires>=Fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=c.sessionTimersExpires:this._sessionTimers.defaultExpires=Fe.SESSION_EXPIRES),this._status=Ee.STATUS_ANSWERED,!this._createDialog(e,"UAS")){e.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),_.unshift("Contact: ".concat(this._contact));var ee=e.parseSDP();Array.isArray(ee.media)||(ee.media=[ee.media]);var De=Ns(ee.media),X;try{for(De.s();!(X=De.n()).done;){var re=X.value;re.type==="audio"&&(W=!0,(!re.direction||re.direction==="sendrecv")&&(K=!0)),re.type==="video"&&(G=!0,(!re.direction||re.direction==="sendrecv")&&(ae=!0))}}catch(ue){De.e(ue)}finally{De.f()}if(d&&g.audio===!1){H=d.getAudioTracks();var be=Ns(H),Ne;try{for(be.s();!(Ne=be.n()).done;){var Q=Ne.value;d.removeTrack(Q)}}catch(ue){be.e(ue)}finally{be.f()}}if(d&&g.video===!1){H=d.getVideoTracks();var ce=Ns(H),me;try{for(ce.s();!(me=ce.n()).done;){var _e=me.value;d.removeTrack(_e)}}catch(ue){ce.e(ue)}finally{ce.f()}}!d&&g.audio===void 0&&(g.audio=K),!d&&g.video===void 0&&(g.video=ae),!d&&!W&&!N.offerToReceiveAudio&&(g.audio=!1),!d&&!G&&!N.offerToReceiveVideo&&(g.video=!1),this._createRTCConnection(A,S),Promise.resolve().then(function(){if(d)return d;if(g.audio||g.video)return a._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(g).catch(function(ue){throw a._status===Ee.STATUS_TERMINATED?new Error("terminated"):(e.reply(480),a._failed("local",null,Fe.causes.USER_DENIED_MEDIA_ACCESS),ve.warn('emit "getusermediafailed" [error:%o]',ue),a.emit("getusermediafailed",ue),new Error("getUserMedia() failed"))})}).then(function(ue){if(a._status===Ee.STATUS_TERMINATED)throw new Error("terminated");a._localMediaStream=ue,ue&&ue.getTracks().forEach(function(ye){a._connection.addTrack(ye,ue)})}).then(function(){if(!a._late_sdp){var ue={originator:"remote",type:"offer",sdp:e.body};ve.debug('emit "sdp"'),a.emit("sdp",ue);var ye=new RTCSessionDescription({type:"offer",sdp:ue.sdp});return a._connectionPromiseQueue=a._connectionPromiseQueue.then(function(){return a._connection.setRemoteDescription(ye)}).catch(function(Re){throw e.reply(488),a._failed("system",null,Fe.causes.WEBRTC_ERROR),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',Re),a.emit("peerconnection:setremotedescriptionfailed",Re),new Error("peerconnection.setRemoteDescription() failed")}),a._connectionPromiseQueue}}).then(function(){if(a._status===Ee.STATUS_TERMINATED)throw new Error("terminated");return a._connecting(e),a._late_sdp?a._createLocalDescription("offer",a._rtcOfferConstraints).catch(function(){throw e.reply(500),new Error("_createLocalDescription() failed")}):a._createLocalDescription("answer",R).catch(function(){throw e.reply(500),new Error("_createLocalDescription() failed")})}).then(function(ue){if(a._status===Ee.STATUS_TERMINATED)throw new Error("terminated");a._handleSessionTimersInIncomingRequest(e,_),e.reply(200,null,_,ue,function(){a._status=Ee.STATUS_WAITING_FOR_ACK,a._setInvite2xxTimer(e,ue),a._setACKTimer(),a._accepted("local")},function(){a._failed("system",null,Fe.causes.CONNECTION_ERROR)})}).catch(function(ue){a._status!==Ee.STATUS_TERMINATED&&ve.warn(ue)})}},{key:"terminate",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ve.debug("terminate()");var e=c.cause||Fe.causes.BYE,_=Xt.cloneArray(c.extraHeaders),g=c.body,d,A=c.status_code,S=c.reason_phrase;if(this._status===Ee.STATUS_TERMINATED)throw new fa.InvalidStateError(this._status);switch(this._status){case Ee.STATUS_NULL:case Ee.STATUS_INVITE_SENT:case Ee.STATUS_1XX_RECEIVED:if(ve.debug("canceling session"),A&&(A<200||A>=700))throw new TypeError("Invalid status_code: ".concat(A));A&&(S=S||Fe.REASON_PHRASE[A]||"",d="SIP ;cause=".concat(A,' ;text="').concat(S,'"')),this._status===Ee.STATUS_NULL||this._status===Ee.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=d):this._status===Ee.STATUS_1XX_RECEIVED&&this._request.cancel(d),this._status=Ee.STATUS_CANCELED,this._failed("local",null,Fe.causes.CANCELED);break;case Ee.STATUS_WAITING_FOR_ANSWER:case Ee.STATUS_ANSWERED:if(ve.debug("rejecting session"),A=A||480,A<300||A>=700)throw new TypeError("Invalid status_code: ".concat(A));this._request.reply(A,S,_,g),this._failed("local",null,Fe.causes.REJECTED);break;case Ee.STATUS_WAITING_FOR_ACK:case Ee.STATUS_CONFIRMED:if(ve.debug("terminating session"),S=c.reason_phrase||Fe.REASON_PHRASE[A]||"",A&&(A<200||A>=700))throw new TypeError("Invalid status_code: ".concat(A));if(A&&_.push("Reason: SIP ;cause=".concat(A,'; text="').concat(S,'"')),this._status===Ee.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Yp.C.STATUS_TERMINATED){var R=this._dialog;this.receiveRequest=function(N){var H=N.method;H===Fe.ACK&&(a.sendRequest(Fe.BYE,{extraHeaders:_,body:g}),R.terminate())},this._request.server_transaction.on("stateChanged",function(){a._request.server_transaction.state===Yp.C.STATUS_TERMINATED&&(a.sendRequest(Fe.BYE,{extraHeaders:_,body:g}),R.terminate())}),this._ended("local",null,e),this._dialog=R,this._ua.newDialog(R)}else this.sendRequest(Fe.BYE,{extraHeaders:_,body:g}),this._ended("local",null,e)}}},{key:"sendDTMF",value:function(a){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};ve.debug("sendDTMF() | tones: %s",a);var e=0,_=c.duration||null,g=c.interToneGap||null,d=c.transportType||Fe.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 fa.InvalidStateError(this._status);if(d!==Fe.DTMF_TRANSPORT.INFO&&d!==Fe.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(d));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(_&&!Xt.isDecimal(_))throw new TypeError("Invalid tone duration: ".concat(_));if(_?_<_r.C.MIN_DURATION?(ve.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(_r.C.MIN_DURATION," milliseconds")),_=_r.C.MIN_DURATION):_>_r.C.MAX_DURATION?(ve.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(_r.C.MAX_DURATION," milliseconds")),_=_r.C.MAX_DURATION):_=Math.abs(_):_=_r.C.DEFAULT_DURATION,c.duration=_,g&&!Xt.isDecimal(g))throw new TypeError("Invalid interToneGap: ".concat(g));if(g?g<_r.C.MIN_INTER_TONE_GAP?(ve.debug('"interToneGap" value is lower than the minimum allowed, setting it to '.concat(_r.C.MIN_INTER_TONE_GAP," milliseconds")),g=_r.C.MIN_INTER_TONE_GAP):g=Math.abs(g):g=_r.C.DEFAULT_INTER_TONE_GAP,d===Fe.DTMF_TRANSPORT.RFC2833){var A=this._getDTMFRTPSender();A&&(a=A.toneBuffer+a,A.insertDTMF(a,_,g));return}if(this._tones){this._tones+=a;return}this._tones=a,S.call(this);function S(){var R=this,N;if(this._status===Ee.STATUS_TERMINATED||!this._tones||e>=this._tones.length){this._tones=null;return}var H=this._tones[e];if(e+=1,H===",")N=2e3;else{var W=new _r(this);c.eventHandlers={onFailed:function(){R._tones=null}},W.send(H,c),N=_+g}setTimeout(S.bind(this),N)}}},{key:"sendInfo",value:function(a,c){var e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(ve.debug("sendInfo()"),this._status!==Ee.STATUS_CONFIRMED&&this._status!==Ee.STATUS_WAITING_FOR_ACK&&this._status!==Ee.STATUS_1XX_RECEIVED)throw new fa.InvalidStateError(this._status);var _=new Xp(this);_.send(a,c,e)}},{key:"mute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};ve.debug("mute()");var c=!1,e=!1;this._audioMuted===!1&&a.audio&&(c=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&a.video&&(e=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(c===!0||e===!0)&&this._onmute({audio:c,video:e})}},{key:"unmute",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!0};ve.debug("unmute()");var c=!1,e=!1;this._audioMuted===!0&&a.audio&&(c=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&a.video&&(e=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(c===!0||e===!0)&&this._onunmute({audio:c,video:e})}},{key:"hold",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;if(ve.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(){e&&e()},failed:function(){a.terminate({cause:Fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return c.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:_,extraHeaders:c.extraHeaders}):this._sendReinvite({eventHandlers:_,extraHeaders:c.extraHeaders}),!0}},{key:"unhold",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;if(ve.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(){e&&e()},failed:function(){a.terminate({cause:Fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return c.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:_,extraHeaders:c.extraHeaders}):this._sendReinvite({eventHandlers:_,extraHeaders:c.extraHeaders}),!0}},{key:"renegotiate",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;ve.debug("renegotiate()");var _=c.rtcOfferConstraints||null;if(this._status!==Ee.STATUS_WAITING_FOR_ACK&&this._status!==Ee.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;var g={succeeded:function(){e&&e()},failed:function(){a.terminate({cause:Fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),c.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:g,rtcOfferConstraints:_,extraHeaders:c.extraHeaders}):this._sendReinvite({eventHandlers:g,rtcOfferConstraints:_,extraHeaders:c.extraHeaders}),!0}},{key:"refer",value:function(a,c){var e=this;ve.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 g=new Kw(this);g.sendRefer(a,c);var d=g.id;return this._referSubscribers[d]=g,g.on("requestFailed",function(){delete e._referSubscribers[d]}),g.on("accepted",function(){delete e._referSubscribers[d]}),g.on("failed",function(){delete e._referSubscribers[d]}),g}},{key:"sendRequest",value:function(a,c){return ve.debug("sendRequest()"),this._dialog.sendRequest(a,c)}},{key:"receiveRequest",value:function(a){var c=this;if(ve.debug("receiveRequest()"),a.method===Fe.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,Fe.causes.CANCELED));else switch(a.method){case Fe.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:Fe.causes.MISSING_SDP,status_code:400});break}var e={originator:"remote",type:"answer",sdp:a.body};ve.debug('emit "sdp"'),this.emit("sdp",e);var _=new RTCSessionDescription({type:"answer",sdp:e.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return c._connection.setRemoteDescription(_)}).then(function(){c._is_confirmed||c._confirmed("remote",a)}).catch(function(d){c.terminate({cause:Fe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',d),c.emit("peerconnection:setremotedescriptionfailed",d)})}else this._is_confirmed||this._confirmed("remote",a);break;case Fe.BYE:this._status===Ee.STATUS_CONFIRMED||this._status===Ee.STATUS_WAITING_FOR_ACK?(a.reply(200),this._ended("remote",a,Fe.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,Fe.causes.BYE)):a.reply(403,"Wrong Status");break;case Fe.INVITE:this._status===Ee.STATUS_CONFIRMED?a.hasHeader("replaces")?this._receiveReplaces(a):this._receiveReinvite(a):a.reply(403,"Wrong Status");break;case Fe.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 g=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0;g&&g.match(/^application\/dtmf-relay/i)?new _r(this).init_incoming(a):g!==void 0?new Xp(this).init_incoming(a):a.reply(415)}else a.reply(403,"Wrong Status");break;case Fe.UPDATE:this._status===Ee.STATUS_CONFIRMED?this._receiveUpdate(a):a.reply(403,"Wrong Status");break;case Fe.REFER:this._status===Ee.STATUS_CONFIRMED?this._receiveRefer(a):a.reply(403,"Wrong Status");break;case Fe.NOTIFY:this._status===Ee.STATUS_CONFIRMED?this._receiveNotify(a):a.reply(403,"Wrong Status");break;default:a.reply(501)}}},{key:"onTransportError",value:function(){ve.warn("onTransportError()"),this._status!==Ee.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Fe.causes.CONNECTION_ERROR,cause:Fe.causes.CONNECTION_ERROR})}},{key:"onRequestTimeout",value:function(){ve.warn("onRequestTimeout()"),this._status!==Ee.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Fe.causes.REQUEST_TIMEOUT,cause:Fe.causes.REQUEST_TIMEOUT})}},{key:"onDialogError",value:function(){ve.warn("onDialogError()"),this._status!==Ee.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Fe.causes.DIALOG_ERROR,cause:Fe.causes.DIALOG_ERROR})}},{key:"newDTMF",value:function(a){ve.debug("newDTMF()"),this.emit("newDTMF",a)}},{key:"newInfo",value:function(a){ve.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?(ve.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(ve.debug("_isReadyToReOffer() | session not established yet"),!1):(ve.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(ve.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(ve.debug("close() | closing local MediaStream"),Xt.closeMediaStream(this._localMediaStream)),this._status!==Ee.STATUS_TERMINATED){if(this._status=Ee.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(_){ve.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 c in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,c)&&(this._earlyDialogs[c].terminate(),delete this._earlyDialogs[c]);for(var e in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,e)&&delete this._referSubscribers[e];this._ua.destroyRTCSession(this)}}},{key:"_setInvite2xxTimer",value:function(a,c){var e=Yo.T1;function _(){this._status===Ee.STATUS_WAITING_FOR_ACK&&(a.reply(200,null,["Contact: ".concat(this._contact)],c),e<Yo.T2&&(e=e*2,e>Yo.T2&&(e=Yo.T2)),this._timers.invite2xxTimer=setTimeout(_.bind(this),e))}this._timers.invite2xxTimer=setTimeout(_.bind(this),e)}},{key:"_setACKTimer",value:function(){var a=this;this._timers.ackTimer=setTimeout(function(){a._status===Ee.STATUS_WAITING_FOR_ACK&&(ve.debug("no ACK received, terminating the session"),clearTimeout(a._timers.invite2xxTimer),a.sendRequest(Fe.BYE),a._ended("remote",null,Fe.causes.NO_ACK))},Yo.TIMER_H)}},{key:"_createRTCConnection",value:function(a,c){var e=this;this._connection=new RTCPeerConnection(a,c),this._connection.addEventListener("iceconnectionstatechange",function(){var _=e._connection.iceConnectionState;_==="failed"&&e.terminate({cause:Fe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:Fe.causes.RTP_TIMEOUT})}),ve.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(a,c){var e=this;if(ve.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(c).catch(function(g){return ve.warn('emit "peerconnection:createofferfailed" [error:%o]',g),e.emit("peerconnection:createofferfailed",g),Promise.reject(g)}):_.createAnswer(c).catch(function(g){return ve.warn('emit "peerconnection:createanswerfailed" [error:%o]',g),e.emit("peerconnection:createanswerfailed",g),Promise.reject(g)})}).then(function(g){return _.setLocalDescription(g).catch(function(d){return e._rtcReady=!0,ve.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',d),e.emit("peerconnection:setlocaldescriptionfailed",d),Promise.reject(d)})}).then(function(){var g=c&&c.iceRestart;if(_.iceGatheringState==="complete"&&!g||_.iceGatheringState==="gathering"&&e._iceReady){e._rtcReady=!0;var d={originator:"local",type:a,sdp:_.localDescription.sdp};return ve.debug('emit "sdp"'),e.emit("sdp",d),Promise.resolve(d.sdp)}return new Promise(function(A){var S=!1,R,N;e._iceReady=!1;var H=function(){_.removeEventListener("icecandidate",R),_.removeEventListener("icegatheringstatechange",N),S=!0,e._rtcReady=!0,e._iceReady=!0;var W={originator:"local",type:a,sdp:_.localDescription.sdp};ve.debug('emit "sdp"'),e.emit("sdp",W),A(W.sdp)};_.addEventListener("icecandidate",R=function(W){var G=W.candidate;G?e.emit("icecandidate",{candidate:G,ready:H}):S||H()}),_.addEventListener("icegatheringstatechange",N=function(){_.iceGatheringState==="complete"&&!S&&H()})})})}},{key:"_createDialog",value:function(a,c,e){var _=c==="UAS"?a.to_tag:a.from_tag,g=c==="UAS"?a.from_tag:a.to_tag,d=a.call_id+_+g,A=this._earlyDialogs[d];if(e)return A?!0:(A=new lu(this,a,c,lu.C.STATUS_EARLY),A.error?(ve.debug(A.error),this._failed("remote",a,Fe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[d]=A,!0));if(this._from_tag=a.from_tag,this._to_tag=a.to_tag,A)return A.update(a,c),this._dialog=A,delete this._earlyDialogs[d],!0;var S=new lu(this,a,c);return S.error?(ve.debug(S.error),this._failed("remote",a,Fe.causes.INTERNAL_ERROR),!1):(this._dialog=S,!0)}},{key:"_receiveReinvite",value:function(a){var c=this;ve.debug("receiveReinvite()");var e=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,_={request:a,callback:void 0,reject:d.bind(this)},g=!1;function d(){var S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};g=!0;var R=S.status_code||403,N=S.reason_phrase||"",H=Xt.cloneArray(S.extraHeaders);if(this._status!==Ee.STATUS_CONFIRMED)return!1;if(R<300||R>=700)throw new TypeError("Invalid status_code: ".concat(R));a.reply(R,N,H)}if(this.emit("reinvite",_),g)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 c._createLocalDescription("offer",c._rtcOfferConstraints)}).then(function(S){A.call(c,S)}).catch(function(){a.reply(500)});return}if(e!=="application/sdp"){ve.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(S){c._status!==Ee.STATUS_TERMINATED&&A.call(c,S)}).catch(function(S){ve.warn(S)});function A(S){var R=this,N=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,N),this._late_sdp&&(S=this._mangleOffer(S)),a.reply(200,null,N,S,function(){R._status=Ee.STATUS_WAITING_FOR_ACK,R._setInvite2xxTimer(a,S),R._setACKTimer()}),typeof _.callback=="function"&&_.callback()}}},{key:"_receiveUpdate",value:function(a){var c=this;ve.debug("receiveUpdate()");var e=a.hasHeader("Content-Type")?a.getHeader("Content-Type").toLowerCase():void 0,_={request:a,callback:void 0,reject:d.bind(this)},g=!1;function d(){var S=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};g=!0;var R=S.status_code||403,N=S.reason_phrase||"",H=Xt.cloneArray(S.extraHeaders);if(this._status!==Ee.STATUS_CONFIRMED)return!1;if(R<300||R>=700)throw new TypeError("Invalid status_code: ".concat(R));a.reply(R,N,H)}if(this.emit("update",_),g)return;if(!a.body){A.call(this,null);return}if(e!=="application/sdp"){ve.debug("invalid Content-Type"),a.reply(415);return}this._processInDialogSdpOffer(a).then(function(S){c._status!==Ee.STATUS_TERMINATED&&A.call(c,S)}).catch(function(S){ve.warn(S)});function A(S){var R=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(a,R),a.reply(200,null,R,S),typeof _.callback=="function"&&_.callback()}}},{key:"_processInDialogSdpOffer",value:function(a){var c=this;ve.debug("_processInDialogSdpOffer()");var e=a.parseSDP(),_=!1,g=Ns(e.media),d;try{for(g.s();!(d=g.n()).done;){var A=d.value;if(uu.indexOf(A.type)!==-1){var S=A.direction||e.direction||"sendrecv";if(S==="sendonly"||S==="inactive")_=!0;else{_=!1;break}}}}catch(H){g.e(H)}finally{g.f()}var R={originator:"remote",type:"offer",sdp:a.body};ve.debug('emit "sdp"'),this.emit("sdp",R);var N=new RTCSessionDescription({type:"offer",sdp:R.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(c._status===Ee.STATUS_TERMINATED)throw new Error("terminated");return c._connection.setRemoteDescription(N).catch(function(H){throw a.reply(488),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',H),c.emit("peerconnection:setremotedescriptionfailed",H),H})}).then(function(){if(c._status===Ee.STATUS_TERMINATED)throw new Error("terminated");c._remoteHold===!0&&_===!1?(c._remoteHold=!1,c._onunhold("remote")):c._remoteHold===!1&&_===!0&&(c._remoteHold=!0,c._onhold("remote"))}).then(function(){if(c._status===Ee.STATUS_TERMINATED)throw new Error("terminated");return c._createLocalDescription("answer",c._rtcAnswerConstraints).catch(function(H){throw a.reply(500),ve.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',H),H})}).catch(function(H){ve.warn("_processInDialogSdpOffer() failed [error: %o]",H)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(a){var c=this;if(ve.debug("receiveRefer()"),!a.refer_to){ve.debug("no Refer-To header field present in REFER"),a.reply(400);return}if(a.refer_to.uri.scheme!==Fe.SIP){ve.debug("Refer-To header field points to a non-SIP URI scheme"),a.reply(416);return}a.reply(202);var e=new Ww(this,a.cseq);ve.debug('emit "refer"'),this.emit("refer",{request:a,accept:function(d,A){_.call(c,d,A)},reject:function(){g.call(c)}});function _(d){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(d=typeof d=="function"?d:null,this._status!==Ee.STATUS_WAITING_FOR_ACK&&this._status!==Ee.STATUS_CONFIRMED)return!1;var S=new r(this._ua);if(S.on("progress",function(N){var H=N.response;e.notify(H.status_code,H.reason_phrase)}),S.on("accepted",function(N){var H=N.response;e.notify(H.status_code,H.reason_phrase)}),S.on("_failed",function(N){var H=N.message,W=N.cause;H?e.notify(H.status_code,H.reason_phrase):e.notify(487,W)}),a.refer_to.uri.hasHeader("replaces")){var R=decodeURIComponent(a.refer_to.uri.getHeader("replaces"));A.extraHeaders=Xt.cloneArray(A.extraHeaders),A.extraHeaders.push("Replaces: ".concat(R))}S.connect(a.refer_to.uri.toAor(),A,d)}function g(){e.notify(603)}}},{key:"_receiveNotify",value:function(a){switch(ve.debug("receiveNotify()"),a.event||a.reply(400),a.event.event){case"refer":{var c,e;if(a.event.params&&a.event.params.id)c=a.event.params.id,e=this._referSubscribers[c];else if(Object.keys(this._referSubscribers).length===1)e=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{a.reply(400,"Missing event id parameter");return}if(!e){a.reply(481,"Subscription does not exist");return}e.receiveNotify(a),a.reply(200);break}default:a.reply(489)}}},{key:"_receiveReplaces",value:function(a){var c=this;ve.debug("receiveReplaces()");function e(g){var d=this;if(this._status!==Ee.STATUS_WAITING_FOR_ACK&&this._status!==Ee.STATUS_CONFIRMED)return!1;var A=new r(this._ua);A.on("confirmed",function(){d.terminate()}),A.init_incoming(a,g)}function _(){ve.debug("Replaced INVITE rejected by the user"),a.reply(486)}this.emit("replaces",{request:a,accept:function(g){e.call(c,g)},reject:function(){_.call(c)}})}},{key:"_sendInitialRequest",value:function(a,c,e){var _=this,g=new Gw(this._ua,this._request,{onRequestTimeout:function(){_.onRequestTimeout()},onTransportError:function(){_.onTransportError()},onAuthenticated:function(d){_._request=d},onReceiveResponse:function(d){_._receiveInviteResponse(d)}});Promise.resolve().then(function(){if(e)return e;if(a.audio||a.video)return _._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(a).catch(function(d){throw _._status===Ee.STATUS_TERMINATED?new Error("terminated"):(_._failed("local",null,Fe.causes.USER_DENIED_MEDIA_ACCESS),ve.warn('emit "getusermediafailed" [error:%o]',d),_.emit("getusermediafailed",d),d)})}).then(function(d){if(_._status===Ee.STATUS_TERMINATED)throw new Error("terminated");return _._localMediaStream=d,d&&d.getTracks().forEach(function(A){_._connection.addTrack(A,d)}),_._connecting(_._request),_._createLocalDescription("offer",c).catch(function(A){throw _._failed("local",null,Fe.causes.WEBRTC_ERROR),A})}).then(function(d){if(_._is_canceled||_._status===Ee.STATUS_TERMINATED)throw new Error("terminated");_._request.body=d,_._status=Ee.STATUS_INVITE_SENT,ve.debug('emit "sending" [request:%o]',_._request),_.emit("sending",{request:_._request}),g.send()}).catch(function(d){_._status!==Ee.STATUS_TERMINATED&&ve.warn(d)})}},{key:"_getDTMFRTPSender",value:function(){var a=this._connection.getSenders().find(function(c){return c.track&&c.track.kind==="audio"});if(!(a&&a.dtmf)){ve.warn("sendDTMF() | no local audio track to send DTMF with");return}return a.dtmf}},{key:"_receiveInviteResponse",value:function(a){var c=this;if(ve.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(Fe.ACK);return}else{var e=new lu(this,a,"UAC");if(e.error!==void 0){ve.debug(e.error);return}this.sendRequest(Fe.ACK),this.sendRequest(Fe.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){ve.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};ve.debug('emit "sdp"'),this.emit("sdp",_);var g=new RTCSessionDescription({type:"answer",sdp:_.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return c._connection.setRemoteDescription(g)}).then(function(){return c._progress("remote",a)}).catch(function(R){ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),c.emit("peerconnection:setremotedescriptionfailed",R)});break}case/^2[0-9]{2}$/.test(a.status_code):{if(this._status=Ee.STATUS_CONFIRMED,!a.body){this._acceptAndTerminate(a,400,Fe.causes.MISSING_SDP),this._failed("remote",a,Fe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(a,"UAC"))break;var d={originator:"remote",type:"answer",sdp:a.body};ve.debug('emit "sdp"'),this.emit("sdp",d);var A=new RTCSessionDescription({type:"answer",sdp:d.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(c._connection.signalingState==="stable")return c._connection.createOffer(c._rtcOfferConstraints).then(function(R){return c._connection.setLocalDescription(R)}).catch(function(R){c._acceptAndTerminate(a,500,R.toString()),c._failed("local",a,Fe.causes.WEBRTC_ERROR)})}).then(function(){c._connection.setRemoteDescription(A).then(function(){c._handleSessionTimersInIncomingResponse(a),c._accepted("remote",a),c.sendRequest(Fe.ACK),c._confirmed("local",null)}).catch(function(R){c._acceptAndTerminate(a,488,"Not Acceptable Here"),c._failed("remote",a,Fe.causes.BAD_MEDIA_DESCRIPTION),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),c.emit("peerconnection:setremotedescriptionfailed",R)})});break}default:{var S=Xt.sipErrorCause(a.status_code);this._failed("remote",a,S)}}}},{key:"_sendReinvite",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ve.debug("sendReinvite()");var e=Xt.cloneArray(c.extraHeaders),_=Xt.cloneObject(c.eventHandlers),g=c.rtcOfferConstraints||this._rtcOfferConstraints||null,d=!1;e.push("Contact: ".concat(this._contact)),e.push("Content-Type: application/sdp"),this._sessionTimers.running&&e.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",g)}).then(function(R){R=a._mangleOffer(R);var N={originator:"local",type:"offer",sdp:R};ve.debug('emit "sdp"'),a.emit("sdp",N),a.sendRequest(Fe.INVITE,{extraHeaders:e,body:R,eventHandlers:{onSuccessResponse:function(H){A.call(a,H),d=!0},onErrorResponse:function(H){S.call(a,H)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){S()});function A(R){var N=this;if(this._status!==Ee.STATUS_TERMINATED&&(this.sendRequest(Fe.ACK),!d)){if(this._handleSessionTimersInIncomingResponse(R),R.body){if(!R.hasHeader("Content-Type")||R.getHeader("Content-Type").toLowerCase()!=="application/sdp"){S.call(this);return}}else{S.call(this);return}var H={originator:"remote",type:"answer",sdp:R.body};ve.debug('emit "sdp"'),this.emit("sdp",H);var W=new RTCSessionDescription({type:"answer",sdp:H.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return N._connection.setRemoteDescription(W)}).then(function(){_.succeeded&&_.succeeded(R)}).catch(function(G){S.call(N),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',G),N.emit("peerconnection:setremotedescriptionfailed",G)})}}function S(R){_.failed&&_.failed(R)}}},{key:"_sendUpdate",value:function(){var a=this,c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ve.debug("sendUpdate()");var e=Xt.cloneArray(c.extraHeaders),_=Xt.cloneObject(c.eventHandlers),g=c.rtcOfferConstraints||this._rtcOfferConstraints||null,d=c.sdpOffer||!1,A=!1;e.push("Contact: ".concat(this._contact)),this._sessionTimers.running&&e.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),d?(e.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return a._createLocalDescription("offer",g)}).then(function(N){N=a._mangleOffer(N);var H={originator:"local",type:"offer",sdp:N};ve.debug('emit "sdp"'),a.emit("sdp",H),a.sendRequest(Fe.UPDATE,{extraHeaders:e,body:N,eventHandlers:{onSuccessResponse:function(W){S.call(a,W),A=!0},onErrorResponse:function(W){R.call(a,W)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}})}).catch(function(){R.call(a)})):this.sendRequest(Fe.UPDATE,{extraHeaders:e,eventHandlers:{onSuccessResponse:function(N){S.call(a,N)},onErrorResponse:function(N){R.call(a,N)},onTransportError:function(){a.onTransportError()},onRequestTimeout:function(){a.onRequestTimeout()},onDialogError:function(){a.onDialogError()}}});function S(N){var H=this;if(this._status!==Ee.STATUS_TERMINATED&&!A)if(this._handleSessionTimersInIncomingResponse(N),d){if(N.body){if(!N.hasHeader("Content-Type")||N.getHeader("Content-Type").toLowerCase()!=="application/sdp"){R.call(this);return}}else{R.call(this);return}var W={originator:"remote",type:"answer",sdp:N.body};ve.debug('emit "sdp"'),this.emit("sdp",W);var G=new RTCSessionDescription({type:"answer",sdp:W.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return H._connection.setRemoteDescription(G)}).then(function(){_.succeeded&&_.succeeded(N)}).catch(function(K){R.call(H),ve.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',K),H.emit("peerconnection:setremotedescriptionfailed",K)})}else _.succeeded&&_.succeeded(N)}function R(N){_.failed&&_.failed(N)}}},{key:"_acceptAndTerminate",value:function(a,c,e){ve.debug("acceptAndTerminate()");var _=[];c&&(e=e||Fe.REASON_PHRASE[c]||"",_.push("Reason: SIP ;cause=".concat(c,'; text="').concat(e,'"'))),(this._dialog||this._createDialog(a,"UAC"))&&(this.sendRequest(Fe.ACK),this.sendRequest(Fe.BYE,{extraHeaders:_})),this._status=Ee.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(a){if(!this._localHold&&!this._remoteHold)return a;if(a=Kp.parse(a),this._localHold&&!this._remoteHold){ve.debug("mangleOffer() | me on hold, mangling offer");var c=Ns(a.media),e;try{for(c.s();!(e=c.n()).done;){var _=e.value;uu.indexOf(_.type)!==-1&&(_.direction?_.direction==="sendrecv"?_.direction="sendonly":_.direction==="recvonly"&&(_.direction="inactive"):_.direction="sendonly")}}catch(H){c.e(H)}finally{c.f()}}else if(this._localHold&&this._remoteHold){ve.debug("mangleOffer() | both on hold, mangling offer");var g=Ns(a.media),d;try{for(g.s();!(d=g.n()).done;){var A=d.value;uu.indexOf(A.type)!==-1&&(A.direction="inactive")}}catch(H){g.e(H)}finally{g.f()}}else if(this._remoteHold){ve.debug("mangleOffer() | remote on hold, mangling offer");var S=Ns(a.media),R;try{for(S.s();!(R=S.n()).done;){var N=R.value;uu.indexOf(N.type)!==-1&&(N.direction?N.direction==="sendrecv"?N.direction="recvonly":N.direction==="recvonly"&&(N.direction="inactive"):N.direction="recvonly")}}catch(H){S.e(H)}finally{S.f()}}return Kp.write(a)}},{key:"_setLocalMediaStatus",value:function(){var a=!0,c=!0;(this._localHold||this._remoteHold)&&(a=!1,c=!1),this._audioMuted&&(a=!1),this._videoMuted&&(c=!1),this._toggleMuteAudio(!a),this._toggleMuteVideo(!c)}},{key:"_handleSessionTimersInIncomingRequest",value:function(a,c){if(this._sessionTimers.enabled){var e;a.session_expires&&a.session_expires>=Fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,e=a.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,e="uas"),c.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(e)),this._sessionTimers.refresher=e==="uas",this._runSessionTimer()}}},{key:"_handleSessionTimersInIncomingResponse",value:function(a){if(this._sessionTimers.enabled){var c;a.session_expires&&a.session_expires>=Fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=a.session_expires,c=a.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,c="uac"),this._sessionTimers.refresher=c==="uac",this._runSessionTimer()}}},{key:"_runSessionTimer",value:function(){var a=this,c=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()&&(ve.debug("runSessionTimer() | sending session refresh request"),a._sessionTimers.refreshMethod===Fe.UPDATE?a._sendUpdate():a._sendReinvite())},c*500):this._sessionTimers.timer=setTimeout(function(){a._status!==Ee.STATUS_TERMINATED&&(ve.warn("runSessionTimer() | timer expired, terminating the session"),a.terminate({cause:Fe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},c*1100)}},{key:"_toggleMuteAudio",value:function(a){var c=this._connection.getSenders().filter(function(d){return d.track&&d.track.kind==="audio"}),e=Ns(c),_;try{for(e.s();!(_=e.n()).done;){var g=_.value;g.track.enabled=!a}}catch(d){e.e(d)}finally{e.f()}}},{key:"_toggleMuteVideo",value:function(a){var c=this._connection.getSenders().filter(function(d){return d.track&&d.track.kind==="video"}),e=Ns(c),_;try{for(e.s();!(_=e.n()).done;){var g=_.value;g.track.enabled=!a}}catch(d){e.e(d)}finally{e.f()}}},{key:"_newRTCSession",value:function(a,c){ve.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:a,session:this,request:c})}},{key:"_connecting",value:function(a){ve.debug("session connecting"),ve.debug('emit "connecting"'),this.emit("connecting",{request:a})}},{key:"_progress",value:function(a,c){ve.debug("session progress"),ve.debug('emit "progress"'),this.emit("progress",{originator:a,response:c||null})}},{key:"_accepted",value:function(a,c){ve.debug("session accepted"),this._start_time=new Date,ve.debug('emit "accepted"'),this.emit("accepted",{originator:a,response:c||null})}},{key:"_confirmed",value:function(a,c){ve.debug("session confirmed"),this._is_confirmed=!0,ve.debug('emit "confirmed"'),this.emit("confirmed",{originator:a,ack:c||null})}},{key:"_ended",value:function(a,c,e){ve.debug("session ended"),this._end_time=new Date,this._close(),ve.debug('emit "ended"'),this.emit("ended",{originator:a,message:c||null,cause:e})}},{key:"_failed",value:function(a,c,e){ve.debug("session failed"),ve.debug('emit "_failed"'),this.emit("_failed",{originator:a,message:c||null,cause:e}),this._close(),ve.debug('emit "failed"'),this.emit("failed",{originator:a,message:c||null,cause:e})}},{key:"_onhold",value:function(a){ve.debug("session onhold"),this._setLocalMediaStatus(),ve.debug('emit "hold"'),this.emit("hold",{originator:a})}},{key:"_onunhold",value:function(a){ve.debug("session onunhold"),this._setLocalMediaStatus(),ve.debug('emit "unhold"'),this.emit("unhold",{originator:a})}},{key:"_onmute",value:function(a){var c=a.audio,e=a.video;ve.debug("session onmute"),this._setLocalMediaStatus(),ve.debug('emit "muted"'),this.emit("muted",{audio:c,video:e})}},{key:"_onunmute",value:function(a){var c=a.audio,e=a.video;ve.debug("session onunmute"),this._setLocalMediaStatus(),ve.debug('emit "unmuted"'),this.emit("unmuted",{audio:c,video:e})}},{key:"C",get:function(){return Ee}},{key:"causes",get:function(){return Fe.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}}]),r}(Bw);function cu(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?cu=function(n){return typeof n}:cu=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},cu(o)}function Xw(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function Qp(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function Jw(o,n,r){return n&&Qp(o.prototype,n),r&&Qp(o,r),o}function Qw(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Nc(o,n)}function Nc(o,n){return Nc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Nc(o,n)}function Zw(o){var n=nS();return function(){var r=du(o),a;if(n){var c=du(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return eS(this,a)}}function eS(o,n){return n&&(cu(n)==="object"||typeof n=="function")?n:tS(o)}function tS(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function nS(){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 du(o){return du=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},du(o)}var rS=Tn.EventEmitter,sS=bn,Mc=dn,iS=Os,Xo=Bn(),aS=jo,Zp=ai,oS=oi(),hu=new sS("Message"),lS=function(o){Qw(r,o);var n=Zw(r);function r(a){var c;return Xw(this,r),c=n.call(this),c._ua=a,c._request=null,c._closed=!1,c._direction=null,c._local_identity=null,c._remote_identity=null,c._is_replied=!1,c._data={},c}return Jw(r,[{key:"send",value:function(a,c){var e=this,_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},g=a;if(a===void 0||c===void 0)throw new TypeError("Not enough arguments");if(a=this._ua.normalizeTarget(a),!a)throw new TypeError("Invalid target: ".concat(g));var d=Xo.cloneArray(_.extraHeaders),A=Xo.cloneObject(_.eventHandlers),S=_.contentType||"text/plain",R={};_.fromUserName&&(R.from_uri=new oS("sip",_.fromUserName,this._ua.configuration.uri.host),d.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),_.fromDisplayName&&(R.from_display_name=_.fromDisplayName);for(var N in A)Object.prototype.hasOwnProperty.call(A,N)&&this.on(N,A[N]);d.push("Content-Type: ".concat(S)),this._request=new iS.OutgoingRequest(Mc.MESSAGE,a,this._ua,R,d),c&&(this._request.body=c);var H=new aS(this._ua,this._request,{onRequestTimeout:function(){e._onRequestTimeout()},onTransportError:function(){e._onTransportError()},onReceiveResponse:function(W){e._receiveResponse(W)}});this._newMessage("local",this._request),H.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]:{},c=Xo.cloneArray(a.extraHeaders),e=a.body;if(this._direction!=="incoming")throw new Zp.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,c,e)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},c=a.status_code||480,e=a.reason_phrase,_=Xo.cloneArray(a.extraHeaders),g=a.body;if(this._direction!=="incoming")throw new Zp.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(c<300||c>=700)throw new TypeError("Invalid status_code: ".concat(c));this._is_replied=!0,this._request.reply(c,e,_,g)}},{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 c=Xo.sipErrorCause(a.status_code);this._failed("remote",a,c);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Mc.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Mc.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newMessage",value:function(a,c){a==="remote"?(this._direction="incoming",this._local_identity=c.to,this._remote_identity=c.from):a==="local"&&(this._direction="outgoing",this._local_identity=c.from,this._remote_identity=c.to),this._ua.newMessage(this,{originator:a,message:this,request:c})}},{key:"_failed",value:function(a,c,e){hu.debug("MESSAGE failed"),this._close(),hu.debug('emit "failed"'),this.emit("failed",{originator:a,response:c||null,cause:e})}},{key:"_succeeded",value:function(a,c){hu.debug("MESSAGE succeeded"),this._close(),hu.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:c})}},{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}}]),r}(rS);function pu(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?pu=function(n){return typeof n}:pu=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},pu(o)}function uS(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function e_(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function cS(o,n,r){return n&&e_(o.prototype,n),r&&e_(o,r),o}function dS(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Uc(o,n)}function Uc(o,n){return Uc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Uc(o,n)}function hS(o){var n=fS();return function(){var r=_u(o),a;if(n){var c=_u(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return pS(this,a)}}function pS(o,n){return n&&(pu(n)==="object"||typeof n=="function")?n:_S(o)}function _S(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function fS(){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 _u(o){return _u=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},_u(o)}var mS=Tn.EventEmitter,gS=bn,Pc=dn,yS=Os,Jo=Bn(),vS=jo,t_=ai,fu=new gS("Options"),TS=function(o){dS(r,o);var n=hS(r);function r(a){var c;return uS(this,r),c=n.call(this),c._ua=a,c._request=null,c._closed=!1,c._direction=null,c._local_identity=null,c._remote_identity=null,c._is_replied=!1,c._data={},c}return cS(r,[{key:"send",value:function(a,c){var e=this,_=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},g=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(g));var d=Jo.cloneArray(_.extraHeaders),A=Jo.cloneObject(_.eventHandlers),S=_.contentType||"application/sdp";for(var R in A)Object.prototype.hasOwnProperty.call(A,R)&&this.on(R,A[R]);d.push("Content-Type: ".concat(S)),this._request=new yS.OutgoingRequest(Pc.OPTIONS,a,this._ua,null,d),c&&(this._request.body=c);var N=new vS(this._ua,this._request,{onRequestTimeout:function(){e._onRequestTimeout()},onTransportError:function(){e._onTransportError()},onReceiveResponse:function(H){e._receiveResponse(H)}});this._newOptions("local",this._request),N.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]:{},c=Jo.cloneArray(a.extraHeaders),e=a.body;if(this._direction!=="incoming")throw new t_.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,c,e)}},{key:"reject",value:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},c=a.status_code||480,e=a.reason_phrase,_=Jo.cloneArray(a.extraHeaders),g=a.body;if(this._direction!=="incoming")throw new t_.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(c<300||c>=700)throw new TypeError("Invalid status_code: ".concat(c));this._is_replied=!0,this._request.reply(c,e,_,g)}},{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 c=Jo.sipErrorCause(a.status_code);this._failed("remote",a,c);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Pc.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Pc.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newOptions",value:function(a,c){a==="remote"?(this._direction="incoming",this._local_identity=c.to,this._remote_identity=c.from):a==="local"&&(this._direction="outgoing",this._local_identity=c.from,this._remote_identity=c.to),this._ua.newOptions(this,{originator:a,message:this,request:c})}},{key:"_failed",value:function(a,c,e){fu.debug("OPTIONS failed"),this._close(),fu.debug('emit "failed"'),this.emit("failed",{originator:a,response:c||null,cause:e})}},{key:"_succeeded",value:function(a,c){fu.debug("OPTIONS succeeded"),this._close(),fu.debug('emit "succeeded"'),this.emit("succeeded",{originator:a,response:c})}},{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}}]),r}(mS),Lc={},bS=bn,qc=Bn(),wS=ss(),Qo=new bS("Socket");Lc.isSocket=function(o){if(Array.isArray(o))return!1;if(typeof o>"u")return Qo.warn("undefined JsSIP.Socket instance"),!1;try{if(!qc.isString(o.url))throw Qo.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!qc.isString(o.via_transport))throw Qo.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(wS.parse(o.sip_uri,"SIP_URI")===-1)throw Qo.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(n){if(!qc.isFunction(o[n]))throw Qo.warn("missing or invalid JsSIP.Socket method: ".concat(n)),new Error("Missing or invalid JsSIP.Socket method: ".concat(n))})}catch{return!1}return!0};function SS(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function n_(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function ES(o,n,r){return n&&n_(o.prototype,n),r&&n_(o,r),o}var CS=bn,AS=Lc,r_=dn,rr=new CS("Transport"),Ar={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:r_.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:r_.CONNECTION_RECOVERY_MAX_INTERVAL}},IS=function(){function o(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ar.recovery_options;SS(this,o),rr.debug("new()"),this.status=Ar.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=r,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(a){rr.warn("cannot use TextDecoder: ".concat(a))}if(typeof n>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");n instanceof Array||(n=[n]),n.forEach(function(a){if(!AS.isSocket(a.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(a.weight&&!Number(a.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:a.socket,weight:a.weight||0,status:Ar.SOCKET_STATUS_READY})},this),this._getSocket()}return ES(o,[{key:"connect",value:function(){if(rr.debug("connect()"),this.isConnected()){rr.debug("Transport is already connected");return}else if(this.isConnecting()){rr.debug("Transport is connecting");return}this.close_requested=!1,this.status=Ar.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(){rr.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=Ar.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(rr.debug("send()"),!this.isConnected())return rr.warn("unable to send message, transport is not connected"),!1;var r=n.toString();return rr.debug(`sending message:
|
|
51
51
|
|
|
52
52
|
`.concat(r,`
|
|
53
53
|
`)),this.socket.send(r)}},{key:"isConnected",value:function(){return this.status===Ar.STATUS_CONNECTED}},{key:"isConnecting",value:function(){return this.status===Ar.STATUS_CONNECTING}},{key:"_reconnect",value:function(){var n=this;this.recover_attempts+=1;var r=Math.floor(Math.random()*Math.pow(2,this.recover_attempts)+1);r<this.recovery_options.min_interval?r=this.recovery_options.min_interval:r>this.recovery_options.max_interval&&(r=this.recovery_options.max_interval),rr.debug("reconnection attempt: ".concat(this.recover_attempts,". next connection attempt in ").concat(r," seconds")),this.recovery_timer=setTimeout(function(){!n.close_requested&&!(n.isConnected()||n.isConnecting())&&(n._getSocket(),n.connect())},r*1e3)}},{key:"_getSocket",value:function(){var n=[];if(this.sockets.forEach(function(a){a.status!==Ar.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=Ar.SOCKET_STATUS_READY}),this._getSocket();return}var r=Math.floor(Math.random()*n.length);this.socket=n[r].socket}},{key:"_onConnect",value:function(){this.recover_attempts=0,this.status=Ar.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}},{key:"_onDisconnect",value:function(n,r,a){this.status=Ar.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:n,code:r,reason:a}),!this.close_requested&&(this.sockets.forEach(function(c){this.socket===c.socket&&(c.status=Ar.SOCKET_STATUS_ERROR)},this),this._reconnect(n))}},{key:"_onData",value:function(n){if(n===`\r
|
|
@@ -58,21 +58,21 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
58
58
|
|
|
59
59
|
`.concat(n,`
|
|
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}}]),o}(),s_={};function i_(o,n){var r;if(typeof Symbol>"u"||o[Symbol.iterator]==null){if(Array.isArray(o)||(r=RS(o))||n&&o&&typeof o.length=="number"){r&&(o=r);var a=0,c=function(){};return{s:c,n:function(){return a>=o.length?{done:!0}:{done:!1,value:o[a++]}},e:function(d){throw d},f:c}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
61
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var e=!0,
|
|
62
|
-
`);if(c===-1){mu.warn("parseMessage() | no CRLF found, not a SIP message");return}var e=o.substring(0,c),
|
|
63
|
-
`,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function OS(o,n,r,a){var c,e=n.indexOf(":",r),
|
|
64
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var e=!0,
|
|
65
|
-
`),c=gu(n),e;try{for(c.s();!(e=c.n()).done;){var
|
|
61
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var e=!0,_=!1,g;return{s:function(){r=o[Symbol.iterator]()},n:function(){var d=r.next();return e=d.done,d},e:function(d){_=!0,g=d},f:function(){try{!e&&r.return!=null&&r.return()}finally{if(_)throw g}}}}function RS(o,n){if(o){if(typeof o=="string")return a_(o,n);var r=Object.prototype.toString.call(o).slice(8,-1);if(r==="Object"&&o.constructor&&(r=o.constructor.name),r==="Map"||r==="Set")return Array.from(o);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return a_(o,n)}}function a_(o,n){(n==null||n>o.length)&&(n=o.length);for(var r=0,a=new Array(n);r<n;r++)a[r]=o[r];return a}var $S=bn,Hc=ss(),zc=Os,mu=new $S("Parser");s_.parseMessage=function(o,n){var r,a,c=o.indexOf(`\r
|
|
62
|
+
`);if(c===-1){mu.warn("parseMessage() | no CRLF found, not a SIP message");return}var e=o.substring(0,c),_=Hc.parse(e,"Request_Response");if(_===-1){mu.warn('parseMessage() | error parsing first line of SIP message: "'.concat(e,'"'));return}else _.status_code?(r=new zc.IncomingResponse,r.status_code=_.status_code,r.reason_phrase=_.reason_phrase):(r=new zc.IncomingRequest(n),r.method=_.method,r.ruri=_.uri);r.data=o;for(var g=c+2;;){if(c=xS(o,g),c===-2){a=g+2;break}else if(c===-1){mu.warn("parseMessage() | malformed message");return}if(_=OS(r,o,g,c),_!==!0){mu.warn("parseMessage() |",_.error);return}g=c+2}if(r.hasHeader("content-length")){var d=r.getHeader("content-length");r.body=o.substr(a,d)}else r.body=o.substring(a);return r};function xS(o,n){var r=n,a=0,c=0;if(o.substring(r,r+2).match(/(^\r\n)/))return-2;for(;a===0;){if(c=o.indexOf(`\r
|
|
63
|
+
`,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function OS(o,n,r,a){var c,e=n.indexOf(":",r),_=n.substring(r,e).trim(),g=n.substring(e+1,a).trim();switch(_.toLowerCase()){case"via":case"v":o.addHeader("via",g),o.getHeaders("via").length===1?(c=o.parseHeader("Via"),c&&(o.via=c,o.via_branch=c.branch)):c=0;break;case"from":case"f":o.setHeader("from",g),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",g),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=Hc.parse(g,"Record_Route"),c===-1)c=void 0;else{var d=i_(c),A;try{for(d.s();!(A=d.n()).done;){var S=A.value;o.addHeader("record-route",g.substring(S.possition,S.offset)),o.headers["Record-Route"][o.getHeaders("record-route").length-1].parsed=S.parsed}}catch(W){d.e(W)}finally{d.f()}}break;case"call-id":case"i":o.setHeader("call-id",g),c=o.parseHeader("call-id"),c&&(o.call_id=g);break;case"contact":case"m":if(c=Hc.parse(g,"Contact"),c===-1)c=void 0;else{var R=i_(c),N;try{for(R.s();!(N=R.n()).done;){var H=N.value;o.addHeader("contact",g.substring(H.possition,H.offset)),o.headers.Contact[o.getHeaders("contact").length-1].parsed=H.parsed}}catch(W){R.e(W)}finally{R.f()}}break;case"content-length":case"l":o.setHeader("content-length",g),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",g),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",g),c=o.parseHeader("cseq"),c&&(o.cseq=c.value),o instanceof zc.IncomingResponse&&(o.method=c.method);break;case"max-forwards":o.setHeader("max-forwards",g),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",g),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",g),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",g),c=o.parseHeader("session-expires"),c&&(o.session_expires=c.expires,o.session_expires_refresher=c.refresher);break;case"refer-to":case"r":o.setHeader("refer-to",g),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",g),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",g),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(_,g),c=0}return c===void 0?{error:'error parsing header "'.concat(_,'"')}:!0}function gu(o,n){var r;if(typeof Symbol>"u"||o[Symbol.iterator]==null){if(Array.isArray(o)||(r=kS(o))||n&&o&&typeof o.length=="number"){r&&(o=r);var a=0,c=function(){};return{s:c,n:function(){return a>=o.length?{done:!0}:{done:!1,value:o[a++]}},e:function(d){throw d},f:c}}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 e=!0,_=!1,g;return{s:function(){r=o[Symbol.iterator]()},n:function(){var d=r.next();return e=d.done,d},e:function(d){_=!0,g=d},f:function(){try{!e&&r.return!=null&&r.return()}finally{if(_)throw g}}}}function kS(o,n){if(o){if(typeof o=="string")return o_(o,n);var r=Object.prototype.toString.call(o).slice(8,-1);if(r==="Object"&&o.constructor&&(r=o.constructor.name),r==="Map"||r==="Set")return Array.from(o);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o_(o,n)}}function o_(o,n){(n==null||n>o.length)&&(n=o.length);for(var r=0,a=new Array(n);r<n;r++)a[r]=o[r];return a}var DS=bn,l_=dn,u_=Os,Fc=Bn(),Bc=new DS("sanityCheck"),NS=[VS],MS=[LS,qS,HS,zS],US=[FS,BS],Vt,as,c_,PS=function(o,n,r){Vt=o,as=n,c_=r;var a=gu(NS),c;try{for(a.s();!(c=a.n()).done;){var e=c.value;if(e()===!1)return!1}}catch(N){a.e(N)}finally{a.f()}if(Vt instanceof u_.IncomingRequest){var _=gu(MS),g;try{for(_.s();!(g=_.n()).done;){var d=g.value;if(d()===!1)return!1}}catch(N){_.e(N)}finally{_.f()}}else if(Vt instanceof u_.IncomingResponse){var A=gu(US),S;try{for(A.s();!(S=A.n()).done;){var R=S.value;if(R()===!1)return!1}}catch(N){A.e(N)}finally{A.f()}}return!0};function LS(){if(Vt.s("to").uri.scheme!=="sip")return Zo(416),!1}function qS(){if(!Vt.to_tag&&Vt.call_id.substr(0,5)===as.configuration.jssip_id)return Zo(482),!1}function HS(){var o=Fc.str_utf8_length(Vt.body),n=Vt.getHeader("content-length");if(o<n)return Zo(400),!1}function zS(){var o=Vt.from_tag,n=Vt.call_id,r=Vt.cseq,a;if(!Vt.to_tag)if(Vt.method===l_.INVITE){if(as._transactions.ist[Vt.via_branch])return!1;for(var c in as._transactions.ist)if(Object.prototype.hasOwnProperty.call(as._transactions.ist,c)&&(a=as._transactions.ist[c],a.request.from_tag===o&&a.request.call_id===n&&a.request.cseq===r))return Zo(482),!1}else{if(as._transactions.nist[Vt.via_branch])return!1;for(var e in as._transactions.nist)if(Object.prototype.hasOwnProperty.call(as._transactions.nist,e)&&(a=as._transactions.nist[e],a.request.from_tag===o&&a.request.call_id===n&&a.request.cseq===r))return Zo(482),!1}}function FS(){if(Vt.getHeaders("via").length>1)return Bc.debug("more than one Via header field present in the response, dropping the response"),!1}function BS(){var o=Fc.str_utf8_length(Vt.body),n=Vt.getHeader("content-length");if(o<n)return Bc.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function VS(){for(var o=["from","to","call_id","cseq","via"],n=0,r=o;n<r.length;n++){var a=r[n];if(!Vt.hasHeader(a))return Bc.debug("missing mandatory header field : ".concat(a,", dropping the response")),!1}}function Zo(o){var n=Vt.getHeaders("via"),r,a="SIP/2.0 ".concat(o," ").concat(l_.REASON_PHRASE[o],`\r
|
|
65
|
+
`),c=gu(n),e;try{for(c.s();!(e=c.n()).done;){var _=e.value;a+="Via: ".concat(_,`\r
|
|
66
66
|
`)}}catch(g){c.e(g)}finally{c.f()}r=Vt.getHeader("To"),Vt.to_tag||(r+=";tag=".concat(Fc.newTag())),a+="To: ".concat(r,`\r
|
|
67
67
|
`),a+="From: ".concat(Vt.getHeader("From"),`\r
|
|
68
68
|
`),a+="Call-ID: ".concat(Vt.call_id,`\r
|
|
69
69
|
`),a+="CSeq: ".concat(Vt.cseq," ").concat(Vt.method,`\r
|
|
70
70
|
`),a+=`\r
|
|
71
71
|
`,c_.send(a)}var Vc={};function d_(o,n){var r;if(typeof Symbol>"u"||o[Symbol.iterator]==null){if(Array.isArray(o)||(r=jS(o))||n&&o&&typeof o.length=="number"){r&&(o=r);var a=0,c=function(){};return{s:c,n:function(){return a>=o.length?{done:!0}:{done:!1,value:o[a++]}},e:function(d){throw d},f:c}}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 e=!0,f=!1,g;return{s:function(){r=o[Symbol.iterator]()},n:function(){var d=r.next();return e=d.done,d},e:function(d){f=!0,g=d},f:function(){try{!e&&r.return!=null&&r.return()}finally{if(f)throw g}}}}function jS(o,n){if(o){if(typeof o=="string")return h_(o,n);var r=Object.prototype.toString.call(o).slice(8,-1);if(r==="Object"&&o.constructor&&(r=o.constructor.name),r==="Map"||r==="Set")return Array.from(o);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return h_(o,n)}}function h_(o,n){(n==null||n>o.length)&&(n=o.length);for(var r=0,a=new Array(n);r<n;r++)a[r]=o[r];return a}var Xa=Bn(),ma=dn,jc=ss(),p_=oi(),Gc=Lc,Wc=ai;Vc.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:ma.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:ma.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:ma.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(Xa.createRandomToken(12),".invalid")};var yu={mandatory:{sockets:function(o){var n=[];if(Gc.isSocket(o))n.push({socket:o});else if(Array.isArray(o)&&o.length){var r=d_(o),a;try{for(r.s();!(a=r.n()).done;){var c=a.value;Object.prototype.hasOwnProperty.call(c,"socket")&&Gc.isSocket(c.socket)?n.push(c):Gc.isSocket(c)&&n.push({socket:c})}}catch(e){r.e(e)}finally{r.f()}}else return;return n},uri:function(o){/^sip:/i.test(o)||(o="".concat(ma.SIP,":").concat(o));var n=p_.parse(o);if(n)return n.user?n:void 0}},optional:{authorization_user:function(o){if(jc.parse('"'.concat(o,'"'),"quoted_string")!==-1)return o},authorization_jwt:function(o){if(typeof o=="string")return o},user_agent:function(o){if(typeof o=="string")return o},connection_recovery_max_interval:function(o){if(Xa.isDecimal(o)){var n=Number(o);if(n>0)return n}},connection_recovery_min_interval:function(o){if(Xa.isDecimal(o)){var n=Number(o);if(n>0)return n}},contact_uri:function(o){if(typeof o=="string"){var n=jc.parse(o,"SIP_URI");if(n!==-1)return n}},display_name:function(o){return o},instance_id:function(o){if(/^uuid:/i.test(o)&&(o=o.substr(5)),jc.parse(o,"uuid")!==-1)return o},no_answer_timeout:function(o){if(Xa.isDecimal(o)){var n=Number(o);if(n>0)return n}},session_timers:function(o){if(typeof o=="boolean")return o},session_timers_refresh_method:function(o){if(typeof o=="string"&&(o=o.toUpperCase(),o===ma.INVITE||o===ma.UPDATE))return o},session_timers_force_refresher:function(o){if(typeof o=="boolean")return o},password:function(o){return String(o)},realm:function(o){return String(o)},ha1:function(o){return String(o)},register:function(o){if(typeof o=="boolean")return o},register_expires:function(o){if(Xa.isDecimal(o)){var n=Number(o);if(n>0)return n}},registrar_server:function(o){/^sip:/i.test(o)||(o="".concat(ma.SIP,":").concat(o));var n=p_.parse(o);if(n)return n.user?void 0:n},use_preloaded_route:function(o){if(typeof o=="boolean")return o},extra_headers:function(o){var n=[];if(Array.isArray(o)&&o.length){var r=d_(o),a;try{for(r.s();!(a=r.n()).done;){var c=a.value;typeof c=="string"&&n.push(c)}}catch(e){r.e(e)}finally{r.f()}}else return;return n}}};Vc.load=function(o,n){for(var r in yu.mandatory)if(n.hasOwnProperty(r)){var a=n[r],c=yu.mandatory[r](a);if(c!==void 0)o[r]=c;else throw new Wc.ConfigurationError(r,a)}else throw new Wc.ConfigurationError(r);for(var e in yu.optional)if(n.hasOwnProperty(e)){var f=n[e];if(Xa.isEmpty(f))continue;var g=yu.optional[e](f);if(g!==void 0)o[e]=g;else throw new Wc.ConfigurationError(e,f)}};function vu(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?vu=function(n){return typeof n}:vu=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},vu(o)}function GS(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function __(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function f_(o,n,r){return n&&__(o.prototype,n),r&&__(o,r),o}function WS(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Kc(o,n)}function Kc(o,n){return Kc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Kc(o,n)}function KS(o){var n=XS();return function(){var r=Tu(o),a;if(n){var c=Tu(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return YS(this,a)}}function YS(o,n){return n&&(vu(n)==="object"||typeof n=="function")?n:m_(o)}function m_(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function XS(){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 Tu(o){return Tu=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Tu(o)}var JS=Tn.EventEmitter,QS=bn,In=dn,ZS=H0,g_=Yw,y_=lS,v_=TS,Yc=Vo,eE=IS,bu=Bn(),tE=ai,nE=oi(),rE=s_,Xc=Os,sE=PS,Jc=Vc,Wt=new QS("UA"),Rn={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},iE=function(o){WS(r,o);var n=KS(r);f_(r,null,[{key:"C",get:function(){return Rn}}]);function r(a){var c;if(GS(this,r),Wt.debug("new() [configuration:%o]",a),c=n.call(this),c._cache={credentials:{}},c._configuration=Object.assign({},Jc.settings),c._dynConfiguration={},c._dialogs={},c._applicants={},c._sessions={},c._transport=null,c._contact=null,c._status=Rn.STATUS_INIT,c._error=null,c._transactions={nist:{},nict:{},ist:{},ict:{}},c._data={},c._closeTimer=null,a===void 0)throw new TypeError("Not enough arguments");try{c._loadConfig(a)}catch(e){throw c._status=Rn.STATUS_NOT_READY,c._error=Rn.CONFIGURATION_ERROR,e}return c._registrator=new ZS(m_(c)),c}return f_(r,[{key:"start",value:function(){Wt.debug("start()"),this._status===Rn.STATUS_INIT?this._transport.connect():this._status===Rn.STATUS_USER_CLOSED?(Wt.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Rn.STATUS_INIT,this._transport.connect()):this._status===Rn.STATUS_READY?Wt.debug("UA is in READY status, not restarted"):Wt.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}},{key:"register",value:function(){Wt.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}},{key:"unregister",value:function(a){Wt.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,c){Wt.debug("call()");var e=new g_(this);return e.connect(a,c),e}},{key:"sendMessage",value:function(a,c,e){Wt.debug("sendMessage()");var f=new y_(this);return f.send(a,c,e),f}},{key:"sendOptions",value:function(a,c,e){Wt.debug("sendOptions()");var f=new v_(this);return f.send(a,c,e),f}},{key:"terminateSessions",value:function(a){Wt.debug("terminateSessions()");for(var c in this._sessions)this._sessions[c].isEnded()||this._sessions[c].terminate(a)}},{key:"stop",value:function(){var a=this;if(Wt.debug("stop()"),this._dynConfiguration={},this._status===Rn.STATUS_USER_CLOSED){Wt.debug("UA already closed");return}this._registrator.close();var c=Object.keys(this._sessions).length;for(var e in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,e)){Wt.debug("closing session ".concat(e));try{this._sessions[e].terminate()}catch{}}for(var f in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,f))try{this._applicants[f].close()}catch{}this._status=Rn.STATUS_USER_CLOSED;var g=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;g===0&&c===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){a._closeTimer=null,a._transport.disconnect()},2e3)}},{key:"normalizeTarget",value:function(a){return bu.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:Wt.warn('get() | cannot get "%s" parameter in runtime',a);return}}},{key:"set",value:function(a,c){switch(a){case"authorization_user":{this._configuration.authorization_user=String(c);break}case"password":{this._configuration.password=String(c);break}case"realm":{this._configuration.realm=String(c);break}case"ha1":{this._configuration.ha1=String(c),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(c);break}case"display_name":{this._configuration.display_name=c;break}default:return Wt.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,c){this._applicants[a]=a,this.emit("newMessage",c)}},{key:"newOptions",value:function(a,c){this._applicants[a]=a,this.emit("newOptions",c)}},{key:"destroyMessage",value:function(a){delete this._applicants[a]}},{key:"newRTCSession",value:function(a,c){this._sessions[a.id]=a,this.emit("newRTCSession",c)}},{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 c=a.method;if(a.ruri.user!==this._configuration.uri.user&&a.ruri.user!==this._contact.uri.user){Wt.debug("Request-URI does not point to us"),a.method!==In.ACK&&a.reply_sl(404);return}if(a.ruri.scheme===In.SIPS){a.reply_sl(416);return}if(!Yc.checkTransaction(this,a)){if(c===In.INVITE?new Yc.InviteServerTransaction(this,this._transport,a):c!==In.ACK&&c!==In.CANCEL&&new Yc.NonInviteServerTransaction(this,this._transport,a),c===In.OPTIONS){if(this.listeners("newOptions").length===0){a.reply(200);return}var e=new v_(this);e.init_incoming(a)}else if(c===In.MESSAGE){if(this.listeners("newMessage").length===0){a.reply(405);return}var f=new y_(this);f.init_incoming(a)}else if(c===In.INVITE&&!a.to_tag&&this.listeners("newRTCSession").length===0){a.reply(405);return}var g,d;if(a.to_tag)g=this._findDialog(a.call_id,a.from_tag,a.to_tag),g?g.receiveRequest(a):c===In.NOTIFY?(d=this._findSession(a),d?d.receiveRequest(a):(Wt.debug("received NOTIFY request for a non existent subscription"),a.reply(481,"Subscription does not exist"))):c!==In.ACK&&a.reply(481);else switch(c){case In.INVITE:if(window.RTCPeerConnection)if(a.hasHeader("replaces")){var A=a.replaces;g=this._findDialog(A.call_id,A.from_tag,A.to_tag),g?(d=g.owner,d.isEnded()?a.reply(603):d.receiveRequest(a)):a.reply(481)}else d=new g_(this),d.init_incoming(a);else Wt.warn("INVITE received but WebRTC is not supported"),a.reply(488);break;case In.BYE:a.reply(481);break;case In.CANCEL:d=this._findSession(a),d?d.receiveRequest(a):Wt.debug("received CANCEL request for a non existent session");break;case In.ACK:break;case In.NOTIFY:this.emit("sipEvent",{event:a.event,request:a}),a.reply(200);break;default:a.reply(405);break}}}},{key:"_findSession",value:function(a){var c=a.call_id,e=a.from_tag,f=a.to_tag,g=c+e,d=this._sessions[g],A=c+f,S=this._sessions[A];return d||S||null}},{key:"_findDialog",value:function(a,c,e){var f=a+c+e,g=this._dialogs[f];return g||(f=a+e+c,g=this._dialogs[f],g||null)}},{key:"_loadConfig",value:function(a){try{Jc.load(this._configuration,a)}catch(A){throw A}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=bu.newUUID()),this._configuration.jssip_id=bu.createRandomToken(5);var c=this._configuration.uri.clone();c.user=null,this._configuration.hostport_params=c.toString().replace(/^sip:/i,"");try{this._transport=new eE(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=aE.bind(this),this._transport.onconnect=oE.bind(this),this._transport.ondisconnect=lE.bind(this),this._transport.ondata=uE.bind(this)}catch(A){throw Wt.warn(A),new tE.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 e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new nE("sip",bu.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 A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},S=A.anonymous||null,R=A.outbound||null,N="<";return S?N+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":N+=this.pub_gruu||this.uri.toString(),R&&(S?!this.temp_gruu:!this.pub_gruu)&&(N+=";ob"),N+=">",N}};var f=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var g in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,g)&&(f.indexOf(g)!==-1?Object.defineProperty(this._configuration,g,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,g,{writable:!1,configurable:!1}));Wt.debug("configuration parameters after validation:");for(var d in this._configuration)if(Object.prototype.hasOwnProperty.call(Jc.settings,d))switch(d){case"uri":case"registrar_server":Wt.debug("- ".concat(d,": ").concat(this._configuration[d]));break;case"password":case"ha1":case"authorization_jwt":Wt.debug("- ".concat(d,": NOT SHOWN"));break;default:Wt.debug("- ".concat(d,": ").concat(JSON.stringify(this._configuration[d])))}}},{key:"C",get:function(){return Rn}},{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}}]),r}(JS);function aE(o){this.emit("connecting",o)}function oE(o){this._status!==Rn.STATUS_USER_CLOSED&&(this._status=Rn.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function lE(o){for(var n=["nict","ict","nist","ist"],r=0,a=n;r<a.length;r++){var c=a[r];for(var e in this._transactions[c])Object.prototype.hasOwnProperty.call(this._transactions[c],e)&&this._transactions[c][e].onTransportError()}this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==Rn.STATUS_USER_CLOSED&&(this._status=Rn.STATUS_NOT_READY,this._error=Rn.NETWORK_ERROR)}function uE(o){var n=o.transport,r=o.message;if(r=rE.parseMessage(r,this),!!r&&!(this._status===Rn.STATUS_USER_CLOSED&&r instanceof Xc.IncomingRequest)&&sE(r,this,n)){if(r instanceof Xc.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Xc.IncomingResponse){var a;switch(r.method){case In.INVITE:a=this._transactions.ict[r.via_branch],a&&a.receiveResponse(r);break;case In.ACK:break;default:a=this._transactions.nict[r.via_branch],a&&a.receiveResponse(r);break}}}}function cE(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function T_(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function dE(o,n,r){return n&&T_(o.prototype,n),r&&T_(o,r),o}var hE=bn,pE=ss(),Xn=new hE("WebSocketInterface"),_E=function(){function o(n){cE(this,o),Xn.debug('new() [url:"%s"]',n),this._url=n,this._sip_uri=null,this._via_transport=null,this._ws=null;var r=pE.parse(n,"absoluteURI");if(r===-1)throw Xn.warn("invalid WebSocket URI: ".concat(n)),new TypeError("Invalid argument: ".concat(n));if(r.scheme!=="wss"&&r.scheme!=="ws")throw Xn.warn("invalid WebSocket URI scheme: ".concat(r.scheme)),new TypeError("Invalid argument: ".concat(n));this._sip_uri="sip:".concat(r.host).concat(r.port?":".concat(r.port):"",";transport=ws"),this._via_transport=r.scheme.toUpperCase()}return dE(o,[{key:"connect",value:function(){if(Xn.debug("connect()"),this.isConnected()){Xn.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){Xn.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),Xn.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(){Xn.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 Xn.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(Xn.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(){Xn.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(n){var r=n.wasClean,a=n.code,c=n.reason;Xn.debug("WebSocket ".concat(this._url," closed")),r===!1&&Xn.debug("WebSocket abrupt disconnection"),this.ondisconnect(!r,a,c)}},{key:"_onMessage",value:function(n){var r=n.data;Xn.debug("received WebSocket message"),this.ondata(r)}},{key:"_onError",value:function(n){Xn.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}}]),o}(),Qc=Pl,fE=dn,mE=ai,gE=Bn(),yE=iE,vE=oi(),TE=cc(),bE=ss(),wE=_E,SE=Wa("JsSIP");SE("version %s",Qc.version);var b_={C:fE,Exceptions:mE,Utils:gE,UA:yE,URI:vE,NameAddrHeader:TE,WebSocketInterface:wE,Grammar:bE,debug:Wa,get name(){return Qc.title},get version(){return Qc.version}};const Ja=Wa,Qa="JsSIP";var mn=class{constructor(o){o?(this._debug=Ja.default(`${Qa}:${o}`),this._warn=Ja.default(`${Qa}:WARN:${o}`),this._error=Ja.default(`${Qa}:ERROR:${o}`)):(this._debug=Ja.default(Qa),this._warn=Ja.default(`${Qa}:WARN`),this._error=Ja.default(`${Qa}: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 wu=Qt(mn),w_=Pl;var bt={USER_AGENT:`${w_.title} ${w_.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 oe=Qt(bt);var ln={},Zc,S_;function ed(){if(S_)return Zc;S_=1;const o=Ms(),n=Hr();return Zc=class mb{static parse(a){if(a=n.parse(a,"Name_Addr_Header"),a!==-1)return a}constructor(a,c,e){if(!a||!(a instanceof o))throw new TypeError('missing or invalid "uri" parameter');this._uri=a,this._parameters={},this.display_name=c;for(const f in e)Object.prototype.hasOwnProperty.call(e,f)&&this.setParam(f,e[f])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(a){this._display_name=a===0?"0":a}setParam(a,c){a&&(this._parameters[a.toLowerCase()]=typeof c>"u"||c===null?null:c.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 c=this._parameters[a];return delete this._parameters[a],c}}clearParams(){this._parameters={}}clone(){return new mb(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(a){return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let a=this._display_name?`"${this._quote(this._display_name)}" `:"";a+=`<${this._uri.toString()}>`;for(const c in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,c)&&(a+=`;${c}`,this._parameters[c]!==null&&(a+=`=${this._parameters[c]}`));return a}},Zc}var E_,C_;function Hr(){return C_||(C_=1,E_=function(){function o(r){return'"'+r.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 n={parse:function(r,a){var c={CRLF:A,DIGIT:S,ALPHA:R,HEXDIG:N,WSP:H,OCTET:W,DQUOTE:G,SP:K,HTAB:ae,alphanum:ee,reserved:De,unreserved:X,mark:re,escaped:be,LWS:Ne,SWS:Q,HCOLON:ce,TEXT_UTF8_TRIM:me,TEXT_UTF8char:_e,UTF8_NONASCII:ue,UTF8_CONT:ye,LHEX:Re,token:J,token_nodot:Se,separators:$e,word:zt,STAR:Ae,SLASH:fe,EQUAL:se,LPAREN:st,RPAREN:We,RAQUOT:ht,LAQUOT:It,COMMA:qe,SEMI:Ue,COLON:wt,LDQUOT:Yt,RDQUOT:Xe,comment:Je,ctext:ut,quoted_string:_t,quoted_string_clean:mt,qdtext:Le,quoted_pair:Pe,SIP_URI_noparams:Ze,SIP_URI:Tt,uri_scheme:qt,uri_scheme_sips:rn,uri_scheme_sip:Dt,userinfo:Wn,user:Pn,user_unreserved:Bs,password:Aa,hostport:jr,host:ar,hostname:_n,domainlabel:Gr,toplabel:yi,IPv6reference:Wr,IPv6address:Kr,h16:de,ls32:Pt,IPv4address:or,dec_octet:lr,port:gn,uri_parameters:Vs,uri_parameter:$r,transport_param:vi,user_param:Ti,method_param:js,ttl_param:bi,maddr_param:Gs,lr_param:wi,other_param:Ws,pname:Si,pvalue:Ks,paramchar:Qn,param_unreserved:ds,headers:Yr,header:mr,hname:Ei,hvalue:Ci,hnv_unreserved:ur,Request_Response:Ia,Request_Line:$t,Request_URI:gr,absoluteURI:yn,hier_part:hs,net_path:Et,abs_path:yr,opaque_part:Ai,uric:vr,uric_no_slash:Ii,path_segments:Ri,segment:xr,param:Tr,pchar:cr,scheme:$i,authority:Ra,srvr:br,reg_name:Zn,query:wr,SIP_Version:Or,INVITEm:ps,ACKm:Ys,OPTIONSm:Xs,BYEm:Js,CANCELm:rt,REGISTERm:Qs,SUBSCRIBEm:xi,NOTIFYm:Oi,REFERm:ki,Method:kr,Status_Line:Di,Status_Code:Zs,extension_code:Ni,Reason_Phrase:vt,Allow_Events:Sr,Call_ID:lo,Contact:_s,contact_param:ne,name_addr:fn,display_name:Dr,contact_params:fs,c_p_q:Mi,c_p_expires:ct,delta_seconds:vn,qvalue:Ui,generic_param:gt,gen_value:ei,Content_Disposition:$a,disp_type:Pi,disp_param:Xr,handling_param:Li,Content_Encoding:xa,Content_Length:Oa,Content_Type:ka,media_type:qi,m_type:Hi,discrete_type:Da,composite_type:Jr,extension_token:Nr,x_token:zi,m_subtype:Na,m_parameter:Qr,m_value:ti,CSeq:Fi,CSeq_value:ms,Expires:uo,Event:co,event_type:er,From:Ma,from_param:gs,tag_param:ys,Max_Forwards:El,Min_Expires:ho,Name_Addr_Header:Ct,Proxy_Authenticate:Ft,challenge:dr,other_challenge:vs,auth_param:Nt,digest_cln:Gt,realm:Qe,realm_value:Ut,domain:ni,URI:Kn,nonce:hr,nonce_value:Ke,opaque:Zr,stale:le,algorithm:Ge,qop_options:Bi,qop_value:Er,Proxy_Require:po,Record_Route:_o,rec_route:at,Reason:fo,reason_param:es,reason_cause:Vi,Require:mo,Route:go,route_param:Mr,Subscription_State:Ln,substate_value:ji,subexp_params:Ts,event_reason_value:pr,Subject:yo,Supported:vo,To,to_param:bs,Via:bo,via_param:Ur,via_params:ws,via_ttl:Gi,via_maddr:Wi,via_received:Ki,via_branch:qn,response_port:Yi,rport:Xi,sent_protocol:Ji,protocol_name:Qi,transport:Zi,sent_by:ea,via_host:ta,via_port:na,ttl:Ss,WWW_Authenticate:wo,Session_Expires:Cl,s_e_expires:Hn,s_e_params:Es,s_e_refresher:Cs,extension_header:Ua,header_value:zn,message_body:So,uuid_URI:Eo,uuid:ra,hex4:sn,hex8:sa,hex12:ia,Refer_To:Co,Replaces:Ao,call_id:aa,replaces_param:As,to_tag:Fn,from_tag:oa,early_flag:la};if(a!==void 0){if(c[a]===void 0)throw new Error("Invalid rule name: "+o(a)+".")}else a="CRLF";var e=0,f=0,g=[];function d(t){e<f||(e>f&&(f=e,g=[]),g.push(t))}function A(){var t;return r.substr(e,2)===`\r
|
|
72
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var e=!0,_=!1,g;return{s:function(){r=o[Symbol.iterator]()},n:function(){var d=r.next();return e=d.done,d},e:function(d){_=!0,g=d},f:function(){try{!e&&r.return!=null&&r.return()}finally{if(_)throw g}}}}function jS(o,n){if(o){if(typeof o=="string")return h_(o,n);var r=Object.prototype.toString.call(o).slice(8,-1);if(r==="Object"&&o.constructor&&(r=o.constructor.name),r==="Map"||r==="Set")return Array.from(o);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return h_(o,n)}}function h_(o,n){(n==null||n>o.length)&&(n=o.length);for(var r=0,a=new Array(n);r<n;r++)a[r]=o[r];return a}var Xa=Bn(),ma=dn,jc=ss(),p_=oi(),Gc=Lc,Wc=ai;Vc.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:ma.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:ma.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:ma.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(Xa.createRandomToken(12),".invalid")};var yu={mandatory:{sockets:function(o){var n=[];if(Gc.isSocket(o))n.push({socket:o});else if(Array.isArray(o)&&o.length){var r=d_(o),a;try{for(r.s();!(a=r.n()).done;){var c=a.value;Object.prototype.hasOwnProperty.call(c,"socket")&&Gc.isSocket(c.socket)?n.push(c):Gc.isSocket(c)&&n.push({socket:c})}}catch(e){r.e(e)}finally{r.f()}}else return;return n},uri:function(o){/^sip:/i.test(o)||(o="".concat(ma.SIP,":").concat(o));var n=p_.parse(o);if(n)return n.user?n:void 0}},optional:{authorization_user:function(o){if(jc.parse('"'.concat(o,'"'),"quoted_string")!==-1)return o},authorization_jwt:function(o){if(typeof o=="string")return o},user_agent:function(o){if(typeof o=="string")return o},connection_recovery_max_interval:function(o){if(Xa.isDecimal(o)){var n=Number(o);if(n>0)return n}},connection_recovery_min_interval:function(o){if(Xa.isDecimal(o)){var n=Number(o);if(n>0)return n}},contact_uri:function(o){if(typeof o=="string"){var n=jc.parse(o,"SIP_URI");if(n!==-1)return n}},display_name:function(o){return o},instance_id:function(o){if(/^uuid:/i.test(o)&&(o=o.substr(5)),jc.parse(o,"uuid")!==-1)return o},no_answer_timeout:function(o){if(Xa.isDecimal(o)){var n=Number(o);if(n>0)return n}},session_timers:function(o){if(typeof o=="boolean")return o},session_timers_refresh_method:function(o){if(typeof o=="string"&&(o=o.toUpperCase(),o===ma.INVITE||o===ma.UPDATE))return o},session_timers_force_refresher:function(o){if(typeof o=="boolean")return o},password:function(o){return String(o)},realm:function(o){return String(o)},ha1:function(o){return String(o)},register:function(o){if(typeof o=="boolean")return o},register_expires:function(o){if(Xa.isDecimal(o)){var n=Number(o);if(n>0)return n}},registrar_server:function(o){/^sip:/i.test(o)||(o="".concat(ma.SIP,":").concat(o));var n=p_.parse(o);if(n)return n.user?void 0:n},use_preloaded_route:function(o){if(typeof o=="boolean")return o},extra_headers:function(o){var n=[];if(Array.isArray(o)&&o.length){var r=d_(o),a;try{for(r.s();!(a=r.n()).done;){var c=a.value;typeof c=="string"&&n.push(c)}}catch(e){r.e(e)}finally{r.f()}}else return;return n}}};Vc.load=function(o,n){for(var r in yu.mandatory)if(n.hasOwnProperty(r)){var a=n[r],c=yu.mandatory[r](a);if(c!==void 0)o[r]=c;else throw new Wc.ConfigurationError(r,a)}else throw new Wc.ConfigurationError(r);for(var e in yu.optional)if(n.hasOwnProperty(e)){var _=n[e];if(Xa.isEmpty(_))continue;var g=yu.optional[e](_);if(g!==void 0)o[e]=g;else throw new Wc.ConfigurationError(e,_)}};function vu(o){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?vu=function(n){return typeof n}:vu=function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},vu(o)}function GS(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function __(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function f_(o,n,r){return n&&__(o.prototype,n),r&&__(o,r),o}function WS(o,n){if(typeof n!="function"&&n!==null)throw new TypeError("Super expression must either be null or a function");o.prototype=Object.create(n&&n.prototype,{constructor:{value:o,writable:!0,configurable:!0}}),n&&Kc(o,n)}function Kc(o,n){return Kc=Object.setPrototypeOf||function(r,a){return r.__proto__=a,r},Kc(o,n)}function KS(o){var n=XS();return function(){var r=Tu(o),a;if(n){var c=Tu(this).constructor;a=Reflect.construct(r,arguments,c)}else a=r.apply(this,arguments);return YS(this,a)}}function YS(o,n){return n&&(vu(n)==="object"||typeof n=="function")?n:m_(o)}function m_(o){if(o===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return o}function XS(){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 Tu(o){return Tu=Object.setPrototypeOf?Object.getPrototypeOf:function(n){return n.__proto__||Object.getPrototypeOf(n)},Tu(o)}var JS=Tn.EventEmitter,QS=bn,In=dn,ZS=H0,g_=Yw,y_=lS,v_=TS,Yc=Vo,eE=IS,bu=Bn(),tE=ai,nE=oi(),rE=s_,Xc=Os,sE=PS,Jc=Vc,Wt=new QS("UA"),Rn={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},iE=function(o){WS(r,o);var n=KS(r);f_(r,null,[{key:"C",get:function(){return Rn}}]);function r(a){var c;if(GS(this,r),Wt.debug("new() [configuration:%o]",a),c=n.call(this),c._cache={credentials:{}},c._configuration=Object.assign({},Jc.settings),c._dynConfiguration={},c._dialogs={},c._applicants={},c._sessions={},c._transport=null,c._contact=null,c._status=Rn.STATUS_INIT,c._error=null,c._transactions={nist:{},nict:{},ist:{},ict:{}},c._data={},c._closeTimer=null,a===void 0)throw new TypeError("Not enough arguments");try{c._loadConfig(a)}catch(e){throw c._status=Rn.STATUS_NOT_READY,c._error=Rn.CONFIGURATION_ERROR,e}return c._registrator=new ZS(m_(c)),c}return f_(r,[{key:"start",value:function(){Wt.debug("start()"),this._status===Rn.STATUS_INIT?this._transport.connect():this._status===Rn.STATUS_USER_CLOSED?(Wt.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Rn.STATUS_INIT,this._transport.connect()):this._status===Rn.STATUS_READY?Wt.debug("UA is in READY status, not restarted"):Wt.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}},{key:"register",value:function(){Wt.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}},{key:"unregister",value:function(a){Wt.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,c){Wt.debug("call()");var e=new g_(this);return e.connect(a,c),e}},{key:"sendMessage",value:function(a,c,e){Wt.debug("sendMessage()");var _=new y_(this);return _.send(a,c,e),_}},{key:"sendOptions",value:function(a,c,e){Wt.debug("sendOptions()");var _=new v_(this);return _.send(a,c,e),_}},{key:"terminateSessions",value:function(a){Wt.debug("terminateSessions()");for(var c in this._sessions)this._sessions[c].isEnded()||this._sessions[c].terminate(a)}},{key:"stop",value:function(){var a=this;if(Wt.debug("stop()"),this._dynConfiguration={},this._status===Rn.STATUS_USER_CLOSED){Wt.debug("UA already closed");return}this._registrator.close();var c=Object.keys(this._sessions).length;for(var e in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,e)){Wt.debug("closing session ".concat(e));try{this._sessions[e].terminate()}catch{}}for(var _ in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,_))try{this._applicants[_].close()}catch{}this._status=Rn.STATUS_USER_CLOSED;var g=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;g===0&&c===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){a._closeTimer=null,a._transport.disconnect()},2e3)}},{key:"normalizeTarget",value:function(a){return bu.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:Wt.warn('get() | cannot get "%s" parameter in runtime',a);return}}},{key:"set",value:function(a,c){switch(a){case"authorization_user":{this._configuration.authorization_user=String(c);break}case"password":{this._configuration.password=String(c);break}case"realm":{this._configuration.realm=String(c);break}case"ha1":{this._configuration.ha1=String(c),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(c);break}case"display_name":{this._configuration.display_name=c;break}default:return Wt.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,c){this._applicants[a]=a,this.emit("newMessage",c)}},{key:"newOptions",value:function(a,c){this._applicants[a]=a,this.emit("newOptions",c)}},{key:"destroyMessage",value:function(a){delete this._applicants[a]}},{key:"newRTCSession",value:function(a,c){this._sessions[a.id]=a,this.emit("newRTCSession",c)}},{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 c=a.method;if(a.ruri.user!==this._configuration.uri.user&&a.ruri.user!==this._contact.uri.user){Wt.debug("Request-URI does not point to us"),a.method!==In.ACK&&a.reply_sl(404);return}if(a.ruri.scheme===In.SIPS){a.reply_sl(416);return}if(!Yc.checkTransaction(this,a)){if(c===In.INVITE?new Yc.InviteServerTransaction(this,this._transport,a):c!==In.ACK&&c!==In.CANCEL&&new Yc.NonInviteServerTransaction(this,this._transport,a),c===In.OPTIONS){if(this.listeners("newOptions").length===0){a.reply(200);return}var e=new v_(this);e.init_incoming(a)}else if(c===In.MESSAGE){if(this.listeners("newMessage").length===0){a.reply(405);return}var _=new y_(this);_.init_incoming(a)}else if(c===In.INVITE&&!a.to_tag&&this.listeners("newRTCSession").length===0){a.reply(405);return}var g,d;if(a.to_tag)g=this._findDialog(a.call_id,a.from_tag,a.to_tag),g?g.receiveRequest(a):c===In.NOTIFY?(d=this._findSession(a),d?d.receiveRequest(a):(Wt.debug("received NOTIFY request for a non existent subscription"),a.reply(481,"Subscription does not exist"))):c!==In.ACK&&a.reply(481);else switch(c){case In.INVITE:if(window.RTCPeerConnection)if(a.hasHeader("replaces")){var A=a.replaces;g=this._findDialog(A.call_id,A.from_tag,A.to_tag),g?(d=g.owner,d.isEnded()?a.reply(603):d.receiveRequest(a)):a.reply(481)}else d=new g_(this),d.init_incoming(a);else Wt.warn("INVITE received but WebRTC is not supported"),a.reply(488);break;case In.BYE:a.reply(481);break;case In.CANCEL:d=this._findSession(a),d?d.receiveRequest(a):Wt.debug("received CANCEL request for a non existent session");break;case In.ACK:break;case In.NOTIFY:this.emit("sipEvent",{event:a.event,request:a}),a.reply(200);break;default:a.reply(405);break}}}},{key:"_findSession",value:function(a){var c=a.call_id,e=a.from_tag,_=a.to_tag,g=c+e,d=this._sessions[g],A=c+_,S=this._sessions[A];return d||S||null}},{key:"_findDialog",value:function(a,c,e){var _=a+c+e,g=this._dialogs[_];return g||(_=a+e+c,g=this._dialogs[_],g||null)}},{key:"_loadConfig",value:function(a){try{Jc.load(this._configuration,a)}catch(A){throw A}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=bu.newUUID()),this._configuration.jssip_id=bu.createRandomToken(5);var c=this._configuration.uri.clone();c.user=null,this._configuration.hostport_params=c.toString().replace(/^sip:/i,"");try{this._transport=new eE(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=aE.bind(this),this._transport.onconnect=oE.bind(this),this._transport.ondisconnect=lE.bind(this),this._transport.ondata=uE.bind(this)}catch(A){throw Wt.warn(A),new tE.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 e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new nE("sip",bu.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 A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},S=A.anonymous||null,R=A.outbound||null,N="<";return S?N+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":N+=this.pub_gruu||this.uri.toString(),R&&(S?!this.temp_gruu:!this.pub_gruu)&&(N+=";ob"),N+=">",N}};var _=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var g in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,g)&&(_.indexOf(g)!==-1?Object.defineProperty(this._configuration,g,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,g,{writable:!1,configurable:!1}));Wt.debug("configuration parameters after validation:");for(var d in this._configuration)if(Object.prototype.hasOwnProperty.call(Jc.settings,d))switch(d){case"uri":case"registrar_server":Wt.debug("- ".concat(d,": ").concat(this._configuration[d]));break;case"password":case"ha1":case"authorization_jwt":Wt.debug("- ".concat(d,": NOT SHOWN"));break;default:Wt.debug("- ".concat(d,": ").concat(JSON.stringify(this._configuration[d])))}}},{key:"C",get:function(){return Rn}},{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}}]),r}(JS);function aE(o){this.emit("connecting",o)}function oE(o){this._status!==Rn.STATUS_USER_CLOSED&&(this._status=Rn.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function lE(o){for(var n=["nict","ict","nist","ist"],r=0,a=n;r<a.length;r++){var c=a[r];for(var e in this._transactions[c])Object.prototype.hasOwnProperty.call(this._transactions[c],e)&&this._transactions[c][e].onTransportError()}this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==Rn.STATUS_USER_CLOSED&&(this._status=Rn.STATUS_NOT_READY,this._error=Rn.NETWORK_ERROR)}function uE(o){var n=o.transport,r=o.message;if(r=rE.parseMessage(r,this),!!r&&!(this._status===Rn.STATUS_USER_CLOSED&&r instanceof Xc.IncomingRequest)&&sE(r,this,n)){if(r instanceof Xc.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Xc.IncomingResponse){var a;switch(r.method){case In.INVITE:a=this._transactions.ict[r.via_branch],a&&a.receiveResponse(r);break;case In.ACK:break;default:a=this._transactions.nict[r.via_branch],a&&a.receiveResponse(r);break}}}}function cE(o,n){if(!(o instanceof n))throw new TypeError("Cannot call a class as a function")}function T_(o,n){for(var r=0;r<n.length;r++){var a=n[r];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(o,a.key,a)}}function dE(o,n,r){return n&&T_(o.prototype,n),r&&T_(o,r),o}var hE=bn,pE=ss(),Xn=new hE("WebSocketInterface"),_E=function(){function o(n){cE(this,o),Xn.debug('new() [url:"%s"]',n),this._url=n,this._sip_uri=null,this._via_transport=null,this._ws=null;var r=pE.parse(n,"absoluteURI");if(r===-1)throw Xn.warn("invalid WebSocket URI: ".concat(n)),new TypeError("Invalid argument: ".concat(n));if(r.scheme!=="wss"&&r.scheme!=="ws")throw Xn.warn("invalid WebSocket URI scheme: ".concat(r.scheme)),new TypeError("Invalid argument: ".concat(n));this._sip_uri="sip:".concat(r.host).concat(r.port?":".concat(r.port):"",";transport=ws"),this._via_transport=r.scheme.toUpperCase()}return dE(o,[{key:"connect",value:function(){if(Xn.debug("connect()"),this.isConnected()){Xn.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){Xn.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),Xn.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(){Xn.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 Xn.debug("send()"),this.isConnected()?(this._ws.send(n),!0):(Xn.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(){Xn.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(n){var r=n.wasClean,a=n.code,c=n.reason;Xn.debug("WebSocket ".concat(this._url," closed")),r===!1&&Xn.debug("WebSocket abrupt disconnection"),this.ondisconnect(!r,a,c)}},{key:"_onMessage",value:function(n){var r=n.data;Xn.debug("received WebSocket message"),this.ondata(r)}},{key:"_onError",value:function(n){Xn.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}}]),o}(),Qc=Pl,fE=dn,mE=ai,gE=Bn(),yE=iE,vE=oi(),TE=cc(),bE=ss(),wE=_E,SE=Wa("JsSIP");SE("version %s",Qc.version);var b_={C:fE,Exceptions:mE,Utils:gE,UA:yE,URI:vE,NameAddrHeader:TE,WebSocketInterface:wE,Grammar:bE,debug:Wa,get name(){return Qc.title},get version(){return Qc.version}};const Ja=Wa,Qa="JsSIP";var mn=class{constructor(o){o?(this._debug=Ja.default(`${Qa}:${o}`),this._warn=Ja.default(`${Qa}:WARN:${o}`),this._error=Ja.default(`${Qa}:ERROR:${o}`)):(this._debug=Ja.default(Qa),this._warn=Ja.default(`${Qa}:WARN`),this._error=Ja.default(`${Qa}: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 wu=Qt(mn),w_=Pl;var bt={USER_AGENT:`${w_.title} ${w_.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 oe=Qt(bt);var ln={},Zc,S_;function ed(){if(S_)return Zc;S_=1;const o=Ms(),n=Hr();return Zc=class mb{static parse(a){if(a=n.parse(a,"Name_Addr_Header"),a!==-1)return a}constructor(a,c,e){if(!a||!(a instanceof o))throw new TypeError('missing or invalid "uri" parameter');this._uri=a,this._parameters={},this.display_name=c;for(const _ in e)Object.prototype.hasOwnProperty.call(e,_)&&this.setParam(_,e[_])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(a){this._display_name=a===0?"0":a}setParam(a,c){a&&(this._parameters[a.toLowerCase()]=typeof c>"u"||c===null?null:c.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 c=this._parameters[a];return delete this._parameters[a],c}}clearParams(){this._parameters={}}clone(){return new mb(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(a){return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let a=this._display_name?`"${this._quote(this._display_name)}" `:"";a+=`<${this._uri.toString()}>`;for(const c in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,c)&&(a+=`;${c}`,this._parameters[c]!==null&&(a+=`=${this._parameters[c]}`));return a}},Zc}var E_,C_;function Hr(){return C_||(C_=1,E_=function(){function o(r){return'"'+r.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 n={parse:function(r,a){var c={CRLF:A,DIGIT:S,ALPHA:R,HEXDIG:N,WSP:H,OCTET:W,DQUOTE:G,SP:K,HTAB:ae,alphanum:ee,reserved:De,unreserved:X,mark:re,escaped:be,LWS:Ne,SWS:Q,HCOLON:ce,TEXT_UTF8_TRIM:me,TEXT_UTF8char:_e,UTF8_NONASCII:ue,UTF8_CONT:ye,LHEX:Re,token:J,token_nodot:Se,separators:$e,word:zt,STAR:Ae,SLASH:fe,EQUAL:se,LPAREN:st,RPAREN:We,RAQUOT:ht,LAQUOT:It,COMMA:qe,SEMI:Ue,COLON:wt,LDQUOT:Yt,RDQUOT:Xe,comment:Je,ctext:ut,quoted_string:_t,quoted_string_clean:mt,qdtext:Le,quoted_pair:Pe,SIP_URI_noparams:Ze,SIP_URI:Tt,uri_scheme:qt,uri_scheme_sips:rn,uri_scheme_sip:Dt,userinfo:Wn,user:Pn,user_unreserved:Bs,password:Aa,hostport:jr,host:ar,hostname:_n,domainlabel:Gr,toplabel:yi,IPv6reference:Wr,IPv6address:Kr,h16:de,ls32:Pt,IPv4address:or,dec_octet:lr,port:gn,uri_parameters:Vs,uri_parameter:$r,transport_param:vi,user_param:Ti,method_param:js,ttl_param:bi,maddr_param:Gs,lr_param:wi,other_param:Ws,pname:Si,pvalue:Ks,paramchar:Qn,param_unreserved:ds,headers:Yr,header:mr,hname:Ei,hvalue:Ci,hnv_unreserved:ur,Request_Response:Ia,Request_Line:$t,Request_URI:gr,absoluteURI:yn,hier_part:hs,net_path:Et,abs_path:yr,opaque_part:Ai,uric:vr,uric_no_slash:Ii,path_segments:Ri,segment:xr,param:Tr,pchar:cr,scheme:$i,authority:Ra,srvr:br,reg_name:Zn,query:wr,SIP_Version:Or,INVITEm:ps,ACKm:Ys,OPTIONSm:Xs,BYEm:Js,CANCELm:rt,REGISTERm:Qs,SUBSCRIBEm:xi,NOTIFYm:Oi,REFERm:ki,Method:kr,Status_Line:Di,Status_Code:Zs,extension_code:Ni,Reason_Phrase:vt,Allow_Events:Sr,Call_ID:lo,Contact:_s,contact_param:ne,name_addr:fn,display_name:Dr,contact_params:fs,c_p_q:Mi,c_p_expires:ct,delta_seconds:vn,qvalue:Ui,generic_param:gt,gen_value:ei,Content_Disposition:$a,disp_type:Pi,disp_param:Xr,handling_param:Li,Content_Encoding:xa,Content_Length:Oa,Content_Type:ka,media_type:qi,m_type:Hi,discrete_type:Da,composite_type:Jr,extension_token:Nr,x_token:zi,m_subtype:Na,m_parameter:Qr,m_value:ti,CSeq:Fi,CSeq_value:ms,Expires:uo,Event:co,event_type:er,From:Ma,from_param:gs,tag_param:ys,Max_Forwards:El,Min_Expires:ho,Name_Addr_Header:Ct,Proxy_Authenticate:Ft,challenge:dr,other_challenge:vs,auth_param:Nt,digest_cln:Gt,realm:Qe,realm_value:Ut,domain:ni,URI:Kn,nonce:hr,nonce_value:Ke,opaque:Zr,stale:le,algorithm:Ge,qop_options:Bi,qop_value:Er,Proxy_Require:po,Record_Route:_o,rec_route:at,Reason:fo,reason_param:es,reason_cause:Vi,Require:mo,Route:go,route_param:Mr,Subscription_State:Ln,substate_value:ji,subexp_params:Ts,event_reason_value:pr,Subject:yo,Supported:vo,To,to_param:bs,Via:bo,via_param:Ur,via_params:ws,via_ttl:Gi,via_maddr:Wi,via_received:Ki,via_branch:qn,response_port:Yi,rport:Xi,sent_protocol:Ji,protocol_name:Qi,transport:Zi,sent_by:ea,via_host:ta,via_port:na,ttl:Ss,WWW_Authenticate:wo,Session_Expires:Cl,s_e_expires:Hn,s_e_params:Es,s_e_refresher:Cs,extension_header:Ua,header_value:zn,message_body:So,uuid_URI:Eo,uuid:ra,hex4:sn,hex8:sa,hex12:ia,Refer_To:Co,Replaces:Ao,call_id:aa,replaces_param:As,to_tag:Fn,from_tag:oa,early_flag:la};if(a!==void 0){if(c[a]===void 0)throw new Error("Invalid rule name: "+o(a)+".")}else a="CRLF";var e=0,_=0,g=[];function d(t){e<_||(e>_&&(_=e,g=[]),g.push(t))}function A(){var t;return r.substr(e,2)===`\r
|
|
73
73
|
`?(t=`\r
|
|
74
|
-
`,e+=2):(t=null,d('"\\r\\n"')),t}function S(){var t;return/^[0-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[0-9]")),t}function R(){var t;return/^[a-zA-Z]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-zA-Z]")),t}function N(){var t;return/^[0-9a-fA-F]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[0-9a-fA-F]")),t}function H(){var t;return t=K(),t===null&&(t=ae()),t}function W(){var t;return/^[\0-\xFF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\0-\\xFF]")),t}function G(){var t;return/^["]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d('["]')),t}function K(){var t;return r.charCodeAt(e)===32?(t=" ",e++):(t=null,d('" "')),t}function ae(){var t;return r.charCodeAt(e)===9?(t=" ",e++):(t=null,d('"\\t"')),t}function ee(){var t;return/^[a-zA-Z0-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-zA-Z0-9]")),t}function De(){var t;return r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","'))))))))))),t}function X(){var t;return t=ee(),t===null&&(t=re()),t}function re(){var t;return r.charCodeAt(e)===45?(t="-",e++):(t=null,d('"-"')),t===null&&(r.charCodeAt(e)===95?(t="_",e++):(t=null,d('"_"')),t===null&&(r.charCodeAt(e)===46?(t=".",e++):(t=null,d('"."')),t===null&&(r.charCodeAt(e)===33?(t="!",e++):(t=null,d('"!"')),t===null&&(r.charCodeAt(e)===126?(t="~",e++):(t=null,d('"~"')),t===null&&(r.charCodeAt(e)===42?(t="*",e++):(t=null,d('"*"')),t===null&&(r.charCodeAt(e)===39?(t="'",e++):(t=null,d(`"'"`)),t===null&&(r.charCodeAt(e)===40?(t="(",e++):(t=null,d('"("')),t===null&&(r.charCodeAt(e)===41?(t=")",e++):(t=null,d('")"')))))))))),t}function be(){var t,i,l,h,_;return h=e,_=e,r.charCodeAt(e)===37?(t="%",e++):(t=null,d('"%"')),t!==null?(i=N(),i!==null?(l=N(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){return I.join("")}(h,t)),t===null&&(e=h),t}function Ne(){var t,i,l,h,_,v;for(h=e,_=e,v=e,t=[],i=H();i!==null;)t.push(i),i=H();if(t!==null?(i=A(),i!==null?t=[t,i]:(t=null,e=v)):(t=null,e=v),t=t!==null?t:"",t!==null){if(l=H(),l!==null)for(i=[];l!==null;)i.push(l),l=H();else i=null;i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t!==null&&(t=function(I){return" "}()),t===null&&(e=h),t}function Q(){var t;return t=Ne(),t=t!==null?t:"",t}function ce(){var t,i,l,h,_;for(h=e,_=e,t=[],i=K(),i===null&&(i=ae());i!==null;)t.push(i),i=K(),i===null&&(i=ae());return t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return":"}()),t===null&&(e=h),t}function me(){var t,i,l,h,_,v,I;if(_=e,v=e,i=_e(),i!==null)for(t=[];i!==null;)t.push(i),i=_e();else t=null;if(t!==null){for(i=[],I=e,l=[],h=Ne();h!==null;)l.push(h),h=Ne();for(l!==null?(h=_e(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;){for(i.push(l),I=e,l=[],h=Ne();h!==null;)l.push(h),h=Ne();l!==null?(h=_e(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I)}i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){return r.substring(e,q)}(_)),t===null&&(e=_),t}function _e(){var t;return/^[!-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[!-~]")),t===null&&(t=ue()),t}function ue(){var t;return/^[\x80-\uFFFF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\x80-\\uFFFF]")),t}function ye(){var t;return/^[\x80-\xBF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\x80-\\xBF]")),t}function Re(){var t;return t=S(),t===null&&(/^[a-f]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-f]"))),t}function J(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"'))))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function Se(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"'))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function $e(){var t;return r.charCodeAt(e)===40?(t="(",e++):(t=null,d('"("')),t===null&&(r.charCodeAt(e)===41?(t=")",e++):(t=null,d('")"')),t===null&&(r.charCodeAt(e)===60?(t="<",e++):(t=null,d('"<"')),t===null&&(r.charCodeAt(e)===62?(t=">",e++):(t=null,d('">"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===92?(t="\\",e++):(t=null,d('"\\\\"')),t===null&&(t=G(),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===123?(t="{",e++):(t=null,d('"{"')),t===null&&(r.charCodeAt(e)===125?(t="}",e++):(t=null,d('"}"')),t===null&&(t=K(),t===null&&(t=ae())))))))))))))))))),t}function zt(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')),i===null&&(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i===null&&(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i===null&&(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i===null&&(r.charCodeAt(e)===62?(i=">",e++):(i=null,d('">"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===92?(i="\\",e++):(i=null,d('"\\\\"')),i===null&&(i=G(),i===null&&(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i===null&&(r.charCodeAt(e)===91?(i="[",e++):(i=null,d('"["')),i===null&&(r.charCodeAt(e)===93?(i="]",e++):(i=null,d('"]"')),i===null&&(r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i===null&&(r.charCodeAt(e)===123?(i="{",e++):(i=null,d('"{"')),i===null&&(r.charCodeAt(e)===125?(i="}",e++):(i=null,d('"}"'))))))))))))))))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')),i===null&&(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i===null&&(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i===null&&(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i===null&&(r.charCodeAt(e)===62?(i=">",e++):(i=null,d('">"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===92?(i="\\",e++):(i=null,d('"\\\\"')),i===null&&(i=G(),i===null&&(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i===null&&(r.charCodeAt(e)===91?(i="[",e++):(i=null,d('"["')),i===null&&(r.charCodeAt(e)===93?(i="]",e++):(i=null,d('"]"')),i===null&&(r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i===null&&(r.charCodeAt(e)===123?(i="{",e++):(i=null,d('"{"')),i===null&&(r.charCodeAt(e)===125?(i="}",e++):(i=null,d('"}"')))))))))))))))))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function Ae(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return"*"}()),t===null&&(e=h),t}function fe(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return"/"}()),t===null&&(e=h),t}function se(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return"="}()),t===null&&(e=h),t}function st(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return"("}()),t===null&&(e=h),t}function We(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return")"}()),t===null&&(e=h),t}function ht(){var t,i,l,h;return l=e,h=e,r.charCodeAt(e)===62?(t=">",e++):(t=null,d('">"')),t!==null?(i=Q(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_){return">"}()),t===null&&(e=l),t}function It(){var t,i,l,h;return l=e,h=e,t=Q(),t!==null?(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_){return"<"}()),t===null&&(e=l),t}function qe(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return","}()),t===null&&(e=h),t}function Ue(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return";"}()),t===null&&(e=h),t}function wt(){var t,i,l,h,_;return h=e,_=e,t=Q(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return":"}()),t===null&&(e=h),t}function Yt(){var t,i,l,h;return l=e,h=e,t=Q(),t!==null?(i=G(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_){return'"'}()),t===null&&(e=l),t}function Xe(){var t,i,l,h;return l=e,h=e,t=G(),t!==null?(i=Q(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_){return'"'}()),t===null&&(e=l),t}function Je(){var t,i,l,h;if(h=e,t=st(),t!==null){for(i=[],l=ut(),l===null&&(l=Pe(),l===null&&(l=Je()));l!==null;)i.push(l),l=ut(),l===null&&(l=Pe(),l===null&&(l=Je()));i!==null?(l=We(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)}else t=null,e=h;return t}function ut(){var t;return/^[!-']/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[!-']")),t===null&&(/^[*-[]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[*-[]")),t===null&&(/^[\]-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\]-~]")),t===null&&(t=ue(),t===null&&(t=Ne())))),t}function _t(){var t,i,l,h,_,v;if(_=e,v=e,t=Q(),t!==null)if(i=G(),i!==null){for(l=[],h=Le(),h===null&&(h=Pe());h!==null;)l.push(h),h=Le(),h===null&&(h=Pe());l!==null?(h=G(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I){return r.substring(e,I)}(_)),t===null&&(e=_),t}function mt(){var t,i,l,h,_,v;if(_=e,v=e,t=Q(),t!==null)if(i=G(),i!==null){for(l=[],h=Le(),h===null&&(h=Pe());h!==null;)l.push(h),h=Le(),h===null&&(h=Pe());l!==null?(h=G(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I){var q=r.substring(e,I).trim();return q.substring(1,q.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(_)),t===null&&(e=_),t}function Le(){var t;return t=Ne(),t===null&&(r.charCodeAt(e)===33?(t="!",e++):(t=null,d('"!"')),t===null&&(/^[#-[]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[#-[]")),t===null&&(/^[\]-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\]-~]")),t===null&&(t=ue())))),t}function Pe(){var t,i,l;return l=e,r.charCodeAt(e)===92?(t="\\",e++):(t=null,d('"\\\\"')),t!==null?(/^[\0-\t]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\0-\\t]")),i===null&&(/^[\x0B-\f]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\x0B-\\f]")),i===null&&(/^[\x0E-]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\x0E-]")))),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Ze(){var t,i,l,h,_,v;return _=e,v=e,t=qt(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Wn(),l=l!==null?l:"",l!==null?(h=jr(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t!==null&&(t=function(I){try{M.uri=new ua(M.scheme,M.user,M.host,M.port),delete M.scheme,delete M.user,delete M.host,delete M.host_type,delete M.port}catch{M=-1}}()),t===null&&(e=_),t}function Tt(){var t,i,l,h,_,v,I,q;return I=e,q=e,t=qt(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Wn(),l=l!==null?l:"",l!==null?(h=jr(),h!==null?(_=Vs(),_!==null?(v=Yr(),v=v!==null?v:"",v!==null?t=[t,i,l,h,_,v]:(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q),t!==null&&(t=function(j){try{M.uri=new ua(M.scheme,M.user,M.host,M.port,M.uri_params,M.uri_headers),delete M.scheme,delete M.user,delete M.host,delete M.host_type,delete M.port,delete M.uri_params,a==="SIP_URI"&&(M=M.uri)}catch{M=-1}}()),t===null&&(e=I),t}function qt(){var t;return t=rn(),t===null&&(t=Dt()),t}function rn(){var t,i;return i=e,r.substr(e,4).toLowerCase()==="sips"?(t=r.substr(e,4),e+=4):(t=null,d('"sips"')),t!==null&&(t=function(l,h){M.scheme=h.toLowerCase()}(i,t)),t===null&&(e=i),t}function Dt(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"sip"')),t!==null&&(t=function(l,h){M.scheme=h.toLowerCase()}(i,t)),t===null&&(e=i),t}function Wn(){var t,i,l,h,_,v;return h=e,_=e,t=Pn(),t!==null?(v=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Aa(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?(r.charCodeAt(e)===64?(l="@",e++):(l=null,d('"@"')),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){M.user=decodeURIComponent(r.substring(e-1,I))}(h)),t===null&&(e=h),t}function Pn(){var t,i;if(i=X(),i===null&&(i=be(),i===null&&(i=Bs())),i!==null)for(t=[];i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(i=Bs()));else t=null;return t}function Bs(){var t;return r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"'))))))))),t}function Aa(){var t,i,l;for(l=e,t=[],i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","'))))))));i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","'))))))));return t!==null&&(t=function(h){M.password=r.substring(e,h)}(l)),t===null&&(e=l),t}function jr(){var t,i,l,h,_;return h=e,t=ar(),t!==null?(_=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=gn(),l!==null?i=[i,l]:(i=null,e=_)):(i=null,e=_),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function ar(){var t,i;return i=e,t=_n(),t===null&&(t=or(),t===null&&(t=Wr())),t!==null&&(t=function(l){return M.host=r.substring(e,l).toLowerCase(),M.host}(i)),t===null&&(e=i),t}function _n(){var t,i,l,h,_,v;for(h=e,_=e,t=[],v=e,i=Gr(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v);i!==null;)t.push(i),v=e,i=Gr(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v);return t!==null?(i=yi(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){return M.host_type="domain",r.substring(e,I)}(h)),t===null&&(e=h),t}function Gr(){var t,i,l,h;if(h=e,t=ee(),t!==null){for(i=[],l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));l!==null;)i.push(l),l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function yi(){var t,i,l,h;if(h=e,t=R(),t!==null){for(i=[],l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));l!==null;)i.push(l),l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function Wr(){var t,i,l,h,_;return h=e,_=e,r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t!==null?(i=Kr(),i!==null?(r.charCodeAt(e)===93?(l="]",e++):(l=null,d('"]"')),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v){return M.host_type="IPv6",r.substring(e,v)}(h)),t===null&&(e=h),t}function Kr(){var t,i,l,h,_,v,I,q,j,Oe,it,an,Pr,ts,z,he;return ts=e,z=e,t=de(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?(r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=de(),j!==null?(r.charCodeAt(e)===58?(Oe=":",e++):(Oe=null,d('":"')),Oe!==null?(it=de(),it!==null?(r.charCodeAt(e)===58?(an=":",e++):(an=null,d('":"')),an!==null?(Pr=Pt(),Pr!==null?t=[t,i,l,h,_,v,I,q,j,Oe,it,an,Pr]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=de(),Oe!==null?(r.charCodeAt(e)===58?(it=":",e++):(it=null,d('":"')),it!==null?(an=Pt(),an!==null?t=[t,i,l,h,_,v,I,q,j,Oe,it,an]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=Pt(),Oe!==null?t=[t,i,l,h,_,v,I,q,j,Oe]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=Pt(),q!==null?t=[t,i,l,h,_,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=Pt(),v!==null?t=[t,i,l,h,_,v]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=Pt(),h!==null?t=[t,i,l,h]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=Pt(),i!==null?t=[t,i]:(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?t=[t,i]:(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(r.substr(e,2)==="::"?(i="::",e+=2):(i=null,d('"::"')),i!==null?(l=de(),l!==null?(r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=de(),j!==null?(r.charCodeAt(e)===58?(Oe=":",e++):(Oe=null,d('":"')),Oe!==null?(it=Pt(),it!==null?t=[t,i,l,h,_,v,I,q,j,Oe,it]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(r.substr(e,2)==="::"?(l="::",e+=2):(l=null,d('"::"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=Pt(),Oe!==null?t=[t,i,l,h,_,v,I,q,j,Oe]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(r.substr(e,2)==="::"?(h="::",e+=2):(h=null,d('"::"')),h!==null?(_=de(),_!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=Pt(),j!==null?t=[t,i,l,h,_,v,I,q,j]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?h=[h,_]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(r.substr(e,2)==="::"?(_="::",e+=2):(_=null,d('"::"')),_!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=Pt(),q!==null?t=[t,i,l,h,_,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?h=[h,_]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?_=[_,v]:(_=null,e=he)):(_=null,e=he),_=_!==null?_:"",_!==null?(r.substr(e,2)==="::"?(v="::",e+=2):(v=null,d('"::"')),v!==null?(I=Pt(),I!==null?t=[t,i,l,h,_,v,I]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?h=[h,_]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?_=[_,v]:(_=null,e=he)):(_=null,e=he),_=_!==null?_:"",_!==null?(he=e,r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?v=[v,I]:(v=null,e=he)):(v=null,e=he),v=v!==null?v:"",v!==null?(r.substr(e,2)==="::"?(I="::",e+=2):(I=null,d('"::"')),I!==null?(q=de(),q!==null?t=[t,i,l,h,_,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(_=de(),_!==null?h=[h,_]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(_=":",e++):(_=null,d('":"')),_!==null?(v=de(),v!==null?_=[_,v]:(_=null,e=he)):(_=null,e=he),_=_!==null?_:"",_!==null?(he=e,r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?v=[v,I]:(v=null,e=he)):(v=null,e=he),v=v!==null?v:"",v!==null?(he=e,r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?I=[I,q]:(I=null,e=he)):(I=null,e=he),I=I!==null?I:"",I!==null?(r.substr(e,2)==="::"?(q="::",e+=2):(q=null,d('"::"')),q!==null?t=[t,i,l,h,_,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z))))))))))))))),t!==null&&(t=function(Oo){return M.host_type="IPv6",r.substring(e,Oo)}(ts)),t===null&&(e=ts),t}function de(){var t,i,l,h,_;return _=e,t=N(),t!==null?(i=N(),i=i!==null?i:"",i!==null?(l=N(),l=l!==null?l:"",l!==null?(h=N(),h=h!==null?h:"",h!==null?t=[t,i,l,h]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t}function Pt(){var t,i,l,h;return h=e,t=de(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(t=or()),t}function or(){var t,i,l,h,_,v,I,q,j;return q=e,j=e,t=lr(),t!==null?(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i!==null?(l=lr(),l!==null?(r.charCodeAt(e)===46?(h=".",e++):(h=null,d('"."')),h!==null?(_=lr(),_!==null?(r.charCodeAt(e)===46?(v=".",e++):(v=null,d('"."')),v!==null?(I=lr(),I!==null?t=[t,i,l,h,_,v,I]:(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j),t!==null&&(t=function(Oe){return M.host_type="IPv4",r.substring(e,Oe)}(q)),t===null&&(e=q),t}function lr(){var t,i,l,h;return h=e,r.substr(e,2)==="25"?(t="25",e+=2):(t=null,d('"25"')),t!==null?(/^[0-5]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[0-5]")),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t===null&&(h=e,r.charCodeAt(e)===50?(t="2",e++):(t=null,d('"2"')),t!==null?(/^[0-4]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[0-4]")),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(h=e,r.charCodeAt(e)===49?(t="1",e++):(t=null,d('"1"')),t!==null?(i=S(),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(h=e,/^[1-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[1-9]")),t!==null?(i=S(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t===null&&(t=S())))),t}function gn(){var t,i,l,h,_,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(_=S(),_=_!==null?_:"",_!==null?t=[t,i,l,h,_]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){return j=parseInt(j.join("")),M.port=j,j}(v,t)),t===null&&(e=v),t}function Vs(){var t,i,l,h;for(t=[],h=e,r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=$r(),l!==null?i=[i,l]:(i=null,e=h)):(i=null,e=h);i!==null;)t.push(i),h=e,r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=$r(),l!==null?i=[i,l]:(i=null,e=h)):(i=null,e=h);return t}function $r(){var t;return t=vi(),t===null&&(t=Ti(),t===null&&(t=js(),t===null&&(t=bi(),t===null&&(t=Gs(),t===null&&(t=wi(),t===null&&(t=Ws())))))),t}function vi(){var t,i,l,h;return l=e,h=e,r.substr(e,10).toLowerCase()==="transport="?(t=r.substr(e,10),e+=10):(t=null,d('"transport="')),t!==null?(r.substr(e,3).toLowerCase()==="udp"?(i=r.substr(e,3),e+=3):(i=null,d('"udp"')),i===null&&(r.substr(e,3).toLowerCase()==="tcp"?(i=r.substr(e,3),e+=3):(i=null,d('"tcp"')),i===null&&(r.substr(e,4).toLowerCase()==="sctp"?(i=r.substr(e,4),e+=4):(i=null,d('"sctp"')),i===null&&(r.substr(e,3).toLowerCase()==="tls"?(i=r.substr(e,3),e+=3):(i=null,d('"tls"')),i===null&&(i=J())))),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.uri_params||(M.uri_params={}),M.uri_params.transport=v.toLowerCase()}(l,t[1])),t===null&&(e=l),t}function Ti(){var t,i,l,h;return l=e,h=e,r.substr(e,5).toLowerCase()==="user="?(t=r.substr(e,5),e+=5):(t=null,d('"user="')),t!==null?(r.substr(e,5).toLowerCase()==="phone"?(i=r.substr(e,5),e+=5):(i=null,d('"phone"')),i===null&&(r.substr(e,2).toLowerCase()==="ip"?(i=r.substr(e,2),e+=2):(i=null,d('"ip"')),i===null&&(i=J())),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.uri_params||(M.uri_params={}),M.uri_params.user=v.toLowerCase()}(l,t[1])),t===null&&(e=l),t}function js(){var t,i,l,h;return l=e,h=e,r.substr(e,7).toLowerCase()==="method="?(t=r.substr(e,7),e+=7):(t=null,d('"method="')),t!==null?(i=kr(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.uri_params||(M.uri_params={}),M.uri_params.method=v}(l,t[1])),t===null&&(e=l),t}function bi(){var t,i,l,h;return l=e,h=e,r.substr(e,4).toLowerCase()==="ttl="?(t=r.substr(e,4),e+=4):(t=null,d('"ttl="')),t!==null?(i=Ss(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.params||(M.params={}),M.params.ttl=v}(l,t[1])),t===null&&(e=l),t}function Gs(){var t,i,l,h;return l=e,h=e,r.substr(e,6).toLowerCase()==="maddr="?(t=r.substr(e,6),e+=6):(t=null,d('"maddr="')),t!==null?(i=ar(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(_,v){M.uri_params||(M.uri_params={}),M.uri_params.maddr=v}(l,t[1])),t===null&&(e=l),t}function wi(){var t,i,l,h,_,v;return h=e,_=e,r.substr(e,2).toLowerCase()==="lr"?(t=r.substr(e,2),e+=2):(t=null,d('"lr"')),t!==null?(v=e,r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=J(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){M.uri_params||(M.uri_params={}),M.uri_params.lr=void 0}()),t===null&&(e=h),t}function Ws(){var t,i,l,h,_,v;return h=e,_=e,t=Si(),t!==null?(v=e,r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Ks(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I,q,j){M.uri_params||(M.uri_params={}),typeof j>"u"?j=void 0:j=j[1],M.uri_params[q.toLowerCase()]=j}(h,t[0],t[1])),t===null&&(e=h),t}function Si(){var t,i,l;if(l=e,i=Qn(),i!==null)for(t=[];i!==null;)t.push(i),i=Qn();else t=null;return t!==null&&(t=function(h,_){return _.join("")}(l,t)),t===null&&(e=l),t}function Ks(){var t,i,l;if(l=e,i=Qn(),i!==null)for(t=[];i!==null;)t.push(i),i=Qn();else t=null;return t!==null&&(t=function(h,_){return _.join("")}(l,t)),t===null&&(e=l),t}function Qn(){var t;return t=ds(),t===null&&(t=X(),t===null&&(t=be())),t}function ds(){var t;return r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')))))))),t}function Yr(){var t,i,l,h,_,v,I;if(v=e,r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t!==null)if(i=mr(),i!==null){for(l=[],I=e,r.charCodeAt(e)===38?(h="&",e++):(h=null,d('"&"')),h!==null?(_=mr(),_!==null?h=[h,_]:(h=null,e=I)):(h=null,e=I);h!==null;)l.push(h),I=e,r.charCodeAt(e)===38?(h="&",e++):(h=null,d('"&"')),h!==null?(_=mr(),_!==null?h=[h,_]:(h=null,e=I)):(h=null,e=I);l!==null?t=[t,i,l]:(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t}function mr(){var t,i,l,h,_;return h=e,_=e,t=Ei(),t!==null?(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Ci(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I,q){I=I.join("").toLowerCase(),q=q.join(""),M.uri_headers||(M.uri_headers={}),M.uri_headers[I]?M.uri_headers[I].push(q):M.uri_headers[I]=[q]}(h,t[0],t[2])),t===null&&(e=h),t}function Ei(){var t,i;if(i=ur(),i===null&&(i=X(),i===null&&(i=be())),i!==null)for(t=[];i!==null;)t.push(i),i=ur(),i===null&&(i=X(),i===null&&(i=be()));else t=null;return t}function Ci(){var t,i;for(t=[],i=ur(),i===null&&(i=X(),i===null&&(i=be()));i!==null;)t.push(i),i=ur(),i===null&&(i=X(),i===null&&(i=be()));return t}function ur(){var t;return r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')))))))),t}function Ia(){var t;return t=Di(),t===null&&(t=$t()),t}function $t(){var t,i,l,h,_,v;return v=e,t=kr(),t!==null?(i=K(),i!==null?(l=gr(),l!==null?(h=K(),h!==null?(_=Or(),_!==null?t=[t,i,l,h,_]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function gr(){var t;return t=Tt(),t===null&&(t=yn()),t}function yn(){var t,i,l,h;return h=e,t=$i(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=hs(),l===null&&(l=Ai()),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function hs(){var t,i,l,h,_;return h=e,t=Et(),t===null&&(t=yr()),t!==null?(_=e,r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i!==null?(l=wr(),l!==null?i=[i,l]:(i=null,e=_)):(i=null,e=_),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function Et(){var t,i,l,h;return h=e,r.substr(e,2)==="//"?(t="//",e+=2):(t=null,d('"//"')),t!==null?(i=Ra(),i!==null?(l=yr(),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function yr(){var t,i,l;return l=e,r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t!==null?(i=Ri(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Ai(){var t,i,l,h;if(h=e,t=Ii(),t!==null){for(i=[],l=vr();l!==null;)i.push(l),l=vr();i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function vr(){var t;return t=De(),t===null&&(t=X(),t===null&&(t=be())),t}function Ii(){var t;return t=X(),t===null&&(t=be(),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')))))))))))),t}function Ri(){var t,i,l,h,_,v;if(_=e,t=xr(),t!==null){for(i=[],v=e,r.charCodeAt(e)===47?(l="/",e++):(l=null,d('"/"')),l!==null?(h=xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===47?(l="/",e++):(l=null,d('"/"')),l!==null?(h=xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function xr(){var t,i,l,h,_,v;for(_=e,t=[],i=cr();i!==null;)t.push(i),i=cr();if(t!==null){for(i=[],v=e,r.charCodeAt(e)===59?(l=";",e++):(l=null,d('";"')),l!==null?(h=Tr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===59?(l=";",e++):(l=null,d('";"')),l!==null?(h=Tr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Tr(){var t,i;for(t=[],i=cr();i!==null;)t.push(i),i=cr();return t}function cr(){var t;return t=X(),t===null&&(t=be(),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')))))))))),t}function $i(){var t,i,l,h,_;if(h=e,_=e,t=R(),t!==null){for(i=[],l=R(),l===null&&(l=S(),l===null&&(r.charCodeAt(e)===43?(l="+",e++):(l=null,d('"+"')),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."'))))));l!==null;)i.push(l),l=R(),l===null&&(l=S(),l===null&&(r.charCodeAt(e)===43?(l="+",e++):(l=null,d('"+"')),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."'))))));i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t!==null&&(t=function(v){M.scheme=r.substring(e,v)}(h)),t===null&&(e=h),t}function Ra(){var t;return t=br(),t===null&&(t=Zn()),t}function br(){var t,i,l,h;return l=e,h=e,t=Wn(),t!==null?(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t=t!==null?t:"",t!==null?(i=jr(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t=t!==null?t:"",t}function Zn(){var t,i;if(i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i===null&&(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"'))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i===null&&(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')))))))))));else t=null;return t}function wr(){var t,i;for(t=[],i=vr();i!==null;)t.push(i),i=vr();return t}function Or(){var t,i,l,h,_,v,I,q;if(I=e,q=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t!==null)if(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i!==null){if(h=S(),h!==null)for(l=[];h!==null;)l.push(h),h=S();else l=null;if(l!==null)if(r.charCodeAt(e)===46?(h=".",e++):(h=null,d('"."')),h!==null){if(v=S(),v!==null)for(_=[];v!==null;)_.push(v),v=S();else _=null;_!==null?t=[t,i,l,h,_]:(t=null,e=q)}else t=null,e=q;else t=null,e=q}else t=null,e=q;else t=null,e=q;return t!==null&&(t=function(j){M.sip_version=r.substring(e,j)}(I)),t===null&&(e=I),t}function ps(){var t;return r.substr(e,6)==="INVITE"?(t="INVITE",e+=6):(t=null,d('"INVITE"')),t}function Ys(){var t;return r.substr(e,3)==="ACK"?(t="ACK",e+=3):(t=null,d('"ACK"')),t}function Xs(){var t;return r.substr(e,7)==="OPTIONS"?(t="OPTIONS",e+=7):(t=null,d('"OPTIONS"')),t}function Js(){var t;return r.substr(e,3)==="BYE"?(t="BYE",e+=3):(t=null,d('"BYE"')),t}function rt(){var t;return r.substr(e,6)==="CANCEL"?(t="CANCEL",e+=6):(t=null,d('"CANCEL"')),t}function Qs(){var t;return r.substr(e,8)==="REGISTER"?(t="REGISTER",e+=8):(t=null,d('"REGISTER"')),t}function xi(){var t;return r.substr(e,9)==="SUBSCRIBE"?(t="SUBSCRIBE",e+=9):(t=null,d('"SUBSCRIBE"')),t}function Oi(){var t;return r.substr(e,6)==="NOTIFY"?(t="NOTIFY",e+=6):(t=null,d('"NOTIFY"')),t}function ki(){var t;return r.substr(e,5)==="REFER"?(t="REFER",e+=5):(t=null,d('"REFER"')),t}function kr(){var t,i;return i=e,t=ps(),t===null&&(t=Ys(),t===null&&(t=Xs(),t===null&&(t=Js(),t===null&&(t=rt(),t===null&&(t=Qs(),t===null&&(t=xi(),t===null&&(t=Oi(),t===null&&(t=ki(),t===null&&(t=J()))))))))),t!==null&&(t=function(l){return M.method=r.substring(e,l),M.method}(i)),t===null&&(e=i),t}function Di(){var t,i,l,h,_,v;return v=e,t=Or(),t!==null?(i=K(),i!==null?(l=Zs(),l!==null?(h=K(),h!==null?(_=vt(),_!==null?t=[t,i,l,h,_]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function Zs(){var t,i;return i=e,t=Ni(),t!==null&&(t=function(l,h){M.status_code=parseInt(h.join(""))}(i,t)),t===null&&(e=i),t}function Ni(){var t,i,l,h;return h=e,t=S(),t!==null?(i=S(),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function vt(){var t,i,l;for(l=e,t=[],i=De(),i===null&&(i=X(),i===null&&(i=be(),i===null&&(i=ue(),i===null&&(i=ye(),i===null&&(i=K(),i===null&&(i=ae()))))));i!==null;)t.push(i),i=De(),i===null&&(i=X(),i===null&&(i=be(),i===null&&(i=ue(),i===null&&(i=ye(),i===null&&(i=K(),i===null&&(i=ae()))))));return t!==null&&(t=function(h){M.reason_phrase=r.substring(e,h)}(l)),t===null&&(e=l),t}function Sr(){var t,i,l,h,_,v;if(_=e,t=er(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=er(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=er(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function lo(){var t,i,l,h,_,v;return h=e,_=e,t=zt(),t!==null?(v=e,r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?(l=zt(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){M=r.substring(e,I)}(h)),t===null&&(e=h),t}function _s(){var t,i,l,h,_,v,I;if(_=e,t=Ae(),t===null)if(v=e,t=ne(),t!==null){for(i=[],I=e,l=qe(),l!==null?(h=ne(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=qe(),l!==null?(h=ne(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j,Oe;for(Oe=M.multi_header.length,j=0;j<Oe;j++)if(M.multi_header[j].parsed===null){M=null;break}M!==null?M=M.multi_header:M=-1}()),t===null&&(e=_),t}function ne(){var t,i,l,h,_,v,I;if(_=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=fs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=fs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j;M.multi_header||(M.multi_header=[]);try{j=new Yn(M.uri,M.display_name,M.params),delete M.uri,delete M.display_name,delete M.params}catch{j=null}M.multi_header.push({possition:e,offset:q,parsed:j})}(_)),t===null&&(e=_),t}function fn(){var t,i,l,h,_;return _=e,t=Dr(),t=t!==null?t:"",t!==null?(i=It(),i!==null?(l=Tt(),l!==null?(h=ht(),h!==null?t=[t,i,l,h]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t}function Dr(){var t,i,l,h,_,v,I;if(_=e,v=e,t=J(),t!==null){for(i=[],I=e,l=Ne(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ne(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t===null&&(t=mt()),t!==null&&(t=function(q,j){typeof j=="string"?M.display_name=j:M.display_name=j[1].reduce(function(Oe,it){return Oe+it[0]+it[1]},j[0])}(_,t)),t===null&&(e=_),t}function fs(){var t;return t=Mi(),t===null&&(t=ct(),t===null&&(t=gt())),t}function Mi(){var t,i,l,h,_;return h=e,_=e,r.substr(e,1).toLowerCase()==="q"?(t=r.substr(e,1),e++):(t=null,d('"q"')),t!==null?(i=se(),i!==null?(l=Ui(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.params||(M.params={}),M.params.q=I}(h,t[2])),t===null&&(e=h),t}function ct(){var t,i,l,h,_;return h=e,_=e,r.substr(e,7).toLowerCase()==="expires"?(t=r.substr(e,7),e+=7):(t=null,d('"expires"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.params||(M.params={}),M.params.expires=I}(h,t[2])),t===null&&(e=h),t}function vn(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,_){return parseInt(_.join(""))}(l,t)),t===null&&(e=l),t}function Ui(){var t,i,l,h,_,v,I,q;return v=e,I=e,r.charCodeAt(e)===48?(t="0",e++):(t=null,d('"0"')),t!==null?(q=e,r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(_=S(),_=_!==null?_:"",_!==null?i=[i,l,h,_]:(i=null,e=q)):(i=null,e=q)):(i=null,e=q)):(i=null,e=q),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(j){return parseFloat(r.substring(e,j))}(v)),t===null&&(e=v),t}function gt(){var t,i,l,h,_,v;return h=e,_=e,t=J(),t!==null?(v=e,i=se(),i!==null?(l=ei(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I,q,j){M.params||(M.params={}),typeof j>"u"?j=void 0:j=j[1],M.params[q.toLowerCase()]=j}(h,t[0],t[1])),t===null&&(e=h),t}function ei(){var t;return t=J(),t===null&&(t=ar(),t===null&&(t=_t())),t}function $a(){var t,i,l,h,_,v;if(_=e,t=Pi(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Pi(){var t;return r.substr(e,6).toLowerCase()==="render"?(t=r.substr(e,6),e+=6):(t=null,d('"render"')),t===null&&(r.substr(e,7).toLowerCase()==="session"?(t=r.substr(e,7),e+=7):(t=null,d('"session"')),t===null&&(r.substr(e,4).toLowerCase()==="icon"?(t=r.substr(e,4),e+=4):(t=null,d('"icon"')),t===null&&(r.substr(e,5).toLowerCase()==="alert"?(t=r.substr(e,5),e+=5):(t=null,d('"alert"')),t===null&&(t=J())))),t}function Xr(){var t;return t=Li(),t===null&&(t=gt()),t}function Li(){var t,i,l,h;return h=e,r.substr(e,8).toLowerCase()==="handling"?(t=r.substr(e,8),e+=8):(t=null,d('"handling"')),t!==null?(i=se(),i!==null?(r.substr(e,8).toLowerCase()==="optional"?(l=r.substr(e,8),e+=8):(l=null,d('"optional"')),l===null&&(r.substr(e,8).toLowerCase()==="required"?(l=r.substr(e,8),e+=8):(l=null,d('"required"')),l===null&&(l=J())),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function xa(){var t,i,l,h,_,v;if(_=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Oa(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,_){M=parseInt(_.join(""))}(l,t)),t===null&&(e=l),t}function ka(){var t,i;return i=e,t=qi(),t!==null&&(t=function(l){M=r.substring(e,l)}(i)),t===null&&(e=i),t}function qi(){var t,i,l,h,_,v,I,q;if(I=e,t=Hi(),t!==null)if(i=fe(),i!==null)if(l=Na(),l!==null){for(h=[],q=e,_=Ue(),_!==null?(v=Qr(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);_!==null;)h.push(_),q=e,_=Ue(),_!==null?(v=Qr(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function Hi(){var t;return t=Da(),t===null&&(t=Jr()),t}function Da(){var t;return r.substr(e,4).toLowerCase()==="text"?(t=r.substr(e,4),e+=4):(t=null,d('"text"')),t===null&&(r.substr(e,5).toLowerCase()==="image"?(t=r.substr(e,5),e+=5):(t=null,d('"image"')),t===null&&(r.substr(e,5).toLowerCase()==="audio"?(t=r.substr(e,5),e+=5):(t=null,d('"audio"')),t===null&&(r.substr(e,5).toLowerCase()==="video"?(t=r.substr(e,5),e+=5):(t=null,d('"video"')),t===null&&(r.substr(e,11).toLowerCase()==="application"?(t=r.substr(e,11),e+=11):(t=null,d('"application"')),t===null&&(t=Nr()))))),t}function Jr(){var t;return r.substr(e,7).toLowerCase()==="message"?(t=r.substr(e,7),e+=7):(t=null,d('"message"')),t===null&&(r.substr(e,9).toLowerCase()==="multipart"?(t=r.substr(e,9),e+=9):(t=null,d('"multipart"')),t===null&&(t=Nr())),t}function Nr(){var t;return t=J(),t===null&&(t=zi()),t}function zi(){var t,i,l;return l=e,r.substr(e,2).toLowerCase()==="x-"?(t=r.substr(e,2),e+=2):(t=null,d('"x-"')),t!==null?(i=J(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Na(){var t;return t=Nr(),t===null&&(t=J()),t}function Qr(){var t,i,l,h;return h=e,t=J(),t!==null?(i=se(),i!==null?(l=ti(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function ti(){var t;return t=J(),t===null&&(t=_t()),t}function Fi(){var t,i,l,h;return h=e,t=ms(),t!==null?(i=Ne(),i!==null?(l=kr(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function ms(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,_){M.value=parseInt(_.join(""))}(l,t)),t===null&&(e=l),t}function uo(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M=h}(i,t)),t===null&&(e=i),t}function co(){var t,i,l,h,_,v,I;if(_=e,v=e,t=er(),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q,j){M.event=j.join("").toLowerCase()}(_,t[0])),t===null&&(e=_),t}function er(){var t,i,l,h,_,v;if(_=e,t=Se(),t!==null){for(i=[],v=e,r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?(h=Se(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?(h=Se(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Ma(){var t,i,l,h,_,v,I;if(_=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j=M.tag;try{M=new Yn(M.uri,M.display_name,M.params),j&&M.setParam("tag",j)}catch{M=-1}}()),t===null&&(e=_),t}function gs(){var t;return t=ys(),t===null&&(t=gt()),t}function ys(){var t,i,l,h,_;return h=e,_=e,r.substr(e,3).toLowerCase()==="tag"?(t=r.substr(e,3),e+=3):(t=null,d('"tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.tag=I}(h,t[2])),t===null&&(e=h),t}function El(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,_){M=parseInt(_.join(""))}(l,t)),t===null&&(e=l),t}function ho(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M=h}(i,t)),t===null&&(e=i),t}function Ct(){var t,i,l,h,_,v,I,q,j,Oe;for(q=e,j=e,t=[],i=Dr();i!==null;)t.push(i),i=Dr();if(t!==null)if(i=It(),i!==null)if(l=Tt(),l!==null)if(h=ht(),h!==null){for(_=[],Oe=e,v=Ue(),v!==null?(I=gt(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);v!==null;)_.push(v),Oe=e,v=Ue(),v!==null?(I=gt(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);_!==null?t=[t,i,l,h,_]:(t=null,e=j)}else t=null,e=j;else t=null,e=j;else t=null,e=j;else t=null,e=j;return t!==null&&(t=function(it){try{M=new Yn(M.uri,M.display_name,M.params)}catch{M=-1}}()),t===null&&(e=q),t}function Ft(){var t;return t=dr(),t}function dr(){var t,i,l,h,_,v,I,q;if(I=e,r.substr(e,6).toLowerCase()==="digest"?(t=r.substr(e,6),e+=6):(t=null,d('"Digest"')),t!==null)if(i=Ne(),i!==null)if(l=Gt(),l!==null){for(h=[],q=e,_=qe(),_!==null?(v=Gt(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);_!==null;)h.push(_),q=e,_=qe(),_!==null?(v=Gt(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t===null&&(t=vs()),t}function vs(){var t,i,l,h,_,v,I,q;if(I=e,t=J(),t!==null)if(i=Ne(),i!==null)if(l=Nt(),l!==null){for(h=[],q=e,_=qe(),_!==null?(v=Nt(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);_!==null;)h.push(_),q=e,_=qe(),_!==null?(v=Nt(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function Nt(){var t,i,l,h;return h=e,t=J(),t!==null?(i=se(),i!==null?(l=J(),l===null&&(l=_t()),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Gt(){var t;return t=Qe(),t===null&&(t=ni(),t===null&&(t=hr(),t===null&&(t=Zr(),t===null&&(t=le(),t===null&&(t=Ge(),t===null&&(t=Bi(),t===null&&(t=Nt()))))))),t}function Qe(){var t,i,l,h;return h=e,r.substr(e,5).toLowerCase()==="realm"?(t=r.substr(e,5),e+=5):(t=null,d('"realm"')),t!==null?(i=se(),i!==null?(l=Ut(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ut(){var t,i;return i=e,t=mt(),t!==null&&(t=function(l,h){M.realm=h}(i,t)),t===null&&(e=i),t}function ni(){var t,i,l,h,_,v,I,q,j;if(q=e,r.substr(e,6).toLowerCase()==="domain"?(t=r.substr(e,6),e+=6):(t=null,d('"domain"')),t!==null)if(i=se(),i!==null)if(l=Yt(),l!==null)if(h=Kn(),h!==null){if(_=[],j=e,I=K(),I!==null)for(v=[];I!==null;)v.push(I),I=K();else v=null;for(v!==null?(I=Kn(),I!==null?v=[v,I]:(v=null,e=j)):(v=null,e=j);v!==null;){if(_.push(v),j=e,I=K(),I!==null)for(v=[];I!==null;)v.push(I),I=K();else v=null;v!==null?(I=Kn(),I!==null?v=[v,I]:(v=null,e=j)):(v=null,e=j)}_!==null?(v=Xe(),v!==null?t=[t,i,l,h,_,v]:(t=null,e=q)):(t=null,e=q)}else t=null,e=q;else t=null,e=q;else t=null,e=q;else t=null,e=q;return t}function Kn(){var t;return t=yn(),t===null&&(t=yr()),t}function hr(){var t,i,l,h;return h=e,r.substr(e,5).toLowerCase()==="nonce"?(t=r.substr(e,5),e+=5):(t=null,d('"nonce"')),t!==null?(i=se(),i!==null?(l=Ke(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ke(){var t,i;return i=e,t=mt(),t!==null&&(t=function(l,h){M.nonce=h}(i,t)),t===null&&(e=i),t}function Zr(){var t,i,l,h,_;return h=e,_=e,r.substr(e,6).toLowerCase()==="opaque"?(t=r.substr(e,6),e+=6):(t=null,d('"opaque"')),t!==null?(i=se(),i!==null?(l=mt(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.opaque=I}(h,t[2])),t===null&&(e=h),t}function le(){var t,i,l,h,_;return h=e,r.substr(e,5).toLowerCase()==="stale"?(t=r.substr(e,5),e+=5):(t=null,d('"stale"')),t!==null?(i=se(),i!==null?(_=e,r.substr(e,4).toLowerCase()==="true"?(l=r.substr(e,4),e+=4):(l=null,d('"true"')),l!==null&&(l=function(v){M.stale=!0}()),l===null&&(e=_),l===null&&(_=e,r.substr(e,5).toLowerCase()==="false"?(l=r.substr(e,5),e+=5):(l=null,d('"false"')),l!==null&&(l=function(v){M.stale=!1}()),l===null&&(e=_)),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ge(){var t,i,l,h,_;return h=e,_=e,r.substr(e,9).toLowerCase()==="algorithm"?(t=r.substr(e,9),e+=9):(t=null,d('"algorithm"')),t!==null?(i=se(),i!==null?(r.substr(e,3).toLowerCase()==="md5"?(l=r.substr(e,3),e+=3):(l=null,d('"MD5"')),l===null&&(r.substr(e,8).toLowerCase()==="md5-sess"?(l=r.substr(e,8),e+=8):(l=null,d('"MD5-sess"')),l===null&&(l=J())),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.algorithm=I.toUpperCase()}(h,t[2])),t===null&&(e=h),t}function Bi(){var t,i,l,h,_,v,I,q,j,Oe;if(q=e,r.substr(e,3).toLowerCase()==="qop"?(t=r.substr(e,3),e+=3):(t=null,d('"qop"')),t!==null)if(i=se(),i!==null)if(l=Yt(),l!==null){if(j=e,h=Er(),h!==null){for(_=[],Oe=e,r.charCodeAt(e)===44?(v=",",e++):(v=null,d('","')),v!==null?(I=Er(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);v!==null;)_.push(v),Oe=e,r.charCodeAt(e)===44?(v=",",e++):(v=null,d('","')),v!==null?(I=Er(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);_!==null?h=[h,_]:(h=null,e=j)}else h=null,e=j;h!==null?(_=Xe(),_!==null?t=[t,i,l,h,_]:(t=null,e=q)):(t=null,e=q)}else t=null,e=q;else t=null,e=q;else t=null,e=q;return t}function Er(){var t,i;return i=e,r.substr(e,8).toLowerCase()==="auth-int"?(t=r.substr(e,8),e+=8):(t=null,d('"auth-int"')),t===null&&(r.substr(e,4).toLowerCase()==="auth"?(t=r.substr(e,4),e+=4):(t=null,d('"auth"')),t===null&&(t=J())),t!==null&&(t=function(l,h){M.qop||(M.qop=[]),M.qop.push(h.toLowerCase())}(i,t)),t===null&&(e=i),t}function po(){var t,i,l,h,_,v;if(_=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function _o(){var t,i,l,h,_,v,I;if(_=e,v=e,t=at(),t!==null){for(i=[],I=e,l=qe(),l!==null?(h=at(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=qe(),l!==null?(h=at(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j,Oe;for(Oe=M.multi_header.length,j=0;j<Oe;j++)if(M.multi_header[j].parsed===null){M=null;break}M!==null?M=M.multi_header:M=-1}()),t===null&&(e=_),t}function at(){var t,i,l,h,_,v,I;if(_=e,v=e,t=fn(),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j;M.multi_header||(M.multi_header=[]);try{j=new Yn(M.uri,M.display_name,M.params),delete M.uri,delete M.display_name,delete M.params}catch{j=null}M.multi_header.push({possition:e,offset:q,parsed:j})}(_)),t===null&&(e=_),t}function fo(){var t,i,l,h,_,v,I;if(_=e,v=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t===null&&(t=J()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=es(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=es(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q,j){if(M.protocol=j.toLowerCase(),M.params||(M.params={}),M.params.text&&M.params.text[0]==='"'){var Oe=M.params.text;M.text=Oe.substring(1,Oe.length-1),delete M.params.text}}(_,t[0])),t===null&&(e=_),t}function es(){var t;return t=Vi(),t===null&&(t=gt()),t}function Vi(){var t,i,l,h,_,v;if(_=e,v=e,r.substr(e,5).toLowerCase()==="cause"?(t=r.substr(e,5),e+=5):(t=null,d('"cause"')),t!==null)if(i=se(),i!==null){if(h=S(),h!==null)for(l=[];h!==null;)l.push(h),h=S();else l=null;l!==null?t=[t,i,l]:(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I,q){M.cause=parseInt(q.join(""))}(_,t[2])),t===null&&(e=_),t}function mo(){var t,i,l,h,_,v;if(_=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function go(){var t,i,l,h,_,v;if(_=e,t=Mr(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=Mr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=Mr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Mr(){var t,i,l,h,_,v;if(_=e,t=fn(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Ln(){var t,i,l,h,_,v;if(_=e,t=ji(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Ts(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Ts(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function ji(){var t,i;return i=e,r.substr(e,6).toLowerCase()==="active"?(t=r.substr(e,6),e+=6):(t=null,d('"active"')),t===null&&(r.substr(e,7).toLowerCase()==="pending"?(t=r.substr(e,7),e+=7):(t=null,d('"pending"')),t===null&&(r.substr(e,10).toLowerCase()==="terminated"?(t=r.substr(e,10),e+=10):(t=null,d('"terminated"')),t===null&&(t=J()))),t!==null&&(t=function(l){M.state=r.substring(e,l)}(i)),t===null&&(e=i),t}function Ts(){var t,i,l,h,_;return h=e,_=e,r.substr(e,6).toLowerCase()==="reason"?(t=r.substr(e,6),e+=6):(t=null,d('"reason"')),t!==null?(i=se(),i!==null?(l=pr(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){typeof I<"u"&&(M.reason=I)}(h,t[2])),t===null&&(e=h),t===null&&(h=e,_=e,r.substr(e,7).toLowerCase()==="expires"?(t=r.substr(e,7),e+=7):(t=null,d('"expires"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){typeof I<"u"&&(M.expires=I)}(h,t[2])),t===null&&(e=h),t===null&&(h=e,_=e,r.substr(e,11).toLowerCase()==="retry_after"?(t=r.substr(e,11),e+=11):(t=null,d('"retry_after"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){typeof I<"u"&&(M.retry_after=I)}(h,t[2])),t===null&&(e=h),t===null&&(t=gt()))),t}function pr(){var t;return r.substr(e,11).toLowerCase()==="deactivated"?(t=r.substr(e,11),e+=11):(t=null,d('"deactivated"')),t===null&&(r.substr(e,9).toLowerCase()==="probation"?(t=r.substr(e,9),e+=9):(t=null,d('"probation"')),t===null&&(r.substr(e,8).toLowerCase()==="rejected"?(t=r.substr(e,8),e+=8):(t=null,d('"rejected"')),t===null&&(r.substr(e,7).toLowerCase()==="timeout"?(t=r.substr(e,7),e+=7):(t=null,d('"timeout"')),t===null&&(r.substr(e,6).toLowerCase()==="giveup"?(t=r.substr(e,6),e+=6):(t=null,d('"giveup"')),t===null&&(r.substr(e,10).toLowerCase()==="noresource"?(t=r.substr(e,10),e+=10):(t=null,d('"noresource"')),t===null&&(r.substr(e,9).toLowerCase()==="invariant"?(t=r.substr(e,9),e+=9):(t=null,d('"invariant"')),t===null&&(t=J()))))))),t}function yo(){var t;return t=me(),t=t!==null?t:"",t}function vo(){var t,i,l,h,_,v;if(_=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t=t!==null?t:"",t}function To(){var t,i,l,h,_,v,I;if(_=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=bs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=bs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j=M.tag;try{M=new Yn(M.uri,M.display_name,M.params),j&&M.setParam("tag",j)}catch{M=-1}}()),t===null&&(e=_),t}function bs(){var t;return t=ys(),t===null&&(t=gt()),t}function bo(){var t,i,l,h,_,v;if(_=e,t=Ur(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=Ur(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=Ur(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Ur(){var t,i,l,h,_,v,I,q;if(I=e,t=Ji(),t!==null)if(i=Ne(),i!==null)if(l=ea(),l!==null){for(h=[],q=e,_=Ue(),_!==null?(v=ws(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);_!==null;)h.push(_),q=e,_=Ue(),_!==null?(v=ws(),v!==null?_=[_,v]:(_=null,e=q)):(_=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function ws(){var t;return t=Gi(),t===null&&(t=Wi(),t===null&&(t=Ki(),t===null&&(t=qn(),t===null&&(t=Yi(),t===null&&(t=gt()))))),t}function Gi(){var t,i,l,h,_;return h=e,_=e,r.substr(e,3).toLowerCase()==="ttl"?(t=r.substr(e,3),e+=3):(t=null,d('"ttl"')),t!==null?(i=se(),i!==null?(l=Ss(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.ttl=I}(h,t[2])),t===null&&(e=h),t}function Wi(){var t,i,l,h,_;return h=e,_=e,r.substr(e,5).toLowerCase()==="maddr"?(t=r.substr(e,5),e+=5):(t=null,d('"maddr"')),t!==null?(i=se(),i!==null?(l=ar(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.maddr=I}(h,t[2])),t===null&&(e=h),t}function Ki(){var t,i,l,h,_;return h=e,_=e,r.substr(e,8).toLowerCase()==="received"?(t=r.substr(e,8),e+=8):(t=null,d('"received"')),t!==null?(i=se(),i!==null?(l=or(),l===null&&(l=Kr()),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.received=I}(h,t[2])),t===null&&(e=h),t}function qn(){var t,i,l,h,_;return h=e,_=e,r.substr(e,6).toLowerCase()==="branch"?(t=r.substr(e,6),e+=6):(t=null,d('"branch"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.branch=I}(h,t[2])),t===null&&(e=h),t}function Yi(){var t,i,l,h,_;return h=e,r.substr(e,5).toLowerCase()==="rport"?(t=r.substr(e,5),e+=5):(t=null,d('"rport"')),t!==null?(_=e,i=se(),i!==null?(l=Xi(),l!==null?i=[i,l]:(i=null,e=_)):(i=null,e=_),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function Xi(){var t,i,l,h,_,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(_=S(),_=_!==null?_:"",_!==null?t=[t,i,l,h,_]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){M.rport=parseInt(j.join(""))}(v,t)),t===null&&(e=v),t}function Ji(){var t,i,l,h,_,v;return v=e,t=Qi(),t!==null?(i=fe(),i!==null?(l=J(),l!==null?(h=fe(),h!==null?(_=Zi(),_!==null?t=[t,i,l,h,_]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function Qi(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t===null&&(t=J()),t!==null&&(t=function(l,h){M.protocol=h}(i,t)),t===null&&(e=i),t}function Zi(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="udp"?(t=r.substr(e,3),e+=3):(t=null,d('"UDP"')),t===null&&(r.substr(e,3).toLowerCase()==="tcp"?(t=r.substr(e,3),e+=3):(t=null,d('"TCP"')),t===null&&(r.substr(e,3).toLowerCase()==="tls"?(t=r.substr(e,3),e+=3):(t=null,d('"TLS"')),t===null&&(r.substr(e,4).toLowerCase()==="sctp"?(t=r.substr(e,4),e+=4):(t=null,d('"SCTP"')),t===null&&(t=J())))),t!==null&&(t=function(l,h){M.transport=h}(i,t)),t===null&&(e=i),t}function ea(){var t,i,l,h,_;return h=e,t=ta(),t!==null?(_=e,i=wt(),i!==null?(l=na(),l!==null?i=[i,l]:(i=null,e=_)):(i=null,e=_),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function ta(){var t,i;return i=e,t=or(),t===null&&(t=Wr(),t===null&&(t=_n())),t!==null&&(t=function(l){M.host=r.substring(e,l)}(i)),t===null&&(e=i),t}function na(){var t,i,l,h,_,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(_=S(),_=_!==null?_:"",_!==null?t=[t,i,l,h,_]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){M.port=parseInt(j.join(""))}(v,t)),t===null&&(e=v),t}function Ss(){var t,i,l,h,_;return h=e,_=e,t=S(),t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){return parseInt(I.join(""))}(h,t)),t===null&&(e=h),t}function wo(){var t;return t=dr(),t}function Cl(){var t,i,l,h,_,v;if(_=e,t=Hn(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Es(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Es(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function Hn(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M.expires=h}(i,t)),t===null&&(e=i),t}function Es(){var t;return t=Cs(),t===null&&(t=gt()),t}function Cs(){var t,i,l,h,_;return h=e,_=e,r.substr(e,9).toLowerCase()==="refresher"?(t=r.substr(e,9),e+=9):(t=null,d('"refresher"')),t!==null?(i=se(),i!==null?(r.substr(e,3).toLowerCase()==="uac"?(l=r.substr(e,3),e+=3):(l=null,d('"uac"')),l===null&&(r.substr(e,3).toLowerCase()==="uas"?(l=r.substr(e,3),e+=3):(l=null,d('"uas"'))),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.refresher=I.toLowerCase()}(h,t[2])),t===null&&(e=h),t}function Ua(){var t,i,l,h;return h=e,t=J(),t!==null?(i=ce(),i!==null?(l=zn(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function zn(){var t,i;for(t=[],i=_e(),i===null&&(i=ye(),i===null&&(i=Ne()));i!==null;)t.push(i),i=_e(),i===null&&(i=ye(),i===null&&(i=Ne()));return t}function So(){var t,i;for(t=[],i=W();i!==null;)t.push(i),i=W();return t}function Eo(){var t,i,l;return l=e,r.substr(e,5)==="uuid:"?(t="uuid:",e+=5):(t=null,d('"uuid:"')),t!==null?(i=ra(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function ra(){var t,i,l,h,_,v,I,q,j,Oe,it;return Oe=e,it=e,t=sa(),t!==null?(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i!==null?(l=sn(),l!==null?(r.charCodeAt(e)===45?(h="-",e++):(h=null,d('"-"')),h!==null?(_=sn(),_!==null?(r.charCodeAt(e)===45?(v="-",e++):(v=null,d('"-"')),v!==null?(I=sn(),I!==null?(r.charCodeAt(e)===45?(q="-",e++):(q=null,d('"-"')),q!==null?(j=ia(),j!==null?t=[t,i,l,h,_,v,I,q,j]:(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it),t!==null&&(t=function(an,Pr){M=r.substring(e+5,an)}(Oe,t[0])),t===null&&(e=Oe),t}function sn(){var t,i,l,h,_;return _=e,t=N(),t!==null?(i=N(),i!==null?(l=N(),l!==null?(h=N(),h!==null?t=[t,i,l,h]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t}function sa(){var t,i,l;return l=e,t=sn(),t!==null?(i=sn(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function ia(){var t,i,l,h;return h=e,t=sn(),t!==null?(i=sn(),i!==null?(l=sn(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Co(){var t,i,l,h,_,v,I;if(_=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){try{M=new Yn(M.uri,M.display_name,M.params)}catch{M=-1}}()),t===null&&(e=_),t}function Ao(){var t,i,l,h,_,v;if(_=e,t=aa(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=As(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=As(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=_)}else t=null,e=_;return t}function aa(){var t,i,l,h,_,v;return h=e,_=e,t=zt(),t!==null?(v=e,r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?(l=zt(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(I){M.call_id=r.substring(e,I)}(h)),t===null&&(e=h),t}function As(){var t;return t=Fn(),t===null&&(t=oa(),t===null&&(t=la(),t===null&&(t=gt()))),t}function Fn(){var t,i,l,h,_;return h=e,_=e,r.substr(e,6)==="to-tag"?(t="to-tag",e+=6):(t=null,d('"to-tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.to_tag=I}(h,t[2])),t===null&&(e=h),t}function oa(){var t,i,l,h,_;return h=e,_=e,r.substr(e,8)==="from-tag"?(t="from-tag",e+=8):(t=null,d('"from-tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=_)):(t=null,e=_)):(t=null,e=_),t!==null&&(t=function(v,I){M.from_tag=I}(h,t[2])),t===null&&(e=h),t}function la(){var t,i;return i=e,r.substr(e,10)==="early-only"?(t="early-only",e+=10):(t=null,d('"early-only"')),t!==null&&(t=function(l){M.early_only=!0}()),t===null&&(e=i),t}function Io(t){t.sort();for(var i=null,l=[],h=0;h<t.length;h++)t[h]!==i&&(l.push(t[h]),i=t[h]);return l}function Ro(){for(var t=1,i=1,l=!1,h=0;h<Math.max(e,f);h++){var _=r.charAt(h);_===`
|
|
75
|
-
`?(l||t++,i=1,l=!1):_==="\r"||_==="\u2028"||_==="\u2029"?(t++,i=1,l=!0):(i++,l=!1)}return{line:t,column:i}}var ua=Ms(),Yn=ed(),M={},$o=c[a]();if($o===null||e!==r.length){var Is=Math.max(e,f),xo=Is<r.length?r.charAt(Is):null,ri=Ro();return new this.SyntaxError(Io(g),xo,Is,ri.line,ri.column),-1}return M},toSource:function(){return this._source}};return n.SyntaxError=function(r,a,c,e,f){function g(d,A){var S,R;switch(d.length){case 0:S="end of input";break;case 1:S=d[0];break;default:S=d.slice(0,d.length-1).join(", ")+" or "+d[d.length-1]}return R=A?o(A):"end of input","Expected "+S+" but "+R+" found."}this.name="SyntaxError",this.expected=r,this.found=a,this.message=g(r,a),this.offset=c,this.line=e,this.column=f},n.SyntaxError.prototype=Error.prototype,n}()),E_}var td,A_;function Ms(){if(A_)return td;A_=1;const o=bt,n=$n(),r=Hr();return td=class gb{static parse(c){if(c=r.parse(c,"SIP_URI"),c!==-1)return c}constructor(c,e,f,g,d={},A={}){if(!f)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=c||o.SIP,this._user=e,this._host=f,this._port=g;for(const S in d)Object.prototype.hasOwnProperty.call(d,S)&&this.setParam(S,d[S]);for(const S in A)Object.prototype.hasOwnProperty.call(A,S)&&this.setHeader(S,A[S])}get scheme(){return this._scheme}set scheme(c){this._scheme=c.toLowerCase()}get user(){return this._user}set user(c){this._user=c}get host(){return this._host}set host(c){this._host=c.toLowerCase()}get port(){return this._port}set port(c){this._port=c===0?c:parseInt(c,10)||null}setParam(c,e){c&&(this._parameters[c.toLowerCase()]=typeof e>"u"||e===null?null:e.toString())}getParam(c){if(c)return this._parameters[c.toLowerCase()]}hasParam(c){if(c)return this._parameters.hasOwnProperty(c.toLowerCase())&&!0||!1}deleteParam(c){if(c=c.toLowerCase(),this._parameters.hasOwnProperty(c)){const e=this._parameters[c];return delete this._parameters[c],e}}clearParams(){this._parameters={}}setHeader(c,e){this._headers[n.headerize(c)]=Array.isArray(e)?e:[e]}getHeader(c){if(c)return this._headers[n.headerize(c)]}hasHeader(c){if(c)return this._headers.hasOwnProperty(n.headerize(c))&&!0||!1}deleteHeader(c){if(c=n.headerize(c),this._headers.hasOwnProperty(c)){const e=this._headers[c];return delete this._headers[c],e}}clearHeaders(){this._headers={}}clone(){return new gb(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}toString(){const c=[];let e=`${this._scheme}:`;this._user&&(e+=`${n.escapeUser(this._user)}@`),e+=this._host,(this._port||this._port===0)&&(e+=`:${this._port}`);for(const f in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,f)&&(e+=`;${f}`,this._parameters[f]!==null&&(e+=`=${this._parameters[f]}`));for(const f in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,f))for(const g of this._headers[f])c.push(`${f}=${g}`);return c.length>0&&(e+=`?${c.join("&")}`),e}toAor(c){let e=`${this._scheme}:`;return this._user&&(e+=`${n.escapeUser(this._user)}@`),e+=this._host,c&&(this._port||this._port===0)&&(e+=`:${this._port}`),e}},td}var I_;function $n(){if(I_)return ln;I_=1;const o=bt,n=Ms(),r=Hr();ln.str_utf8_length=f=>unescape(encodeURIComponent(f)).length;const a=ln.isFunction=f=>f!==void 0?Object.prototype.toString.call(f)==="[object Function]":!1;ln.isString=f=>f!==void 0?Object.prototype.toString.call(f)==="[object String]":!1,ln.isDecimal=f=>!isNaN(f)&&parseFloat(f)===parseInt(f,10),ln.isEmpty=f=>f===null||f===""||f===void 0||Array.isArray(f)&&f.length===0||typeof f=="number"&&isNaN(f),ln.hasMethods=function(f,...g){for(const d of g)if(a(f[d]))return!1;return!0};const c=ln.createRandomToken=(f,g=32)=>{let d,A,S="";for(d=0;d<f;d++)A=Math.random()*g|0,S+=A.toString(g);return S};ln.newTag=()=>c(10),ln.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,f=>{const g=Math.random()*16|0;return(f==="x"?g:g&3|8).toString(16)}),ln.hostType=f=>{if(f){if(f=r.parse(f,"host"),f!==-1)return f.host_type}else return};const e=ln.escapeUser=f=>encodeURIComponent(decodeURIComponent(f)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/");return ln.normalizeTarget=(f,g)=>{if(f){if(f instanceof n)return f;if(typeof f=="string"){const d=f.split("@");let A,S;switch(d.length){case 1:if(!g)return;A=f,S=g;break;case 2:A=d[0],S=d[1];break;default:A=d.slice(0,d.length-1).join("@"),S=d[d.length-1]}A=A.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(A)&&(A=A.replace(/[-.()]/g,"")),f=`${o.SIP}:${e(A)}@${S}`;let R;return(R=n.parse(f))?R:void 0}else return}else return},ln.headerize=f=>{const g={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},d=f.toLowerCase().replace(/_/g,"-").split("-");let A="";const S=d.length;let R;for(R=0;R<S;R++)R!==0&&(A+="-"),A+=d[R].charAt(0).toUpperCase()+d[R].substring(1);return g[A]&&(A=g[A]),A},ln.sipErrorCause=f=>{for(const g in o.SIP_ERROR_CAUSES)if(o.SIP_ERROR_CAUSES[g].indexOf(f)!==-1)return o.causes[g];return o.causes.SIP_FAILURE_CODE},ln.getRandomTestNetIP=()=>{function f(g,d){return Math.floor(Math.random()*(d-g+1)+g)}return`192.0.2.${f(1,254)}`},ln.calculateMD5=f=>{function g(Xe,Je){return Xe<<Je|Xe>>>32-Je}function d(Xe,Je){const ut=Xe&2147483648,_t=Je&2147483648,mt=Xe&1073741824,Le=Je&1073741824,Pe=(Xe&1073741823)+(Je&1073741823);return mt&Le?Pe^2147483648^ut^_t:mt|Le?Pe&1073741824?Pe^3221225472^ut^_t:Pe^1073741824^ut^_t:Pe^ut^_t}function A(Xe,Je,ut){return Xe&Je|~Xe&ut}function S(Xe,Je,ut){return Xe&ut|Je&~ut}function R(Xe,Je,ut){return Xe^Je^ut}function N(Xe,Je,ut){return Je^(Xe|~ut)}function H(Xe,Je,ut,_t,mt,Le,Pe){return Xe=d(Xe,d(d(A(Je,ut,_t),mt),Pe)),d(g(Xe,Le),Je)}function W(Xe,Je,ut,_t,mt,Le,Pe){return Xe=d(Xe,d(d(S(Je,ut,_t),mt),Pe)),d(g(Xe,Le),Je)}function G(Xe,Je,ut,_t,mt,Le,Pe){return Xe=d(Xe,d(d(R(Je,ut,_t),mt),Pe)),d(g(Xe,Le),Je)}function K(Xe,Je,ut,_t,mt,Le,Pe){return Xe=d(Xe,d(d(N(Je,ut,_t),mt),Pe)),d(g(Xe,Le),Je)}function ae(Xe){let Je;const ut=Xe.length,_t=ut+8,mt=((_t-_t%64)/64+1)*16,Le=new Array(mt-1);let Pe=0,Ze=0;for(;Ze<ut;)Je=(Ze-Ze%4)/4,Pe=Ze%4*8,Le[Je]=Le[Je]|Xe.charCodeAt(Ze)<<Pe,Ze++;return Je=(Ze-Ze%4)/4,Pe=Ze%4*8,Le[Je]=Le[Je]|128<<Pe,Le[mt-2]=ut<<3,Le[mt-1]=ut>>>29,Le}function ee(Xe){let Je="",ut="",_t,mt;for(mt=0;mt<=3;mt++)_t=Xe>>>mt*8&255,ut=`0${_t.toString(16)}`,Je=Je+ut.substr(ut.length-2,2);return Je}function De(Xe){let Je="";for(let ut=0;ut<Xe.length;ut++){const _t=Xe.charCodeAt(ut);_t<128?Je+=String.fromCharCode(_t):_t>127&&_t<2048?(Je+=String.fromCharCode(_t>>6|192),Je+=String.fromCharCode(_t&63|128)):(Je+=String.fromCharCode(_t>>12|224),Je+=String.fromCharCode(_t>>6&63|128),Je+=String.fromCharCode(_t&63|128))}return Je}let X=[],re,be,Ne,Q,ce,me,_e,ue,ye;const Re=7,J=12,Se=17,$e=22,zt=5,Ae=9,fe=14,se=20,st=4,We=11,ht=16,It=23,qe=6,Ue=10,wt=15,Yt=21;for(f=De(f),X=ae(f),me=1732584193,_e=4023233417,ue=2562383102,ye=271733878,re=0;re<X.length;re+=16)be=me,Ne=_e,Q=ue,ce=ye,me=H(me,_e,ue,ye,X[re+0],Re,3614090360),ye=H(ye,me,_e,ue,X[re+1],J,3905402710),ue=H(ue,ye,me,_e,X[re+2],Se,606105819),_e=H(_e,ue,ye,me,X[re+3],$e,3250441966),me=H(me,_e,ue,ye,X[re+4],Re,4118548399),ye=H(ye,me,_e,ue,X[re+5],J,1200080426),ue=H(ue,ye,me,_e,X[re+6],Se,2821735955),_e=H(_e,ue,ye,me,X[re+7],$e,4249261313),me=H(me,_e,ue,ye,X[re+8],Re,1770035416),ye=H(ye,me,_e,ue,X[re+9],J,2336552879),ue=H(ue,ye,me,_e,X[re+10],Se,4294925233),_e=H(_e,ue,ye,me,X[re+11],$e,2304563134),me=H(me,_e,ue,ye,X[re+12],Re,1804603682),ye=H(ye,me,_e,ue,X[re+13],J,4254626195),ue=H(ue,ye,me,_e,X[re+14],Se,2792965006),_e=H(_e,ue,ye,me,X[re+15],$e,1236535329),me=W(me,_e,ue,ye,X[re+1],zt,4129170786),ye=W(ye,me,_e,ue,X[re+6],Ae,3225465664),ue=W(ue,ye,me,_e,X[re+11],fe,643717713),_e=W(_e,ue,ye,me,X[re+0],se,3921069994),me=W(me,_e,ue,ye,X[re+5],zt,3593408605),ye=W(ye,me,_e,ue,X[re+10],Ae,38016083),ue=W(ue,ye,me,_e,X[re+15],fe,3634488961),_e=W(_e,ue,ye,me,X[re+4],se,3889429448),me=W(me,_e,ue,ye,X[re+9],zt,568446438),ye=W(ye,me,_e,ue,X[re+14],Ae,3275163606),ue=W(ue,ye,me,_e,X[re+3],fe,4107603335),_e=W(_e,ue,ye,me,X[re+8],se,1163531501),me=W(me,_e,ue,ye,X[re+13],zt,2850285829),ye=W(ye,me,_e,ue,X[re+2],Ae,4243563512),ue=W(ue,ye,me,_e,X[re+7],fe,1735328473),_e=W(_e,ue,ye,me,X[re+12],se,2368359562),me=G(me,_e,ue,ye,X[re+5],st,4294588738),ye=G(ye,me,_e,ue,X[re+8],We,2272392833),ue=G(ue,ye,me,_e,X[re+11],ht,1839030562),_e=G(_e,ue,ye,me,X[re+14],It,4259657740),me=G(me,_e,ue,ye,X[re+1],st,2763975236),ye=G(ye,me,_e,ue,X[re+4],We,1272893353),ue=G(ue,ye,me,_e,X[re+7],ht,4139469664),_e=G(_e,ue,ye,me,X[re+10],It,3200236656),me=G(me,_e,ue,ye,X[re+13],st,681279174),ye=G(ye,me,_e,ue,X[re+0],We,3936430074),ue=G(ue,ye,me,_e,X[re+3],ht,3572445317),_e=G(_e,ue,ye,me,X[re+6],It,76029189),me=G(me,_e,ue,ye,X[re+9],st,3654602809),ye=G(ye,me,_e,ue,X[re+12],We,3873151461),ue=G(ue,ye,me,_e,X[re+15],ht,530742520),_e=G(_e,ue,ye,me,X[re+2],It,3299628645),me=K(me,_e,ue,ye,X[re+0],qe,4096336452),ye=K(ye,me,_e,ue,X[re+7],Ue,1126891415),ue=K(ue,ye,me,_e,X[re+14],wt,2878612391),_e=K(_e,ue,ye,me,X[re+5],Yt,4237533241),me=K(me,_e,ue,ye,X[re+12],qe,1700485571),ye=K(ye,me,_e,ue,X[re+3],Ue,2399980690),ue=K(ue,ye,me,_e,X[re+10],wt,4293915773),_e=K(_e,ue,ye,me,X[re+1],Yt,2240044497),me=K(me,_e,ue,ye,X[re+8],qe,1873313359),ye=K(ye,me,_e,ue,X[re+15],Ue,4264355552),ue=K(ue,ye,me,_e,X[re+6],wt,2734768916),_e=K(_e,ue,ye,me,X[re+13],Yt,1309151649),me=K(me,_e,ue,ye,X[re+4],qe,4149444226),ye=K(ye,me,_e,ue,X[re+11],Ue,3174756917),ue=K(ue,ye,me,_e,X[re+2],wt,718787259),_e=K(_e,ue,ye,me,X[re+9],Yt,3951481745),me=d(me,be),_e=d(_e,Ne),ue=d(ue,Q),ye=d(ye,ce);return(ee(me)+ee(_e)+ee(ue)+ee(ye)).toLowerCase()},ln.closeMediaStream=f=>{if(f)try{let g;if(f.getTracks){g=f.getTracks();for(const d of g)d.stop()}else{g=f.getAudioTracks();for(const d of g)d.stop();g=f.getVideoTracks();for(const d of g)d.stop()}}catch{(typeof f.stop=="function"||typeof f.stop=="object")&&f.stop()}},ln.cloneArray=f=>f&&f.slice()||[],ln.cloneObject=(f,g={})=>f&&Object.assign({},f)||g,ln}const R_=nr,EE=mn,xn=bt,pn=$n(),$_=ed(),CE=Hr(),nd=new EE("SIPMessage");class Su{constructor(n,r,a,c,e,f){if(!n||!r||!a)return null;c=c||{},this.ua=a,this.headers={},this.method=n,this.ruri=r,this.body=f,this.extraHeaders=pn.cloneArray(e),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),c.route_set?this.setHeader("route",c.route_set):a.configuration.use_preloaded_route&&this.setHeader("route",`<${a.transport.sip_uri};lr>`),this.setHeader("via",""),this.setHeader("max-forwards",xn.MAX_FORWARDS);const g=c.to_uri||r,d=c.to_tag?{tag:c.to_tag}:null,A=typeof c.to_display_name<"u"?c.to_display_name:null;this.to=new $_(g,A,d),this.setHeader("to",this.to.toString());const S=c.from_uri||a.configuration.uri,R={tag:c.from_tag||pn.newTag()};let N;typeof c.from_display_name<"u"?N=c.from_display_name:a.configuration.display_name?N=a.configuration.display_name:N=null,this.from=new $_(S,N,R),this.setHeader("from",this.from.toString());const H=c.call_id||a.configuration.jssip_id+pn.createRandomToken(15);this.call_id=H,this.setHeader("call-id",H);const W=c.cseq||Math.floor(Math.random()*1e4);this.cseq=W,this.setHeader("cseq",`${W} ${n}`)}setHeader(n,r){const a=new RegExp(`^\\s*${n}\\s*:`,"i");for(let c=0;c<this.extraHeaders.length;c++)a.test(this.extraHeaders[c])&&this.extraHeaders.splice(c,1);this.headers[pn.headerize(n)]=Array.isArray(r)?r:[r]}getHeader(n){const r=this.headers[pn.headerize(n)];if(r){if(r[0])return r[0]}else{const a=new RegExp(`^\\s*${n}\\s*:`,"i");for(const c of this.extraHeaders)if(a.test(c))return c.substring(c.indexOf(":")+1).trim()}}getHeaders(n){const r=this.headers[pn.headerize(n)],a=[];if(r){for(const c of r)a.push(c);return a}else{const c=new RegExp(`^\\s*${n}\\s*:`,"i");for(const e of this.extraHeaders)c.test(e)&&a.push(e.substring(e.indexOf(":")+1).trim());return a}}hasHeader(n){if(this.headers[pn.headerize(n)])return!0;{const r=new RegExp(`^\\s*${n}\\s*:`,"i");for(const a of this.extraHeaders)if(r.test(a))return!0}return!1}parseSDP(n){return!n&&this.sdp?this.sdp:(this.sdp=R_.parse(this.body||""),this.sdp)}toString(){let n=`${this.method} ${this.ruri} SIP/2.0\r
|
|
74
|
+
`,e+=2):(t=null,d('"\\r\\n"')),t}function S(){var t;return/^[0-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[0-9]")),t}function R(){var t;return/^[a-zA-Z]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-zA-Z]")),t}function N(){var t;return/^[0-9a-fA-F]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[0-9a-fA-F]")),t}function H(){var t;return t=K(),t===null&&(t=ae()),t}function W(){var t;return/^[\0-\xFF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\0-\\xFF]")),t}function G(){var t;return/^["]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d('["]')),t}function K(){var t;return r.charCodeAt(e)===32?(t=" ",e++):(t=null,d('" "')),t}function ae(){var t;return r.charCodeAt(e)===9?(t=" ",e++):(t=null,d('"\\t"')),t}function ee(){var t;return/^[a-zA-Z0-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-zA-Z0-9]")),t}function De(){var t;return r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","'))))))))))),t}function X(){var t;return t=ee(),t===null&&(t=re()),t}function re(){var t;return r.charCodeAt(e)===45?(t="-",e++):(t=null,d('"-"')),t===null&&(r.charCodeAt(e)===95?(t="_",e++):(t=null,d('"_"')),t===null&&(r.charCodeAt(e)===46?(t=".",e++):(t=null,d('"."')),t===null&&(r.charCodeAt(e)===33?(t="!",e++):(t=null,d('"!"')),t===null&&(r.charCodeAt(e)===126?(t="~",e++):(t=null,d('"~"')),t===null&&(r.charCodeAt(e)===42?(t="*",e++):(t=null,d('"*"')),t===null&&(r.charCodeAt(e)===39?(t="'",e++):(t=null,d(`"'"`)),t===null&&(r.charCodeAt(e)===40?(t="(",e++):(t=null,d('"("')),t===null&&(r.charCodeAt(e)===41?(t=")",e++):(t=null,d('")"')))))))))),t}function be(){var t,i,l,h,f;return h=e,f=e,r.charCodeAt(e)===37?(t="%",e++):(t=null,d('"%"')),t!==null?(i=N(),i!==null?(l=N(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){return I.join("")}(h,t)),t===null&&(e=h),t}function Ne(){var t,i,l,h,f,v;for(h=e,f=e,v=e,t=[],i=H();i!==null;)t.push(i),i=H();if(t!==null?(i=A(),i!==null?t=[t,i]:(t=null,e=v)):(t=null,e=v),t=t!==null?t:"",t!==null){if(l=H(),l!==null)for(i=[];l!==null;)i.push(l),l=H();else i=null;i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t!==null&&(t=function(I){return" "}()),t===null&&(e=h),t}function Q(){var t;return t=Ne(),t=t!==null?t:"",t}function ce(){var t,i,l,h,f;for(h=e,f=e,t=[],i=K(),i===null&&(i=ae());i!==null;)t.push(i),i=K(),i===null&&(i=ae());return t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return":"}()),t===null&&(e=h),t}function me(){var t,i,l,h,f,v,I;if(f=e,v=e,i=_e(),i!==null)for(t=[];i!==null;)t.push(i),i=_e();else t=null;if(t!==null){for(i=[],I=e,l=[],h=Ne();h!==null;)l.push(h),h=Ne();for(l!==null?(h=_e(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;){for(i.push(l),I=e,l=[],h=Ne();h!==null;)l.push(h),h=Ne();l!==null?(h=_e(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I)}i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){return r.substring(e,q)}(f)),t===null&&(e=f),t}function _e(){var t;return/^[!-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[!-~]")),t===null&&(t=ue()),t}function ue(){var t;return/^[\x80-\uFFFF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\x80-\\uFFFF]")),t}function ye(){var t;return/^[\x80-\xBF]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\x80-\\xBF]")),t}function Re(){var t;return t=S(),t===null&&(/^[a-f]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[a-f]"))),t}function J(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"'))))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function Se(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"'))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function $e(){var t;return r.charCodeAt(e)===40?(t="(",e++):(t=null,d('"("')),t===null&&(r.charCodeAt(e)===41?(t=")",e++):(t=null,d('")"')),t===null&&(r.charCodeAt(e)===60?(t="<",e++):(t=null,d('"<"')),t===null&&(r.charCodeAt(e)===62?(t=">",e++):(t=null,d('">"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===92?(t="\\",e++):(t=null,d('"\\\\"')),t===null&&(t=G(),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===123?(t="{",e++):(t=null,d('"{"')),t===null&&(r.charCodeAt(e)===125?(t="}",e++):(t=null,d('"}"')),t===null&&(t=K(),t===null&&(t=ae())))))))))))))))))),t}function zt(){var t,i,l;if(l=e,i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')),i===null&&(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i===null&&(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i===null&&(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i===null&&(r.charCodeAt(e)===62?(i=">",e++):(i=null,d('">"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===92?(i="\\",e++):(i=null,d('"\\\\"')),i===null&&(i=G(),i===null&&(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i===null&&(r.charCodeAt(e)===91?(i="[",e++):(i=null,d('"["')),i===null&&(r.charCodeAt(e)===93?(i="]",e++):(i=null,d('"]"')),i===null&&(r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i===null&&(r.charCodeAt(e)===123?(i="{",e++):(i=null,d('"{"')),i===null&&(r.charCodeAt(e)===125?(i="}",e++):(i=null,d('"}"'))))))))))))))))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=ee(),i===null&&(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i===null&&(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i===null&&(r.charCodeAt(e)===33?(i="!",e++):(i=null,d('"!"')),i===null&&(r.charCodeAt(e)===37?(i="%",e++):(i=null,d('"%"')),i===null&&(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i===null&&(r.charCodeAt(e)===95?(i="_",e++):(i=null,d('"_"')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===96?(i="`",e++):(i=null,d('"`"')),i===null&&(r.charCodeAt(e)===39?(i="'",e++):(i=null,d(`"'"`)),i===null&&(r.charCodeAt(e)===126?(i="~",e++):(i=null,d('"~"')),i===null&&(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i===null&&(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i===null&&(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i===null&&(r.charCodeAt(e)===62?(i=">",e++):(i=null,d('">"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===92?(i="\\",e++):(i=null,d('"\\\\"')),i===null&&(i=G(),i===null&&(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i===null&&(r.charCodeAt(e)===91?(i="[",e++):(i=null,d('"["')),i===null&&(r.charCodeAt(e)===93?(i="]",e++):(i=null,d('"]"')),i===null&&(r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i===null&&(r.charCodeAt(e)===123?(i="{",e++):(i=null,d('"{"')),i===null&&(r.charCodeAt(e)===125?(i="}",e++):(i=null,d('"}"')))))))))))))))))))))))));else t=null;return t!==null&&(t=function(h){return r.substring(e,h)}(l)),t===null&&(e=l),t}function Ae(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===42?(i="*",e++):(i=null,d('"*"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return"*"}()),t===null&&(e=h),t}function fe(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return"/"}()),t===null&&(e=h),t}function se(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return"="}()),t===null&&(e=h),t}function st(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===40?(i="(",e++):(i=null,d('"("')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return"("}()),t===null&&(e=h),t}function We(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===41?(i=")",e++):(i=null,d('")"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return")"}()),t===null&&(e=h),t}function ht(){var t,i,l,h;return l=e,h=e,r.charCodeAt(e)===62?(t=">",e++):(t=null,d('">"')),t!==null?(i=Q(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f){return">"}()),t===null&&(e=l),t}function It(){var t,i,l,h;return l=e,h=e,t=Q(),t!==null?(r.charCodeAt(e)===60?(i="<",e++):(i=null,d('"<"')),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f){return"<"}()),t===null&&(e=l),t}function qe(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return","}()),t===null&&(e=h),t}function Ue(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return";"}()),t===null&&(e=h),t}function wt(){var t,i,l,h,f;return h=e,f=e,t=Q(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Q(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return":"}()),t===null&&(e=h),t}function Yt(){var t,i,l,h;return l=e,h=e,t=Q(),t!==null?(i=G(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f){return'"'}()),t===null&&(e=l),t}function Xe(){var t,i,l,h;return l=e,h=e,t=G(),t!==null?(i=Q(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f){return'"'}()),t===null&&(e=l),t}function Je(){var t,i,l,h;if(h=e,t=st(),t!==null){for(i=[],l=ut(),l===null&&(l=Pe(),l===null&&(l=Je()));l!==null;)i.push(l),l=ut(),l===null&&(l=Pe(),l===null&&(l=Je()));i!==null?(l=We(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)}else t=null,e=h;return t}function ut(){var t;return/^[!-']/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[!-']")),t===null&&(/^[*-[]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[*-[]")),t===null&&(/^[\]-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\]-~]")),t===null&&(t=ue(),t===null&&(t=Ne())))),t}function _t(){var t,i,l,h,f,v;if(f=e,v=e,t=Q(),t!==null)if(i=G(),i!==null){for(l=[],h=Le(),h===null&&(h=Pe());h!==null;)l.push(h),h=Le(),h===null&&(h=Pe());l!==null?(h=G(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I){return r.substring(e,I)}(f)),t===null&&(e=f),t}function mt(){var t,i,l,h,f,v;if(f=e,v=e,t=Q(),t!==null)if(i=G(),i!==null){for(l=[],h=Le(),h===null&&(h=Pe());h!==null;)l.push(h),h=Le(),h===null&&(h=Pe());l!==null?(h=G(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I){var q=r.substring(e,I).trim();return q.substring(1,q.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(f)),t===null&&(e=f),t}function Le(){var t;return t=Ne(),t===null&&(r.charCodeAt(e)===33?(t="!",e++):(t=null,d('"!"')),t===null&&(/^[#-[]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[#-[]")),t===null&&(/^[\]-~]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[\\]-~]")),t===null&&(t=ue())))),t}function Pe(){var t,i,l;return l=e,r.charCodeAt(e)===92?(t="\\",e++):(t=null,d('"\\\\"')),t!==null?(/^[\0-\t]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\0-\\t]")),i===null&&(/^[\x0B-\f]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\x0B-\\f]")),i===null&&(/^[\x0E-]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[\\x0E-]")))),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Ze(){var t,i,l,h,f,v;return f=e,v=e,t=qt(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Wn(),l=l!==null?l:"",l!==null?(h=jr(),h!==null?t=[t,i,l,h]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t!==null&&(t=function(I){try{M.uri=new ua(M.scheme,M.user,M.host,M.port),delete M.scheme,delete M.user,delete M.host,delete M.host_type,delete M.port}catch{M=-1}}()),t===null&&(e=f),t}function Tt(){var t,i,l,h,f,v,I,q;return I=e,q=e,t=qt(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Wn(),l=l!==null?l:"",l!==null?(h=jr(),h!==null?(f=Vs(),f!==null?(v=Yr(),v=v!==null?v:"",v!==null?t=[t,i,l,h,f,v]:(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q)):(t=null,e=q),t!==null&&(t=function(j){try{M.uri=new ua(M.scheme,M.user,M.host,M.port,M.uri_params,M.uri_headers),delete M.scheme,delete M.user,delete M.host,delete M.host_type,delete M.port,delete M.uri_params,a==="SIP_URI"&&(M=M.uri)}catch{M=-1}}()),t===null&&(e=I),t}function qt(){var t;return t=rn(),t===null&&(t=Dt()),t}function rn(){var t,i;return i=e,r.substr(e,4).toLowerCase()==="sips"?(t=r.substr(e,4),e+=4):(t=null,d('"sips"')),t!==null&&(t=function(l,h){M.scheme=h.toLowerCase()}(i,t)),t===null&&(e=i),t}function Dt(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"sip"')),t!==null&&(t=function(l,h){M.scheme=h.toLowerCase()}(i,t)),t===null&&(e=i),t}function Wn(){var t,i,l,h,f,v;return h=e,f=e,t=Pn(),t!==null?(v=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=Aa(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?(r.charCodeAt(e)===64?(l="@",e++):(l=null,d('"@"')),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){M.user=decodeURIComponent(r.substring(e-1,I))}(h)),t===null&&(e=h),t}function Pn(){var t,i;if(i=X(),i===null&&(i=be(),i===null&&(i=Bs())),i!==null)for(t=[];i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(i=Bs()));else t=null;return t}function Bs(){var t;return r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"'))))))))),t}function Aa(){var t,i,l;for(l=e,t=[],i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","'))))))));i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","'))))))));return t!==null&&(t=function(h){M.password=r.substring(e,h)}(l)),t===null&&(e=l),t}function jr(){var t,i,l,h,f;return h=e,t=ar(),t!==null?(f=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=gn(),l!==null?i=[i,l]:(i=null,e=f)):(i=null,e=f),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function ar(){var t,i;return i=e,t=_n(),t===null&&(t=or(),t===null&&(t=Wr())),t!==null&&(t=function(l){return M.host=r.substring(e,l).toLowerCase(),M.host}(i)),t===null&&(e=i),t}function _n(){var t,i,l,h,f,v;for(h=e,f=e,t=[],v=e,i=Gr(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v);i!==null;)t.push(i),v=e,i=Gr(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v);return t!==null?(i=yi(),i!==null?(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){return M.host_type="domain",r.substring(e,I)}(h)),t===null&&(e=h),t}function Gr(){var t,i,l,h;if(h=e,t=ee(),t!==null){for(i=[],l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));l!==null;)i.push(l),l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function yi(){var t,i,l,h;if(h=e,t=R(),t!==null){for(i=[],l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));l!==null;)i.push(l),l=ee(),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===95?(l="_",e++):(l=null,d('"_"'))));i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function Wr(){var t,i,l,h,f;return h=e,f=e,r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t!==null?(i=Kr(),i!==null?(r.charCodeAt(e)===93?(l="]",e++):(l=null,d('"]"')),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v){return M.host_type="IPv6",r.substring(e,v)}(h)),t===null&&(e=h),t}function Kr(){var t,i,l,h,f,v,I,q,j,Oe,it,an,Pr,ts,z,he;return ts=e,z=e,t=de(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?(r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=de(),j!==null?(r.charCodeAt(e)===58?(Oe=":",e++):(Oe=null,d('":"')),Oe!==null?(it=de(),it!==null?(r.charCodeAt(e)===58?(an=":",e++):(an=null,d('":"')),an!==null?(Pr=Pt(),Pr!==null?t=[t,i,l,h,f,v,I,q,j,Oe,it,an,Pr]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=de(),Oe!==null?(r.charCodeAt(e)===58?(it=":",e++):(it=null,d('":"')),it!==null?(an=Pt(),an!==null?t=[t,i,l,h,f,v,I,q,j,Oe,it,an]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=Pt(),Oe!==null?t=[t,i,l,h,f,v,I,q,j,Oe]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=Pt(),q!==null?t=[t,i,l,h,f,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=Pt(),v!==null?t=[t,i,l,h,f,v]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?(r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=Pt(),h!==null?t=[t,i,l,h]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=Pt(),i!==null?t=[t,i]:(t=null,e=z)):(t=null,e=z),t===null&&(z=e,r.substr(e,2)==="::"?(t="::",e+=2):(t=null,d('"::"')),t!==null?(i=de(),i!==null?t=[t,i]:(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(r.substr(e,2)==="::"?(i="::",e+=2):(i=null,d('"::"')),i!==null?(l=de(),l!==null?(r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=de(),j!==null?(r.charCodeAt(e)===58?(Oe=":",e++):(Oe=null,d('":"')),Oe!==null?(it=Pt(),it!==null?t=[t,i,l,h,f,v,I,q,j,Oe,it]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(r.substr(e,2)==="::"?(l="::",e+=2):(l=null,d('"::"')),l!==null?(h=de(),h!==null?(r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?(r.charCodeAt(e)===58?(j=":",e++):(j=null,d('":"')),j!==null?(Oe=Pt(),Oe!==null?t=[t,i,l,h,f,v,I,q,j,Oe]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(r.substr(e,2)==="::"?(h="::",e+=2):(h=null,d('"::"')),h!==null?(f=de(),f!==null?(r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?(r.charCodeAt(e)===58?(q=":",e++):(q=null,d('":"')),q!==null?(j=Pt(),j!==null?t=[t,i,l,h,f,v,I,q,j]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?h=[h,f]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(r.substr(e,2)==="::"?(f="::",e+=2):(f=null,d('"::"')),f!==null?(v=de(),v!==null?(r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=Pt(),q!==null?t=[t,i,l,h,f,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?h=[h,f]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?f=[f,v]:(f=null,e=he)):(f=null,e=he),f=f!==null?f:"",f!==null?(r.substr(e,2)==="::"?(v="::",e+=2):(v=null,d('"::"')),v!==null?(I=Pt(),I!==null?t=[t,i,l,h,f,v,I]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?h=[h,f]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?f=[f,v]:(f=null,e=he)):(f=null,e=he),f=f!==null?f:"",f!==null?(he=e,r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?v=[v,I]:(v=null,e=he)):(v=null,e=he),v=v!==null?v:"",v!==null?(r.substr(e,2)==="::"?(I="::",e+=2):(I=null,d('"::"')),I!==null?(q=de(),q!==null?t=[t,i,l,h,f,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z),t===null&&(z=e,t=de(),t!==null?(he=e,r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?i=[i,l]:(i=null,e=he)):(i=null,e=he),i=i!==null?i:"",i!==null?(he=e,r.charCodeAt(e)===58?(l=":",e++):(l=null,d('":"')),l!==null?(h=de(),h!==null?l=[l,h]:(l=null,e=he)):(l=null,e=he),l=l!==null?l:"",l!==null?(he=e,r.charCodeAt(e)===58?(h=":",e++):(h=null,d('":"')),h!==null?(f=de(),f!==null?h=[h,f]:(h=null,e=he)):(h=null,e=he),h=h!==null?h:"",h!==null?(he=e,r.charCodeAt(e)===58?(f=":",e++):(f=null,d('":"')),f!==null?(v=de(),v!==null?f=[f,v]:(f=null,e=he)):(f=null,e=he),f=f!==null?f:"",f!==null?(he=e,r.charCodeAt(e)===58?(v=":",e++):(v=null,d('":"')),v!==null?(I=de(),I!==null?v=[v,I]:(v=null,e=he)):(v=null,e=he),v=v!==null?v:"",v!==null?(he=e,r.charCodeAt(e)===58?(I=":",e++):(I=null,d('":"')),I!==null?(q=de(),q!==null?I=[I,q]:(I=null,e=he)):(I=null,e=he),I=I!==null?I:"",I!==null?(r.substr(e,2)==="::"?(q="::",e+=2):(q=null,d('"::"')),q!==null?t=[t,i,l,h,f,v,I,q]:(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z)):(t=null,e=z))))))))))))))),t!==null&&(t=function(Oo){return M.host_type="IPv6",r.substring(e,Oo)}(ts)),t===null&&(e=ts),t}function de(){var t,i,l,h,f;return f=e,t=N(),t!==null?(i=N(),i=i!==null?i:"",i!==null?(l=N(),l=l!==null?l:"",l!==null?(h=N(),h=h!==null?h:"",h!==null?t=[t,i,l,h]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t}function Pt(){var t,i,l,h;return h=e,t=de(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=de(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(t=or()),t}function or(){var t,i,l,h,f,v,I,q,j;return q=e,j=e,t=lr(),t!==null?(r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i!==null?(l=lr(),l!==null?(r.charCodeAt(e)===46?(h=".",e++):(h=null,d('"."')),h!==null?(f=lr(),f!==null?(r.charCodeAt(e)===46?(v=".",e++):(v=null,d('"."')),v!==null?(I=lr(),I!==null?t=[t,i,l,h,f,v,I]:(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j)):(t=null,e=j),t!==null&&(t=function(Oe){return M.host_type="IPv4",r.substring(e,Oe)}(q)),t===null&&(e=q),t}function lr(){var t,i,l,h;return h=e,r.substr(e,2)==="25"?(t="25",e+=2):(t=null,d('"25"')),t!==null?(/^[0-5]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[0-5]")),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t===null&&(h=e,r.charCodeAt(e)===50?(t="2",e++):(t=null,d('"2"')),t!==null?(/^[0-4]/.test(r.charAt(e))?(i=r.charAt(e),e++):(i=null,d("[0-4]")),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(h=e,r.charCodeAt(e)===49?(t="1",e++):(t=null,d('"1"')),t!==null?(i=S(),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t===null&&(h=e,/^[1-9]/.test(r.charAt(e))?(t=r.charAt(e),e++):(t=null,d("[1-9]")),t!==null?(i=S(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t===null&&(t=S())))),t}function gn(){var t,i,l,h,f,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(f=S(),f=f!==null?f:"",f!==null?t=[t,i,l,h,f]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){return j=parseInt(j.join("")),M.port=j,j}(v,t)),t===null&&(e=v),t}function Vs(){var t,i,l,h;for(t=[],h=e,r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=$r(),l!==null?i=[i,l]:(i=null,e=h)):(i=null,e=h);i!==null;)t.push(i),h=e,r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i!==null?(l=$r(),l!==null?i=[i,l]:(i=null,e=h)):(i=null,e=h);return t}function $r(){var t;return t=vi(),t===null&&(t=Ti(),t===null&&(t=js(),t===null&&(t=bi(),t===null&&(t=Gs(),t===null&&(t=wi(),t===null&&(t=Ws())))))),t}function vi(){var t,i,l,h;return l=e,h=e,r.substr(e,10).toLowerCase()==="transport="?(t=r.substr(e,10),e+=10):(t=null,d('"transport="')),t!==null?(r.substr(e,3).toLowerCase()==="udp"?(i=r.substr(e,3),e+=3):(i=null,d('"udp"')),i===null&&(r.substr(e,3).toLowerCase()==="tcp"?(i=r.substr(e,3),e+=3):(i=null,d('"tcp"')),i===null&&(r.substr(e,4).toLowerCase()==="sctp"?(i=r.substr(e,4),e+=4):(i=null,d('"sctp"')),i===null&&(r.substr(e,3).toLowerCase()==="tls"?(i=r.substr(e,3),e+=3):(i=null,d('"tls"')),i===null&&(i=J())))),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.uri_params||(M.uri_params={}),M.uri_params.transport=v.toLowerCase()}(l,t[1])),t===null&&(e=l),t}function Ti(){var t,i,l,h;return l=e,h=e,r.substr(e,5).toLowerCase()==="user="?(t=r.substr(e,5),e+=5):(t=null,d('"user="')),t!==null?(r.substr(e,5).toLowerCase()==="phone"?(i=r.substr(e,5),e+=5):(i=null,d('"phone"')),i===null&&(r.substr(e,2).toLowerCase()==="ip"?(i=r.substr(e,2),e+=2):(i=null,d('"ip"')),i===null&&(i=J())),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.uri_params||(M.uri_params={}),M.uri_params.user=v.toLowerCase()}(l,t[1])),t===null&&(e=l),t}function js(){var t,i,l,h;return l=e,h=e,r.substr(e,7).toLowerCase()==="method="?(t=r.substr(e,7),e+=7):(t=null,d('"method="')),t!==null?(i=kr(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.uri_params||(M.uri_params={}),M.uri_params.method=v}(l,t[1])),t===null&&(e=l),t}function bi(){var t,i,l,h;return l=e,h=e,r.substr(e,4).toLowerCase()==="ttl="?(t=r.substr(e,4),e+=4):(t=null,d('"ttl="')),t!==null?(i=Ss(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.params||(M.params={}),M.params.ttl=v}(l,t[1])),t===null&&(e=l),t}function Gs(){var t,i,l,h;return l=e,h=e,r.substr(e,6).toLowerCase()==="maddr="?(t=r.substr(e,6),e+=6):(t=null,d('"maddr="')),t!==null?(i=ar(),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t!==null&&(t=function(f,v){M.uri_params||(M.uri_params={}),M.uri_params.maddr=v}(l,t[1])),t===null&&(e=l),t}function wi(){var t,i,l,h,f,v;return h=e,f=e,r.substr(e,2).toLowerCase()==="lr"?(t=r.substr(e,2),e+=2):(t=null,d('"lr"')),t!==null?(v=e,r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=J(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){M.uri_params||(M.uri_params={}),M.uri_params.lr=void 0}()),t===null&&(e=h),t}function Ws(){var t,i,l,h,f,v;return h=e,f=e,t=Si(),t!==null?(v=e,r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Ks(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I,q,j){M.uri_params||(M.uri_params={}),typeof j>"u"?j=void 0:j=j[1],M.uri_params[q.toLowerCase()]=j}(h,t[0],t[1])),t===null&&(e=h),t}function Si(){var t,i,l;if(l=e,i=Qn(),i!==null)for(t=[];i!==null;)t.push(i),i=Qn();else t=null;return t!==null&&(t=function(h,f){return f.join("")}(l,t)),t===null&&(e=l),t}function Ks(){var t,i,l;if(l=e,i=Qn(),i!==null)for(t=[];i!==null;)t.push(i),i=Qn();else t=null;return t!==null&&(t=function(h,f){return f.join("")}(l,t)),t===null&&(e=l),t}function Qn(){var t;return t=ds(),t===null&&(t=X(),t===null&&(t=be())),t}function ds(){var t;return r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')))))))),t}function Yr(){var t,i,l,h,f,v,I;if(v=e,r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t!==null)if(i=mr(),i!==null){for(l=[],I=e,r.charCodeAt(e)===38?(h="&",e++):(h=null,d('"&"')),h!==null?(f=mr(),f!==null?h=[h,f]:(h=null,e=I)):(h=null,e=I);h!==null;)l.push(h),I=e,r.charCodeAt(e)===38?(h="&",e++):(h=null,d('"&"')),h!==null?(f=mr(),f!==null?h=[h,f]:(h=null,e=I)):(h=null,e=I);l!==null?t=[t,i,l]:(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t}function mr(){var t,i,l,h,f;return h=e,f=e,t=Ei(),t!==null?(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i!==null?(l=Ci(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I,q){I=I.join("").toLowerCase(),q=q.join(""),M.uri_headers||(M.uri_headers={}),M.uri_headers[I]?M.uri_headers[I].push(q):M.uri_headers[I]=[q]}(h,t[0],t[2])),t===null&&(e=h),t}function Ei(){var t,i;if(i=ur(),i===null&&(i=X(),i===null&&(i=be())),i!==null)for(t=[];i!==null;)t.push(i),i=ur(),i===null&&(i=X(),i===null&&(i=be()));else t=null;return t}function Ci(){var t,i;for(t=[],i=ur(),i===null&&(i=X(),i===null&&(i=be()));i!==null;)t.push(i),i=ur(),i===null&&(i=X(),i===null&&(i=be()));return t}function ur(){var t;return r.charCodeAt(e)===91?(t="[",e++):(t=null,d('"["')),t===null&&(r.charCodeAt(e)===93?(t="]",e++):(t=null,d('"]"')),t===null&&(r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')))))))),t}function Ia(){var t;return t=Di(),t===null&&(t=$t()),t}function $t(){var t,i,l,h,f,v;return v=e,t=kr(),t!==null?(i=K(),i!==null?(l=gr(),l!==null?(h=K(),h!==null?(f=Or(),f!==null?t=[t,i,l,h,f]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function gr(){var t;return t=Tt(),t===null&&(t=yn()),t}function yn(){var t,i,l,h;return h=e,t=$i(),t!==null?(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i!==null?(l=hs(),l===null&&(l=Ai()),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function hs(){var t,i,l,h,f;return h=e,t=Et(),t===null&&(t=yr()),t!==null?(f=e,r.charCodeAt(e)===63?(i="?",e++):(i=null,d('"?"')),i!==null?(l=wr(),l!==null?i=[i,l]:(i=null,e=f)):(i=null,e=f),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function Et(){var t,i,l,h;return h=e,r.substr(e,2)==="//"?(t="//",e+=2):(t=null,d('"//"')),t!==null?(i=Ra(),i!==null?(l=yr(),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function yr(){var t,i,l;return l=e,r.charCodeAt(e)===47?(t="/",e++):(t=null,d('"/"')),t!==null?(i=Ri(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Ai(){var t,i,l,h;if(h=e,t=Ii(),t!==null){for(i=[],l=vr();l!==null;)i.push(l),l=vr();i!==null?t=[t,i]:(t=null,e=h)}else t=null,e=h;return t}function vr(){var t;return t=De(),t===null&&(t=X(),t===null&&(t=be())),t}function Ii(){var t;return t=X(),t===null&&(t=be(),t===null&&(r.charCodeAt(e)===59?(t=";",e++):(t=null,d('";"')),t===null&&(r.charCodeAt(e)===63?(t="?",e++):(t=null,d('"?"')),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')))))))))))),t}function Ri(){var t,i,l,h,f,v;if(f=e,t=xr(),t!==null){for(i=[],v=e,r.charCodeAt(e)===47?(l="/",e++):(l=null,d('"/"')),l!==null?(h=xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===47?(l="/",e++):(l=null,d('"/"')),l!==null?(h=xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function xr(){var t,i,l,h,f,v;for(f=e,t=[],i=cr();i!==null;)t.push(i),i=cr();if(t!==null){for(i=[],v=e,r.charCodeAt(e)===59?(l=";",e++):(l=null,d('";"')),l!==null?(h=Tr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===59?(l=";",e++):(l=null,d('";"')),l!==null?(h=Tr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Tr(){var t,i;for(t=[],i=cr();i!==null;)t.push(i),i=cr();return t}function cr(){var t;return t=X(),t===null&&(t=be(),t===null&&(r.charCodeAt(e)===58?(t=":",e++):(t=null,d('":"')),t===null&&(r.charCodeAt(e)===64?(t="@",e++):(t=null,d('"@"')),t===null&&(r.charCodeAt(e)===38?(t="&",e++):(t=null,d('"&"')),t===null&&(r.charCodeAt(e)===61?(t="=",e++):(t=null,d('"="')),t===null&&(r.charCodeAt(e)===43?(t="+",e++):(t=null,d('"+"')),t===null&&(r.charCodeAt(e)===36?(t="$",e++):(t=null,d('"$"')),t===null&&(r.charCodeAt(e)===44?(t=",",e++):(t=null,d('","')))))))))),t}function $i(){var t,i,l,h,f;if(h=e,f=e,t=R(),t!==null){for(i=[],l=R(),l===null&&(l=S(),l===null&&(r.charCodeAt(e)===43?(l="+",e++):(l=null,d('"+"')),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."'))))));l!==null;)i.push(l),l=R(),l===null&&(l=S(),l===null&&(r.charCodeAt(e)===43?(l="+",e++):(l=null,d('"+"')),l===null&&(r.charCodeAt(e)===45?(l="-",e++):(l=null,d('"-"')),l===null&&(r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."'))))));i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t!==null&&(t=function(v){M.scheme=r.substring(e,v)}(h)),t===null&&(e=h),t}function Ra(){var t;return t=br(),t===null&&(t=Zn()),t}function br(){var t,i,l,h;return l=e,h=e,t=Wn(),t!==null?(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t=t!==null?t:"",t!==null?(i=jr(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t=t!==null?t:"",t}function Zn(){var t,i;if(i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i===null&&(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"'))))))))))),i!==null)for(t=[];i!==null;)t.push(i),i=X(),i===null&&(i=be(),i===null&&(r.charCodeAt(e)===36?(i="$",e++):(i=null,d('"$"')),i===null&&(r.charCodeAt(e)===44?(i=",",e++):(i=null,d('","')),i===null&&(r.charCodeAt(e)===59?(i=";",e++):(i=null,d('";"')),i===null&&(r.charCodeAt(e)===58?(i=":",e++):(i=null,d('":"')),i===null&&(r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i===null&&(r.charCodeAt(e)===38?(i="&",e++):(i=null,d('"&"')),i===null&&(r.charCodeAt(e)===61?(i="=",e++):(i=null,d('"="')),i===null&&(r.charCodeAt(e)===43?(i="+",e++):(i=null,d('"+"')))))))))));else t=null;return t}function wr(){var t,i;for(t=[],i=vr();i!==null;)t.push(i),i=vr();return t}function Or(){var t,i,l,h,f,v,I,q;if(I=e,q=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t!==null)if(r.charCodeAt(e)===47?(i="/",e++):(i=null,d('"/"')),i!==null){if(h=S(),h!==null)for(l=[];h!==null;)l.push(h),h=S();else l=null;if(l!==null)if(r.charCodeAt(e)===46?(h=".",e++):(h=null,d('"."')),h!==null){if(v=S(),v!==null)for(f=[];v!==null;)f.push(v),v=S();else f=null;f!==null?t=[t,i,l,h,f]:(t=null,e=q)}else t=null,e=q;else t=null,e=q}else t=null,e=q;else t=null,e=q;return t!==null&&(t=function(j){M.sip_version=r.substring(e,j)}(I)),t===null&&(e=I),t}function ps(){var t;return r.substr(e,6)==="INVITE"?(t="INVITE",e+=6):(t=null,d('"INVITE"')),t}function Ys(){var t;return r.substr(e,3)==="ACK"?(t="ACK",e+=3):(t=null,d('"ACK"')),t}function Xs(){var t;return r.substr(e,7)==="OPTIONS"?(t="OPTIONS",e+=7):(t=null,d('"OPTIONS"')),t}function Js(){var t;return r.substr(e,3)==="BYE"?(t="BYE",e+=3):(t=null,d('"BYE"')),t}function rt(){var t;return r.substr(e,6)==="CANCEL"?(t="CANCEL",e+=6):(t=null,d('"CANCEL"')),t}function Qs(){var t;return r.substr(e,8)==="REGISTER"?(t="REGISTER",e+=8):(t=null,d('"REGISTER"')),t}function xi(){var t;return r.substr(e,9)==="SUBSCRIBE"?(t="SUBSCRIBE",e+=9):(t=null,d('"SUBSCRIBE"')),t}function Oi(){var t;return r.substr(e,6)==="NOTIFY"?(t="NOTIFY",e+=6):(t=null,d('"NOTIFY"')),t}function ki(){var t;return r.substr(e,5)==="REFER"?(t="REFER",e+=5):(t=null,d('"REFER"')),t}function kr(){var t,i;return i=e,t=ps(),t===null&&(t=Ys(),t===null&&(t=Xs(),t===null&&(t=Js(),t===null&&(t=rt(),t===null&&(t=Qs(),t===null&&(t=xi(),t===null&&(t=Oi(),t===null&&(t=ki(),t===null&&(t=J()))))))))),t!==null&&(t=function(l){return M.method=r.substring(e,l),M.method}(i)),t===null&&(e=i),t}function Di(){var t,i,l,h,f,v;return v=e,t=Or(),t!==null?(i=K(),i!==null?(l=Zs(),l!==null?(h=K(),h!==null?(f=vt(),f!==null?t=[t,i,l,h,f]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function Zs(){var t,i;return i=e,t=Ni(),t!==null&&(t=function(l,h){M.status_code=parseInt(h.join(""))}(i,t)),t===null&&(e=i),t}function Ni(){var t,i,l,h;return h=e,t=S(),t!==null?(i=S(),i!==null?(l=S(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function vt(){var t,i,l;for(l=e,t=[],i=De(),i===null&&(i=X(),i===null&&(i=be(),i===null&&(i=ue(),i===null&&(i=ye(),i===null&&(i=K(),i===null&&(i=ae()))))));i!==null;)t.push(i),i=De(),i===null&&(i=X(),i===null&&(i=be(),i===null&&(i=ue(),i===null&&(i=ye(),i===null&&(i=K(),i===null&&(i=ae()))))));return t!==null&&(t=function(h){M.reason_phrase=r.substring(e,h)}(l)),t===null&&(e=l),t}function Sr(){var t,i,l,h,f,v;if(f=e,t=er(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=er(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=er(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function lo(){var t,i,l,h,f,v;return h=e,f=e,t=zt(),t!==null?(v=e,r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?(l=zt(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){M=r.substring(e,I)}(h)),t===null&&(e=h),t}function _s(){var t,i,l,h,f,v,I;if(f=e,t=Ae(),t===null)if(v=e,t=ne(),t!==null){for(i=[],I=e,l=qe(),l!==null?(h=ne(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=qe(),l!==null?(h=ne(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j,Oe;for(Oe=M.multi_header.length,j=0;j<Oe;j++)if(M.multi_header[j].parsed===null){M=null;break}M!==null?M=M.multi_header:M=-1}()),t===null&&(e=f),t}function ne(){var t,i,l,h,f,v,I;if(f=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=fs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=fs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j;M.multi_header||(M.multi_header=[]);try{j=new Yn(M.uri,M.display_name,M.params),delete M.uri,delete M.display_name,delete M.params}catch{j=null}M.multi_header.push({possition:e,offset:q,parsed:j})}(f)),t===null&&(e=f),t}function fn(){var t,i,l,h,f;return f=e,t=Dr(),t=t!==null?t:"",t!==null?(i=It(),i!==null?(l=Tt(),l!==null?(h=ht(),h!==null?t=[t,i,l,h]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t}function Dr(){var t,i,l,h,f,v,I;if(f=e,v=e,t=J(),t!==null){for(i=[],I=e,l=Ne(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ne(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t===null&&(t=mt()),t!==null&&(t=function(q,j){typeof j=="string"?M.display_name=j:M.display_name=j[1].reduce(function(Oe,it){return Oe+it[0]+it[1]},j[0])}(f,t)),t===null&&(e=f),t}function fs(){var t;return t=Mi(),t===null&&(t=ct(),t===null&&(t=gt())),t}function Mi(){var t,i,l,h,f;return h=e,f=e,r.substr(e,1).toLowerCase()==="q"?(t=r.substr(e,1),e++):(t=null,d('"q"')),t!==null?(i=se(),i!==null?(l=Ui(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.params||(M.params={}),M.params.q=I}(h,t[2])),t===null&&(e=h),t}function ct(){var t,i,l,h,f;return h=e,f=e,r.substr(e,7).toLowerCase()==="expires"?(t=r.substr(e,7),e+=7):(t=null,d('"expires"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.params||(M.params={}),M.params.expires=I}(h,t[2])),t===null&&(e=h),t}function vn(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,f){return parseInt(f.join(""))}(l,t)),t===null&&(e=l),t}function Ui(){var t,i,l,h,f,v,I,q;return v=e,I=e,r.charCodeAt(e)===48?(t="0",e++):(t=null,d('"0"')),t!==null?(q=e,r.charCodeAt(e)===46?(i=".",e++):(i=null,d('"."')),i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(f=S(),f=f!==null?f:"",f!==null?i=[i,l,h,f]:(i=null,e=q)):(i=null,e=q)):(i=null,e=q)):(i=null,e=q),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(j){return parseFloat(r.substring(e,j))}(v)),t===null&&(e=v),t}function gt(){var t,i,l,h,f,v;return h=e,f=e,t=J(),t!==null?(v=e,i=se(),i!==null?(l=ei(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I,q,j){M.params||(M.params={}),typeof j>"u"?j=void 0:j=j[1],M.params[q.toLowerCase()]=j}(h,t[0],t[1])),t===null&&(e=h),t}function ei(){var t;return t=J(),t===null&&(t=ar(),t===null&&(t=_t())),t}function $a(){var t,i,l,h,f,v;if(f=e,t=Pi(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Xr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Pi(){var t;return r.substr(e,6).toLowerCase()==="render"?(t=r.substr(e,6),e+=6):(t=null,d('"render"')),t===null&&(r.substr(e,7).toLowerCase()==="session"?(t=r.substr(e,7),e+=7):(t=null,d('"session"')),t===null&&(r.substr(e,4).toLowerCase()==="icon"?(t=r.substr(e,4),e+=4):(t=null,d('"icon"')),t===null&&(r.substr(e,5).toLowerCase()==="alert"?(t=r.substr(e,5),e+=5):(t=null,d('"alert"')),t===null&&(t=J())))),t}function Xr(){var t;return t=Li(),t===null&&(t=gt()),t}function Li(){var t,i,l,h;return h=e,r.substr(e,8).toLowerCase()==="handling"?(t=r.substr(e,8),e+=8):(t=null,d('"handling"')),t!==null?(i=se(),i!==null?(r.substr(e,8).toLowerCase()==="optional"?(l=r.substr(e,8),e+=8):(l=null,d('"optional"')),l===null&&(r.substr(e,8).toLowerCase()==="required"?(l=r.substr(e,8),e+=8):(l=null,d('"required"')),l===null&&(l=J())),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function xa(){var t,i,l,h,f,v;if(f=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Oa(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,f){M=parseInt(f.join(""))}(l,t)),t===null&&(e=l),t}function ka(){var t,i;return i=e,t=qi(),t!==null&&(t=function(l){M=r.substring(e,l)}(i)),t===null&&(e=i),t}function qi(){var t,i,l,h,f,v,I,q;if(I=e,t=Hi(),t!==null)if(i=fe(),i!==null)if(l=Na(),l!==null){for(h=[],q=e,f=Ue(),f!==null?(v=Qr(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);f!==null;)h.push(f),q=e,f=Ue(),f!==null?(v=Qr(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function Hi(){var t;return t=Da(),t===null&&(t=Jr()),t}function Da(){var t;return r.substr(e,4).toLowerCase()==="text"?(t=r.substr(e,4),e+=4):(t=null,d('"text"')),t===null&&(r.substr(e,5).toLowerCase()==="image"?(t=r.substr(e,5),e+=5):(t=null,d('"image"')),t===null&&(r.substr(e,5).toLowerCase()==="audio"?(t=r.substr(e,5),e+=5):(t=null,d('"audio"')),t===null&&(r.substr(e,5).toLowerCase()==="video"?(t=r.substr(e,5),e+=5):(t=null,d('"video"')),t===null&&(r.substr(e,11).toLowerCase()==="application"?(t=r.substr(e,11),e+=11):(t=null,d('"application"')),t===null&&(t=Nr()))))),t}function Jr(){var t;return r.substr(e,7).toLowerCase()==="message"?(t=r.substr(e,7),e+=7):(t=null,d('"message"')),t===null&&(r.substr(e,9).toLowerCase()==="multipart"?(t=r.substr(e,9),e+=9):(t=null,d('"multipart"')),t===null&&(t=Nr())),t}function Nr(){var t;return t=J(),t===null&&(t=zi()),t}function zi(){var t,i,l;return l=e,r.substr(e,2).toLowerCase()==="x-"?(t=r.substr(e,2),e+=2):(t=null,d('"x-"')),t!==null?(i=J(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function Na(){var t;return t=Nr(),t===null&&(t=J()),t}function Qr(){var t,i,l,h;return h=e,t=J(),t!==null?(i=se(),i!==null?(l=ti(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function ti(){var t;return t=J(),t===null&&(t=_t()),t}function Fi(){var t,i,l,h;return h=e,t=ms(),t!==null?(i=Ne(),i!==null?(l=kr(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function ms(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,f){M.value=parseInt(f.join(""))}(l,t)),t===null&&(e=l),t}function uo(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M=h}(i,t)),t===null&&(e=i),t}function co(){var t,i,l,h,f,v,I;if(f=e,v=e,t=er(),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q,j){M.event=j.join("").toLowerCase()}(f,t[0])),t===null&&(e=f),t}function er(){var t,i,l,h,f,v;if(f=e,t=Se(),t!==null){for(i=[],v=e,r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?(h=Se(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,r.charCodeAt(e)===46?(l=".",e++):(l=null,d('"."')),l!==null?(h=Se(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Ma(){var t,i,l,h,f,v,I;if(f=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j=M.tag;try{M=new Yn(M.uri,M.display_name,M.params),j&&M.setParam("tag",j)}catch{M=-1}}()),t===null&&(e=f),t}function gs(){var t;return t=ys(),t===null&&(t=gt()),t}function ys(){var t,i,l,h,f;return h=e,f=e,r.substr(e,3).toLowerCase()==="tag"?(t=r.substr(e,3),e+=3):(t=null,d('"tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.tag=I}(h,t[2])),t===null&&(e=h),t}function El(){var t,i,l;if(l=e,i=S(),i!==null)for(t=[];i!==null;)t.push(i),i=S();else t=null;return t!==null&&(t=function(h,f){M=parseInt(f.join(""))}(l,t)),t===null&&(e=l),t}function ho(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M=h}(i,t)),t===null&&(e=i),t}function Ct(){var t,i,l,h,f,v,I,q,j,Oe;for(q=e,j=e,t=[],i=Dr();i!==null;)t.push(i),i=Dr();if(t!==null)if(i=It(),i!==null)if(l=Tt(),l!==null)if(h=ht(),h!==null){for(f=[],Oe=e,v=Ue(),v!==null?(I=gt(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);v!==null;)f.push(v),Oe=e,v=Ue(),v!==null?(I=gt(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);f!==null?t=[t,i,l,h,f]:(t=null,e=j)}else t=null,e=j;else t=null,e=j;else t=null,e=j;else t=null,e=j;return t!==null&&(t=function(it){try{M=new Yn(M.uri,M.display_name,M.params)}catch{M=-1}}()),t===null&&(e=q),t}function Ft(){var t;return t=dr(),t}function dr(){var t,i,l,h,f,v,I,q;if(I=e,r.substr(e,6).toLowerCase()==="digest"?(t=r.substr(e,6),e+=6):(t=null,d('"Digest"')),t!==null)if(i=Ne(),i!==null)if(l=Gt(),l!==null){for(h=[],q=e,f=qe(),f!==null?(v=Gt(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);f!==null;)h.push(f),q=e,f=qe(),f!==null?(v=Gt(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t===null&&(t=vs()),t}function vs(){var t,i,l,h,f,v,I,q;if(I=e,t=J(),t!==null)if(i=Ne(),i!==null)if(l=Nt(),l!==null){for(h=[],q=e,f=qe(),f!==null?(v=Nt(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);f!==null;)h.push(f),q=e,f=qe(),f!==null?(v=Nt(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function Nt(){var t,i,l,h;return h=e,t=J(),t!==null?(i=se(),i!==null?(l=J(),l===null&&(l=_t()),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Gt(){var t;return t=Qe(),t===null&&(t=ni(),t===null&&(t=hr(),t===null&&(t=Zr(),t===null&&(t=le(),t===null&&(t=Ge(),t===null&&(t=Bi(),t===null&&(t=Nt()))))))),t}function Qe(){var t,i,l,h;return h=e,r.substr(e,5).toLowerCase()==="realm"?(t=r.substr(e,5),e+=5):(t=null,d('"realm"')),t!==null?(i=se(),i!==null?(l=Ut(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ut(){var t,i;return i=e,t=mt(),t!==null&&(t=function(l,h){M.realm=h}(i,t)),t===null&&(e=i),t}function ni(){var t,i,l,h,f,v,I,q,j;if(q=e,r.substr(e,6).toLowerCase()==="domain"?(t=r.substr(e,6),e+=6):(t=null,d('"domain"')),t!==null)if(i=se(),i!==null)if(l=Yt(),l!==null)if(h=Kn(),h!==null){if(f=[],j=e,I=K(),I!==null)for(v=[];I!==null;)v.push(I),I=K();else v=null;for(v!==null?(I=Kn(),I!==null?v=[v,I]:(v=null,e=j)):(v=null,e=j);v!==null;){if(f.push(v),j=e,I=K(),I!==null)for(v=[];I!==null;)v.push(I),I=K();else v=null;v!==null?(I=Kn(),I!==null?v=[v,I]:(v=null,e=j)):(v=null,e=j)}f!==null?(v=Xe(),v!==null?t=[t,i,l,h,f,v]:(t=null,e=q)):(t=null,e=q)}else t=null,e=q;else t=null,e=q;else t=null,e=q;else t=null,e=q;return t}function Kn(){var t;return t=yn(),t===null&&(t=yr()),t}function hr(){var t,i,l,h;return h=e,r.substr(e,5).toLowerCase()==="nonce"?(t=r.substr(e,5),e+=5):(t=null,d('"nonce"')),t!==null?(i=se(),i!==null?(l=Ke(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ke(){var t,i;return i=e,t=mt(),t!==null&&(t=function(l,h){M.nonce=h}(i,t)),t===null&&(e=i),t}function Zr(){var t,i,l,h,f;return h=e,f=e,r.substr(e,6).toLowerCase()==="opaque"?(t=r.substr(e,6),e+=6):(t=null,d('"opaque"')),t!==null?(i=se(),i!==null?(l=mt(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.opaque=I}(h,t[2])),t===null&&(e=h),t}function le(){var t,i,l,h,f;return h=e,r.substr(e,5).toLowerCase()==="stale"?(t=r.substr(e,5),e+=5):(t=null,d('"stale"')),t!==null?(i=se(),i!==null?(f=e,r.substr(e,4).toLowerCase()==="true"?(l=r.substr(e,4),e+=4):(l=null,d('"true"')),l!==null&&(l=function(v){M.stale=!0}()),l===null&&(e=f),l===null&&(f=e,r.substr(e,5).toLowerCase()==="false"?(l=r.substr(e,5),e+=5):(l=null,d('"false"')),l!==null&&(l=function(v){M.stale=!1}()),l===null&&(e=f)),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Ge(){var t,i,l,h,f;return h=e,f=e,r.substr(e,9).toLowerCase()==="algorithm"?(t=r.substr(e,9),e+=9):(t=null,d('"algorithm"')),t!==null?(i=se(),i!==null?(r.substr(e,3).toLowerCase()==="md5"?(l=r.substr(e,3),e+=3):(l=null,d('"MD5"')),l===null&&(r.substr(e,8).toLowerCase()==="md5-sess"?(l=r.substr(e,8),e+=8):(l=null,d('"MD5-sess"')),l===null&&(l=J())),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.algorithm=I.toUpperCase()}(h,t[2])),t===null&&(e=h),t}function Bi(){var t,i,l,h,f,v,I,q,j,Oe;if(q=e,r.substr(e,3).toLowerCase()==="qop"?(t=r.substr(e,3),e+=3):(t=null,d('"qop"')),t!==null)if(i=se(),i!==null)if(l=Yt(),l!==null){if(j=e,h=Er(),h!==null){for(f=[],Oe=e,r.charCodeAt(e)===44?(v=",",e++):(v=null,d('","')),v!==null?(I=Er(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);v!==null;)f.push(v),Oe=e,r.charCodeAt(e)===44?(v=",",e++):(v=null,d('","')),v!==null?(I=Er(),I!==null?v=[v,I]:(v=null,e=Oe)):(v=null,e=Oe);f!==null?h=[h,f]:(h=null,e=j)}else h=null,e=j;h!==null?(f=Xe(),f!==null?t=[t,i,l,h,f]:(t=null,e=q)):(t=null,e=q)}else t=null,e=q;else t=null,e=q;else t=null,e=q;return t}function Er(){var t,i;return i=e,r.substr(e,8).toLowerCase()==="auth-int"?(t=r.substr(e,8),e+=8):(t=null,d('"auth-int"')),t===null&&(r.substr(e,4).toLowerCase()==="auth"?(t=r.substr(e,4),e+=4):(t=null,d('"auth"')),t===null&&(t=J())),t!==null&&(t=function(l,h){M.qop||(M.qop=[]),M.qop.push(h.toLowerCase())}(i,t)),t===null&&(e=i),t}function po(){var t,i,l,h,f,v;if(f=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function _o(){var t,i,l,h,f,v,I;if(f=e,v=e,t=at(),t!==null){for(i=[],I=e,l=qe(),l!==null?(h=at(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=qe(),l!==null?(h=at(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j,Oe;for(Oe=M.multi_header.length,j=0;j<Oe;j++)if(M.multi_header[j].parsed===null){M=null;break}M!==null?M=M.multi_header:M=-1}()),t===null&&(e=f),t}function at(){var t,i,l,h,f,v,I;if(f=e,v=e,t=fn(),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j;M.multi_header||(M.multi_header=[]);try{j=new Yn(M.uri,M.display_name,M.params),delete M.uri,delete M.display_name,delete M.params}catch{j=null}M.multi_header.push({possition:e,offset:q,parsed:j})}(f)),t===null&&(e=f),t}function fo(){var t,i,l,h,f,v,I;if(f=e,v=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t===null&&(t=J()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=es(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=es(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q,j){if(M.protocol=j.toLowerCase(),M.params||(M.params={}),M.params.text&&M.params.text[0]==='"'){var Oe=M.params.text;M.text=Oe.substring(1,Oe.length-1),delete M.params.text}}(f,t[0])),t===null&&(e=f),t}function es(){var t;return t=Vi(),t===null&&(t=gt()),t}function Vi(){var t,i,l,h,f,v;if(f=e,v=e,r.substr(e,5).toLowerCase()==="cause"?(t=r.substr(e,5),e+=5):(t=null,d('"cause"')),t!==null)if(i=se(),i!==null){if(h=S(),h!==null)for(l=[];h!==null;)l.push(h),h=S();else l=null;l!==null?t=[t,i,l]:(t=null,e=v)}else t=null,e=v;else t=null,e=v;return t!==null&&(t=function(I,q){M.cause=parseInt(q.join(""))}(f,t[2])),t===null&&(e=f),t}function mo(){var t,i,l,h,f,v;if(f=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function go(){var t,i,l,h,f,v;if(f=e,t=Mr(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=Mr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=Mr(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Mr(){var t,i,l,h,f,v;if(f=e,t=fn(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Ln(){var t,i,l,h,f,v;if(f=e,t=ji(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Ts(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Ts(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function ji(){var t,i;return i=e,r.substr(e,6).toLowerCase()==="active"?(t=r.substr(e,6),e+=6):(t=null,d('"active"')),t===null&&(r.substr(e,7).toLowerCase()==="pending"?(t=r.substr(e,7),e+=7):(t=null,d('"pending"')),t===null&&(r.substr(e,10).toLowerCase()==="terminated"?(t=r.substr(e,10),e+=10):(t=null,d('"terminated"')),t===null&&(t=J()))),t!==null&&(t=function(l){M.state=r.substring(e,l)}(i)),t===null&&(e=i),t}function Ts(){var t,i,l,h,f;return h=e,f=e,r.substr(e,6).toLowerCase()==="reason"?(t=r.substr(e,6),e+=6):(t=null,d('"reason"')),t!==null?(i=se(),i!==null?(l=pr(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){typeof I<"u"&&(M.reason=I)}(h,t[2])),t===null&&(e=h),t===null&&(h=e,f=e,r.substr(e,7).toLowerCase()==="expires"?(t=r.substr(e,7),e+=7):(t=null,d('"expires"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){typeof I<"u"&&(M.expires=I)}(h,t[2])),t===null&&(e=h),t===null&&(h=e,f=e,r.substr(e,11).toLowerCase()==="retry_after"?(t=r.substr(e,11),e+=11):(t=null,d('"retry_after"')),t!==null?(i=se(),i!==null?(l=vn(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){typeof I<"u"&&(M.retry_after=I)}(h,t[2])),t===null&&(e=h),t===null&&(t=gt()))),t}function pr(){var t;return r.substr(e,11).toLowerCase()==="deactivated"?(t=r.substr(e,11),e+=11):(t=null,d('"deactivated"')),t===null&&(r.substr(e,9).toLowerCase()==="probation"?(t=r.substr(e,9),e+=9):(t=null,d('"probation"')),t===null&&(r.substr(e,8).toLowerCase()==="rejected"?(t=r.substr(e,8),e+=8):(t=null,d('"rejected"')),t===null&&(r.substr(e,7).toLowerCase()==="timeout"?(t=r.substr(e,7),e+=7):(t=null,d('"timeout"')),t===null&&(r.substr(e,6).toLowerCase()==="giveup"?(t=r.substr(e,6),e+=6):(t=null,d('"giveup"')),t===null&&(r.substr(e,10).toLowerCase()==="noresource"?(t=r.substr(e,10),e+=10):(t=null,d('"noresource"')),t===null&&(r.substr(e,9).toLowerCase()==="invariant"?(t=r.substr(e,9),e+=9):(t=null,d('"invariant"')),t===null&&(t=J()))))))),t}function yo(){var t;return t=me(),t=t!==null?t:"",t}function vo(){var t,i,l,h,f,v;if(f=e,t=J(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=J(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t=t!==null?t:"",t}function To(){var t,i,l,h,f,v,I;if(f=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=bs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=bs(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){var j=M.tag;try{M=new Yn(M.uri,M.display_name,M.params),j&&M.setParam("tag",j)}catch{M=-1}}()),t===null&&(e=f),t}function bs(){var t;return t=ys(),t===null&&(t=gt()),t}function bo(){var t,i,l,h,f,v;if(f=e,t=Ur(),t!==null){for(i=[],v=e,l=qe(),l!==null?(h=Ur(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=qe(),l!==null?(h=Ur(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Ur(){var t,i,l,h,f,v,I,q;if(I=e,t=Ji(),t!==null)if(i=Ne(),i!==null)if(l=ea(),l!==null){for(h=[],q=e,f=Ue(),f!==null?(v=ws(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);f!==null;)h.push(f),q=e,f=Ue(),f!==null?(v=ws(),v!==null?f=[f,v]:(f=null,e=q)):(f=null,e=q);h!==null?t=[t,i,l,h]:(t=null,e=I)}else t=null,e=I;else t=null,e=I;else t=null,e=I;return t}function ws(){var t;return t=Gi(),t===null&&(t=Wi(),t===null&&(t=Ki(),t===null&&(t=qn(),t===null&&(t=Yi(),t===null&&(t=gt()))))),t}function Gi(){var t,i,l,h,f;return h=e,f=e,r.substr(e,3).toLowerCase()==="ttl"?(t=r.substr(e,3),e+=3):(t=null,d('"ttl"')),t!==null?(i=se(),i!==null?(l=Ss(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.ttl=I}(h,t[2])),t===null&&(e=h),t}function Wi(){var t,i,l,h,f;return h=e,f=e,r.substr(e,5).toLowerCase()==="maddr"?(t=r.substr(e,5),e+=5):(t=null,d('"maddr"')),t!==null?(i=se(),i!==null?(l=ar(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.maddr=I}(h,t[2])),t===null&&(e=h),t}function Ki(){var t,i,l,h,f;return h=e,f=e,r.substr(e,8).toLowerCase()==="received"?(t=r.substr(e,8),e+=8):(t=null,d('"received"')),t!==null?(i=se(),i!==null?(l=or(),l===null&&(l=Kr()),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.received=I}(h,t[2])),t===null&&(e=h),t}function qn(){var t,i,l,h,f;return h=e,f=e,r.substr(e,6).toLowerCase()==="branch"?(t=r.substr(e,6),e+=6):(t=null,d('"branch"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.branch=I}(h,t[2])),t===null&&(e=h),t}function Yi(){var t,i,l,h,f;return h=e,r.substr(e,5).toLowerCase()==="rport"?(t=r.substr(e,5),e+=5):(t=null,d('"rport"')),t!==null?(f=e,i=se(),i!==null?(l=Xi(),l!==null?i=[i,l]:(i=null,e=f)):(i=null,e=f),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function Xi(){var t,i,l,h,f,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(f=S(),f=f!==null?f:"",f!==null?t=[t,i,l,h,f]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){M.rport=parseInt(j.join(""))}(v,t)),t===null&&(e=v),t}function Ji(){var t,i,l,h,f,v;return v=e,t=Qi(),t!==null?(i=fe(),i!==null?(l=J(),l!==null?(h=fe(),h!==null?(f=Zi(),f!==null?t=[t,i,l,h,f]:(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v)):(t=null,e=v),t}function Qi(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="sip"?(t=r.substr(e,3),e+=3):(t=null,d('"SIP"')),t===null&&(t=J()),t!==null&&(t=function(l,h){M.protocol=h}(i,t)),t===null&&(e=i),t}function Zi(){var t,i;return i=e,r.substr(e,3).toLowerCase()==="udp"?(t=r.substr(e,3),e+=3):(t=null,d('"UDP"')),t===null&&(r.substr(e,3).toLowerCase()==="tcp"?(t=r.substr(e,3),e+=3):(t=null,d('"TCP"')),t===null&&(r.substr(e,3).toLowerCase()==="tls"?(t=r.substr(e,3),e+=3):(t=null,d('"TLS"')),t===null&&(r.substr(e,4).toLowerCase()==="sctp"?(t=r.substr(e,4),e+=4):(t=null,d('"SCTP"')),t===null&&(t=J())))),t!==null&&(t=function(l,h){M.transport=h}(i,t)),t===null&&(e=i),t}function ea(){var t,i,l,h,f;return h=e,t=ta(),t!==null?(f=e,i=wt(),i!==null?(l=na(),l!==null?i=[i,l]:(i=null,e=f)):(i=null,e=f),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=h)):(t=null,e=h),t}function ta(){var t,i;return i=e,t=or(),t===null&&(t=Wr(),t===null&&(t=_n())),t!==null&&(t=function(l){M.host=r.substring(e,l)}(i)),t===null&&(e=i),t}function na(){var t,i,l,h,f,v,I;return v=e,I=e,t=S(),t=t!==null?t:"",t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?(h=S(),h=h!==null?h:"",h!==null?(f=S(),f=f!==null?f:"",f!==null?t=[t,i,l,h,f]:(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I)):(t=null,e=I),t!==null&&(t=function(q,j){M.port=parseInt(j.join(""))}(v,t)),t===null&&(e=v),t}function Ss(){var t,i,l,h,f;return h=e,f=e,t=S(),t!==null?(i=S(),i=i!==null?i:"",i!==null?(l=S(),l=l!==null?l:"",l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){return parseInt(I.join(""))}(h,t)),t===null&&(e=h),t}function wo(){var t;return t=dr(),t}function Cl(){var t,i,l,h,f,v;if(f=e,t=Hn(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=Es(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=Es(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function Hn(){var t,i;return i=e,t=vn(),t!==null&&(t=function(l,h){M.expires=h}(i,t)),t===null&&(e=i),t}function Es(){var t;return t=Cs(),t===null&&(t=gt()),t}function Cs(){var t,i,l,h,f;return h=e,f=e,r.substr(e,9).toLowerCase()==="refresher"?(t=r.substr(e,9),e+=9):(t=null,d('"refresher"')),t!==null?(i=se(),i!==null?(r.substr(e,3).toLowerCase()==="uac"?(l=r.substr(e,3),e+=3):(l=null,d('"uac"')),l===null&&(r.substr(e,3).toLowerCase()==="uas"?(l=r.substr(e,3),e+=3):(l=null,d('"uas"'))),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.refresher=I.toLowerCase()}(h,t[2])),t===null&&(e=h),t}function Ua(){var t,i,l,h;return h=e,t=J(),t!==null?(i=ce(),i!==null?(l=zn(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function zn(){var t,i;for(t=[],i=_e(),i===null&&(i=ye(),i===null&&(i=Ne()));i!==null;)t.push(i),i=_e(),i===null&&(i=ye(),i===null&&(i=Ne()));return t}function So(){var t,i;for(t=[],i=W();i!==null;)t.push(i),i=W();return t}function Eo(){var t,i,l;return l=e,r.substr(e,5)==="uuid:"?(t="uuid:",e+=5):(t=null,d('"uuid:"')),t!==null?(i=ra(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function ra(){var t,i,l,h,f,v,I,q,j,Oe,it;return Oe=e,it=e,t=sa(),t!==null?(r.charCodeAt(e)===45?(i="-",e++):(i=null,d('"-"')),i!==null?(l=sn(),l!==null?(r.charCodeAt(e)===45?(h="-",e++):(h=null,d('"-"')),h!==null?(f=sn(),f!==null?(r.charCodeAt(e)===45?(v="-",e++):(v=null,d('"-"')),v!==null?(I=sn(),I!==null?(r.charCodeAt(e)===45?(q="-",e++):(q=null,d('"-"')),q!==null?(j=ia(),j!==null?t=[t,i,l,h,f,v,I,q,j]:(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it)):(t=null,e=it),t!==null&&(t=function(an,Pr){M=r.substring(e+5,an)}(Oe,t[0])),t===null&&(e=Oe),t}function sn(){var t,i,l,h,f;return f=e,t=N(),t!==null?(i=N(),i!==null?(l=N(),l!==null?(h=N(),h!==null?t=[t,i,l,h]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t}function sa(){var t,i,l;return l=e,t=sn(),t!==null?(i=sn(),i!==null?t=[t,i]:(t=null,e=l)):(t=null,e=l),t}function ia(){var t,i,l,h;return h=e,t=sn(),t!==null?(i=sn(),i!==null?(l=sn(),l!==null?t=[t,i,l]:(t=null,e=h)):(t=null,e=h)):(t=null,e=h),t}function Co(){var t,i,l,h,f,v,I;if(f=e,v=e,t=Ze(),t===null&&(t=fn()),t!==null){for(i=[],I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);l!==null;)i.push(l),I=e,l=Ue(),l!==null?(h=gt(),h!==null?l=[l,h]:(l=null,e=I)):(l=null,e=I);i!==null?t=[t,i]:(t=null,e=v)}else t=null,e=v;return t!==null&&(t=function(q){try{M=new Yn(M.uri,M.display_name,M.params)}catch{M=-1}}()),t===null&&(e=f),t}function Ao(){var t,i,l,h,f,v;if(f=e,t=aa(),t!==null){for(i=[],v=e,l=Ue(),l!==null?(h=As(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);l!==null;)i.push(l),v=e,l=Ue(),l!==null?(h=As(),h!==null?l=[l,h]:(l=null,e=v)):(l=null,e=v);i!==null?t=[t,i]:(t=null,e=f)}else t=null,e=f;return t}function aa(){var t,i,l,h,f,v;return h=e,f=e,t=zt(),t!==null?(v=e,r.charCodeAt(e)===64?(i="@",e++):(i=null,d('"@"')),i!==null?(l=zt(),l!==null?i=[i,l]:(i=null,e=v)):(i=null,e=v),i=i!==null?i:"",i!==null?t=[t,i]:(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(I){M.call_id=r.substring(e,I)}(h)),t===null&&(e=h),t}function As(){var t;return t=Fn(),t===null&&(t=oa(),t===null&&(t=la(),t===null&&(t=gt()))),t}function Fn(){var t,i,l,h,f;return h=e,f=e,r.substr(e,6)==="to-tag"?(t="to-tag",e+=6):(t=null,d('"to-tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.to_tag=I}(h,t[2])),t===null&&(e=h),t}function oa(){var t,i,l,h,f;return h=e,f=e,r.substr(e,8)==="from-tag"?(t="from-tag",e+=8):(t=null,d('"from-tag"')),t!==null?(i=se(),i!==null?(l=J(),l!==null?t=[t,i,l]:(t=null,e=f)):(t=null,e=f)):(t=null,e=f),t!==null&&(t=function(v,I){M.from_tag=I}(h,t[2])),t===null&&(e=h),t}function la(){var t,i;return i=e,r.substr(e,10)==="early-only"?(t="early-only",e+=10):(t=null,d('"early-only"')),t!==null&&(t=function(l){M.early_only=!0}()),t===null&&(e=i),t}function Io(t){t.sort();for(var i=null,l=[],h=0;h<t.length;h++)t[h]!==i&&(l.push(t[h]),i=t[h]);return l}function Ro(){for(var t=1,i=1,l=!1,h=0;h<Math.max(e,_);h++){var f=r.charAt(h);f===`
|
|
75
|
+
`?(l||t++,i=1,l=!1):f==="\r"||f==="\u2028"||f==="\u2029"?(t++,i=1,l=!0):(i++,l=!1)}return{line:t,column:i}}var ua=Ms(),Yn=ed(),M={},$o=c[a]();if($o===null||e!==r.length){var Is=Math.max(e,_),xo=Is<r.length?r.charAt(Is):null,ri=Ro();return new this.SyntaxError(Io(g),xo,Is,ri.line,ri.column),-1}return M},toSource:function(){return this._source}};return n.SyntaxError=function(r,a,c,e,_){function g(d,A){var S,R;switch(d.length){case 0:S="end of input";break;case 1:S=d[0];break;default:S=d.slice(0,d.length-1).join(", ")+" or "+d[d.length-1]}return R=A?o(A):"end of input","Expected "+S+" but "+R+" found."}this.name="SyntaxError",this.expected=r,this.found=a,this.message=g(r,a),this.offset=c,this.line=e,this.column=_},n.SyntaxError.prototype=Error.prototype,n}()),E_}var td,A_;function Ms(){if(A_)return td;A_=1;const o=bt,n=$n(),r=Hr();return td=class gb{static parse(c){if(c=r.parse(c,"SIP_URI"),c!==-1)return c}constructor(c,e,_,g,d={},A={}){if(!_)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=c||o.SIP,this._user=e,this._host=_,this._port=g;for(const S in d)Object.prototype.hasOwnProperty.call(d,S)&&this.setParam(S,d[S]);for(const S in A)Object.prototype.hasOwnProperty.call(A,S)&&this.setHeader(S,A[S])}get scheme(){return this._scheme}set scheme(c){this._scheme=c.toLowerCase()}get user(){return this._user}set user(c){this._user=c}get host(){return this._host}set host(c){this._host=c.toLowerCase()}get port(){return this._port}set port(c){this._port=c===0?c:parseInt(c,10)||null}setParam(c,e){c&&(this._parameters[c.toLowerCase()]=typeof e>"u"||e===null?null:e.toString())}getParam(c){if(c)return this._parameters[c.toLowerCase()]}hasParam(c){if(c)return this._parameters.hasOwnProperty(c.toLowerCase())&&!0||!1}deleteParam(c){if(c=c.toLowerCase(),this._parameters.hasOwnProperty(c)){const e=this._parameters[c];return delete this._parameters[c],e}}clearParams(){this._parameters={}}setHeader(c,e){this._headers[n.headerize(c)]=Array.isArray(e)?e:[e]}getHeader(c){if(c)return this._headers[n.headerize(c)]}hasHeader(c){if(c)return this._headers.hasOwnProperty(n.headerize(c))&&!0||!1}deleteHeader(c){if(c=n.headerize(c),this._headers.hasOwnProperty(c)){const e=this._headers[c];return delete this._headers[c],e}}clearHeaders(){this._headers={}}clone(){return new gb(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}toString(){const c=[];let e=`${this._scheme}:`;this._user&&(e+=`${n.escapeUser(this._user)}@`),e+=this._host,(this._port||this._port===0)&&(e+=`:${this._port}`);for(const _ in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,_)&&(e+=`;${_}`,this._parameters[_]!==null&&(e+=`=${this._parameters[_]}`));for(const _ in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,_))for(const g of this._headers[_])c.push(`${_}=${g}`);return c.length>0&&(e+=`?${c.join("&")}`),e}toAor(c){let e=`${this._scheme}:`;return this._user&&(e+=`${n.escapeUser(this._user)}@`),e+=this._host,c&&(this._port||this._port===0)&&(e+=`:${this._port}`),e}},td}var I_;function $n(){if(I_)return ln;I_=1;const o=bt,n=Ms(),r=Hr();ln.str_utf8_length=_=>unescape(encodeURIComponent(_)).length;const a=ln.isFunction=_=>_!==void 0?Object.prototype.toString.call(_)==="[object Function]":!1;ln.isString=_=>_!==void 0?Object.prototype.toString.call(_)==="[object String]":!1,ln.isDecimal=_=>!isNaN(_)&&parseFloat(_)===parseInt(_,10),ln.isEmpty=_=>_===null||_===""||_===void 0||Array.isArray(_)&&_.length===0||typeof _=="number"&&isNaN(_),ln.hasMethods=function(_,...g){for(const d of g)if(a(_[d]))return!1;return!0};const c=ln.createRandomToken=(_,g=32)=>{let d,A,S="";for(d=0;d<_;d++)A=Math.random()*g|0,S+=A.toString(g);return S};ln.newTag=()=>c(10),ln.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,_=>{const g=Math.random()*16|0;return(_==="x"?g:g&3|8).toString(16)}),ln.hostType=_=>{if(_){if(_=r.parse(_,"host"),_!==-1)return _.host_type}else return};const e=ln.escapeUser=_=>encodeURIComponent(decodeURIComponent(_)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/");return ln.normalizeTarget=(_,g)=>{if(_){if(_ instanceof n)return _;if(typeof _=="string"){const d=_.split("@");let A,S;switch(d.length){case 1:if(!g)return;A=_,S=g;break;case 2:A=d[0],S=d[1];break;default:A=d.slice(0,d.length-1).join("@"),S=d[d.length-1]}A=A.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(A)&&(A=A.replace(/[-.()]/g,"")),_=`${o.SIP}:${e(A)}@${S}`;let R;return(R=n.parse(_))?R:void 0}else return}else return},ln.headerize=_=>{const g={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},d=_.toLowerCase().replace(/_/g,"-").split("-");let A="";const S=d.length;let R;for(R=0;R<S;R++)R!==0&&(A+="-"),A+=d[R].charAt(0).toUpperCase()+d[R].substring(1);return g[A]&&(A=g[A]),A},ln.sipErrorCause=_=>{for(const g in o.SIP_ERROR_CAUSES)if(o.SIP_ERROR_CAUSES[g].indexOf(_)!==-1)return o.causes[g];return o.causes.SIP_FAILURE_CODE},ln.getRandomTestNetIP=()=>{function _(g,d){return Math.floor(Math.random()*(d-g+1)+g)}return`192.0.2.${_(1,254)}`},ln.calculateMD5=_=>{function g(Xe,Je){return Xe<<Je|Xe>>>32-Je}function d(Xe,Je){const ut=Xe&2147483648,_t=Je&2147483648,mt=Xe&1073741824,Le=Je&1073741824,Pe=(Xe&1073741823)+(Je&1073741823);return mt&Le?Pe^2147483648^ut^_t:mt|Le?Pe&1073741824?Pe^3221225472^ut^_t:Pe^1073741824^ut^_t:Pe^ut^_t}function A(Xe,Je,ut){return Xe&Je|~Xe&ut}function S(Xe,Je,ut){return Xe&ut|Je&~ut}function R(Xe,Je,ut){return Xe^Je^ut}function N(Xe,Je,ut){return Je^(Xe|~ut)}function H(Xe,Je,ut,_t,mt,Le,Pe){return Xe=d(Xe,d(d(A(Je,ut,_t),mt),Pe)),d(g(Xe,Le),Je)}function W(Xe,Je,ut,_t,mt,Le,Pe){return Xe=d(Xe,d(d(S(Je,ut,_t),mt),Pe)),d(g(Xe,Le),Je)}function G(Xe,Je,ut,_t,mt,Le,Pe){return Xe=d(Xe,d(d(R(Je,ut,_t),mt),Pe)),d(g(Xe,Le),Je)}function K(Xe,Je,ut,_t,mt,Le,Pe){return Xe=d(Xe,d(d(N(Je,ut,_t),mt),Pe)),d(g(Xe,Le),Je)}function ae(Xe){let Je;const ut=Xe.length,_t=ut+8,mt=((_t-_t%64)/64+1)*16,Le=new Array(mt-1);let Pe=0,Ze=0;for(;Ze<ut;)Je=(Ze-Ze%4)/4,Pe=Ze%4*8,Le[Je]=Le[Je]|Xe.charCodeAt(Ze)<<Pe,Ze++;return Je=(Ze-Ze%4)/4,Pe=Ze%4*8,Le[Je]=Le[Je]|128<<Pe,Le[mt-2]=ut<<3,Le[mt-1]=ut>>>29,Le}function ee(Xe){let Je="",ut="",_t,mt;for(mt=0;mt<=3;mt++)_t=Xe>>>mt*8&255,ut=`0${_t.toString(16)}`,Je=Je+ut.substr(ut.length-2,2);return Je}function De(Xe){let Je="";for(let ut=0;ut<Xe.length;ut++){const _t=Xe.charCodeAt(ut);_t<128?Je+=String.fromCharCode(_t):_t>127&&_t<2048?(Je+=String.fromCharCode(_t>>6|192),Je+=String.fromCharCode(_t&63|128)):(Je+=String.fromCharCode(_t>>12|224),Je+=String.fromCharCode(_t>>6&63|128),Je+=String.fromCharCode(_t&63|128))}return Je}let X=[],re,be,Ne,Q,ce,me,_e,ue,ye;const Re=7,J=12,Se=17,$e=22,zt=5,Ae=9,fe=14,se=20,st=4,We=11,ht=16,It=23,qe=6,Ue=10,wt=15,Yt=21;for(_=De(_),X=ae(_),me=1732584193,_e=4023233417,ue=2562383102,ye=271733878,re=0;re<X.length;re+=16)be=me,Ne=_e,Q=ue,ce=ye,me=H(me,_e,ue,ye,X[re+0],Re,3614090360),ye=H(ye,me,_e,ue,X[re+1],J,3905402710),ue=H(ue,ye,me,_e,X[re+2],Se,606105819),_e=H(_e,ue,ye,me,X[re+3],$e,3250441966),me=H(me,_e,ue,ye,X[re+4],Re,4118548399),ye=H(ye,me,_e,ue,X[re+5],J,1200080426),ue=H(ue,ye,me,_e,X[re+6],Se,2821735955),_e=H(_e,ue,ye,me,X[re+7],$e,4249261313),me=H(me,_e,ue,ye,X[re+8],Re,1770035416),ye=H(ye,me,_e,ue,X[re+9],J,2336552879),ue=H(ue,ye,me,_e,X[re+10],Se,4294925233),_e=H(_e,ue,ye,me,X[re+11],$e,2304563134),me=H(me,_e,ue,ye,X[re+12],Re,1804603682),ye=H(ye,me,_e,ue,X[re+13],J,4254626195),ue=H(ue,ye,me,_e,X[re+14],Se,2792965006),_e=H(_e,ue,ye,me,X[re+15],$e,1236535329),me=W(me,_e,ue,ye,X[re+1],zt,4129170786),ye=W(ye,me,_e,ue,X[re+6],Ae,3225465664),ue=W(ue,ye,me,_e,X[re+11],fe,643717713),_e=W(_e,ue,ye,me,X[re+0],se,3921069994),me=W(me,_e,ue,ye,X[re+5],zt,3593408605),ye=W(ye,me,_e,ue,X[re+10],Ae,38016083),ue=W(ue,ye,me,_e,X[re+15],fe,3634488961),_e=W(_e,ue,ye,me,X[re+4],se,3889429448),me=W(me,_e,ue,ye,X[re+9],zt,568446438),ye=W(ye,me,_e,ue,X[re+14],Ae,3275163606),ue=W(ue,ye,me,_e,X[re+3],fe,4107603335),_e=W(_e,ue,ye,me,X[re+8],se,1163531501),me=W(me,_e,ue,ye,X[re+13],zt,2850285829),ye=W(ye,me,_e,ue,X[re+2],Ae,4243563512),ue=W(ue,ye,me,_e,X[re+7],fe,1735328473),_e=W(_e,ue,ye,me,X[re+12],se,2368359562),me=G(me,_e,ue,ye,X[re+5],st,4294588738),ye=G(ye,me,_e,ue,X[re+8],We,2272392833),ue=G(ue,ye,me,_e,X[re+11],ht,1839030562),_e=G(_e,ue,ye,me,X[re+14],It,4259657740),me=G(me,_e,ue,ye,X[re+1],st,2763975236),ye=G(ye,me,_e,ue,X[re+4],We,1272893353),ue=G(ue,ye,me,_e,X[re+7],ht,4139469664),_e=G(_e,ue,ye,me,X[re+10],It,3200236656),me=G(me,_e,ue,ye,X[re+13],st,681279174),ye=G(ye,me,_e,ue,X[re+0],We,3936430074),ue=G(ue,ye,me,_e,X[re+3],ht,3572445317),_e=G(_e,ue,ye,me,X[re+6],It,76029189),me=G(me,_e,ue,ye,X[re+9],st,3654602809),ye=G(ye,me,_e,ue,X[re+12],We,3873151461),ue=G(ue,ye,me,_e,X[re+15],ht,530742520),_e=G(_e,ue,ye,me,X[re+2],It,3299628645),me=K(me,_e,ue,ye,X[re+0],qe,4096336452),ye=K(ye,me,_e,ue,X[re+7],Ue,1126891415),ue=K(ue,ye,me,_e,X[re+14],wt,2878612391),_e=K(_e,ue,ye,me,X[re+5],Yt,4237533241),me=K(me,_e,ue,ye,X[re+12],qe,1700485571),ye=K(ye,me,_e,ue,X[re+3],Ue,2399980690),ue=K(ue,ye,me,_e,X[re+10],wt,4293915773),_e=K(_e,ue,ye,me,X[re+1],Yt,2240044497),me=K(me,_e,ue,ye,X[re+8],qe,1873313359),ye=K(ye,me,_e,ue,X[re+15],Ue,4264355552),ue=K(ue,ye,me,_e,X[re+6],wt,2734768916),_e=K(_e,ue,ye,me,X[re+13],Yt,1309151649),me=K(me,_e,ue,ye,X[re+4],qe,4149444226),ye=K(ye,me,_e,ue,X[re+11],Ue,3174756917),ue=K(ue,ye,me,_e,X[re+2],wt,718787259),_e=K(_e,ue,ye,me,X[re+9],Yt,3951481745),me=d(me,be),_e=d(_e,Ne),ue=d(ue,Q),ye=d(ye,ce);return(ee(me)+ee(_e)+ee(ue)+ee(ye)).toLowerCase()},ln.closeMediaStream=_=>{if(_)try{let g;if(_.getTracks){g=_.getTracks();for(const d of g)d.stop()}else{g=_.getAudioTracks();for(const d of g)d.stop();g=_.getVideoTracks();for(const d of g)d.stop()}}catch{(typeof _.stop=="function"||typeof _.stop=="object")&&_.stop()}},ln.cloneArray=_=>_&&_.slice()||[],ln.cloneObject=(_,g={})=>_&&Object.assign({},_)||g,ln}const R_=nr,EE=mn,xn=bt,pn=$n(),$_=ed(),CE=Hr(),nd=new EE("SIPMessage");class Su{constructor(n,r,a,c,e,_){if(!n||!r||!a)return null;c=c||{},this.ua=a,this.headers={},this.method=n,this.ruri=r,this.body=_,this.extraHeaders=pn.cloneArray(e),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),c.route_set?this.setHeader("route",c.route_set):a.configuration.use_preloaded_route&&this.setHeader("route",`<${a.transport.sip_uri};lr>`),this.setHeader("via",""),this.setHeader("max-forwards",xn.MAX_FORWARDS);const g=c.to_uri||r,d=c.to_tag?{tag:c.to_tag}:null,A=typeof c.to_display_name<"u"?c.to_display_name:null;this.to=new $_(g,A,d),this.setHeader("to",this.to.toString());const S=c.from_uri||a.configuration.uri,R={tag:c.from_tag||pn.newTag()};let N;typeof c.from_display_name<"u"?N=c.from_display_name:a.configuration.display_name?N=a.configuration.display_name:N=null,this.from=new $_(S,N,R),this.setHeader("from",this.from.toString());const H=c.call_id||a.configuration.jssip_id+pn.createRandomToken(15);this.call_id=H,this.setHeader("call-id",H);const W=c.cseq||Math.floor(Math.random()*1e4);this.cseq=W,this.setHeader("cseq",`${W} ${n}`)}setHeader(n,r){const a=new RegExp(`^\\s*${n}\\s*:`,"i");for(let c=0;c<this.extraHeaders.length;c++)a.test(this.extraHeaders[c])&&this.extraHeaders.splice(c,1);this.headers[pn.headerize(n)]=Array.isArray(r)?r:[r]}getHeader(n){const r=this.headers[pn.headerize(n)];if(r){if(r[0])return r[0]}else{const a=new RegExp(`^\\s*${n}\\s*:`,"i");for(const c of this.extraHeaders)if(a.test(c))return c.substring(c.indexOf(":")+1).trim()}}getHeaders(n){const r=this.headers[pn.headerize(n)],a=[];if(r){for(const c of r)a.push(c);return a}else{const c=new RegExp(`^\\s*${n}\\s*:`,"i");for(const e of this.extraHeaders)c.test(e)&&a.push(e.substring(e.indexOf(":")+1).trim());return a}}hasHeader(n){if(this.headers[pn.headerize(n)])return!0;{const r=new RegExp(`^\\s*${n}\\s*:`,"i");for(const a of this.extraHeaders)if(r.test(a))return!0}return!1}parseSDP(n){return!n&&this.sdp?this.sdp:(this.sdp=R_.parse(this.body||""),this.sdp)}toString(){let n=`${this.method} ${this.ruri} SIP/2.0\r
|
|
76
76
|
`;for(const c in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,c))for(const e of this.headers[c])n+=`${c}: ${e}\r
|
|
77
77
|
`;for(const c of this.extraHeaders)n+=`${c.trim()}\r
|
|
78
78
|
`;const r=[];switch(this.method){case xn.REGISTER:r.push("path","gruu");break;case xn.INVITE:this.ua.configuration.session_timers&&r.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&r.push("gruu"),r.push("ice","replaces");break;case xn.UPDATE:this.ua.configuration.session_timers&&r.push("timer"),r.push("ice");break}r.push("outbound");const a=this.ua.configuration.user_agent||xn.USER_AGENT;if(n+=`Allow: ${xn.ALLOWED_METHODS}\r
|
|
@@ -82,7 +82,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
82
82
|
\r
|
|
83
83
|
`,n+=this.body}else n+=`Content-Length: 0\r
|
|
84
84
|
\r
|
|
85
|
-
`;return n}clone(){const n=new Su(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){n.headers[r]=this.headers[r].slice()},this),n.body=this.body,n.extraHeaders=pn.cloneArray(this.extraHeaders),n.to=this.to,n.from=this.from,n.call_id=this.call_id,n.cseq=this.cseq,n}}class rd extends Su{constructor(n,r,a,c,e){super(xn.INVITE,n,r,a,c,e),this.transaction=null}cancel(n){this.transaction.cancel(n)}clone(){const n=new rd(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){n.headers[r]=this.headers[r].slice()},this),n.body=this.body,n.extraHeaders=pn.cloneArray(this.extraHeaders),n.to=this.to,n.from=this.from,n.call_id=this.call_id,n.cseq=this.cseq,n.transaction=this.transaction,n}}class x_{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(n,r){const a={raw:r};n=pn.headerize(n),this.headers[n]?this.headers[n].push(a):this.headers[n]=[a]}getHeader(n){const r=this.headers[pn.headerize(n)];if(r){if(r[0])return r[0].raw}else return}getHeaders(n){const r=this.headers[pn.headerize(n)],a=[];if(!r)return[];for(const c of r)a.push(c.raw);return a}hasHeader(n){return!!this.headers[pn.headerize(n)]}parseHeader(n,r=0){if(n=pn.headerize(n),this.headers[n]){if(r>=this.headers[n].length){nd.debug(`not so many "${n}" headers present`);return}}else{nd.debug(`header "${n}" not present`);return}const a=this.headers[n][r],c=a.raw;if(a.parsed)return a.parsed;const e=CE.parse(c,n.replace(/-/g,"_"));if(e===-1){this.headers[n].splice(r,1),nd.debug(`error parsing "${n}" header field with value "${c}"`);return}else return a.parsed=e,e}s(n,r){return this.parseHeader(n,r)}setHeader(n,r){const a={raw:r};this.headers[pn.headerize(n)]=[a]}parseSDP(n){return!n&&this.sdp?this.sdp:(this.sdp=R_.parse(this.body||""),this.sdp)}toString(){return this.data}}class AE extends x_{constructor(n){super(),this.ua=n,this.headers={},this.ruri=null,this.transport=null,this.server_transaction=null}reply(n,r,a,c,e,
|
|
85
|
+
`;return n}clone(){const n=new Su(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){n.headers[r]=this.headers[r].slice()},this),n.body=this.body,n.extraHeaders=pn.cloneArray(this.extraHeaders),n.to=this.to,n.from=this.from,n.call_id=this.call_id,n.cseq=this.cseq,n}}class rd extends Su{constructor(n,r,a,c,e){super(xn.INVITE,n,r,a,c,e),this.transaction=null}cancel(n){this.transaction.cancel(n)}clone(){const n=new rd(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){n.headers[r]=this.headers[r].slice()},this),n.body=this.body,n.extraHeaders=pn.cloneArray(this.extraHeaders),n.to=this.to,n.from=this.from,n.call_id=this.call_id,n.cseq=this.cseq,n.transaction=this.transaction,n}}class x_{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(n,r){const a={raw:r};n=pn.headerize(n),this.headers[n]?this.headers[n].push(a):this.headers[n]=[a]}getHeader(n){const r=this.headers[pn.headerize(n)];if(r){if(r[0])return r[0].raw}else return}getHeaders(n){const r=this.headers[pn.headerize(n)],a=[];if(!r)return[];for(const c of r)a.push(c.raw);return a}hasHeader(n){return!!this.headers[pn.headerize(n)]}parseHeader(n,r=0){if(n=pn.headerize(n),this.headers[n]){if(r>=this.headers[n].length){nd.debug(`not so many "${n}" headers present`);return}}else{nd.debug(`header "${n}" not present`);return}const a=this.headers[n][r],c=a.raw;if(a.parsed)return a.parsed;const e=CE.parse(c,n.replace(/-/g,"_"));if(e===-1){this.headers[n].splice(r,1),nd.debug(`error parsing "${n}" header field with value "${c}"`);return}else return a.parsed=e,e}s(n,r){return this.parseHeader(n,r)}setHeader(n,r){const a={raw:r};this.headers[pn.headerize(n)]=[a]}parseSDP(n){return!n&&this.sdp?this.sdp:(this.sdp=R_.parse(this.body||""),this.sdp)}toString(){return this.data}}class AE extends x_{constructor(n){super(),this.ua=n,this.headers={},this.ruri=null,this.transport=null,this.server_transaction=null}reply(n,r,a,c,e,_){const g=[];let d=this.getHeader("To");if(n=n||null,r=r||null,!n||n<100||n>699)throw new TypeError(`Invalid status_code: ${n}`);if(r&&typeof r!="string"&&!(r instanceof String))throw new TypeError(`Invalid reason_phrase: ${r}`);r=r||xn.REASON_PHRASE[n]||"",a=pn.cloneArray(a),this.ua.configuration.extra_headers&&(a=a.concat(this.ua.configuration.extra_headers));let A=`SIP/2.0 ${n} ${r}\r
|
|
86
86
|
`;if(this.method===xn.INVITE&&n>100&&n<=200){const R=this.getHeaders("record-route");for(const N of R)A+=`Record-Route: ${N}\r
|
|
87
87
|
`}const S=this.getHeaders("via");for(const R of S)A+=`Via: ${R}\r
|
|
88
88
|
`;!this.to_tag&&n>100?d+=`;tag=${pn.newTag()}`:this.to_tag&&!this.s("to").hasParam("tag")&&(d+=`;tag=${this.to_tag}`),A+=`To: ${d}\r
|
|
@@ -100,19 +100,19 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
100
100
|
\r
|
|
101
101
|
`,A+=c}else A+=`Content-Length: 0\r
|
|
102
102
|
\r
|
|
103
|
-
`;this.server_transaction.receiveResponse(n,A,e,
|
|
104
|
-
`;for(const
|
|
103
|
+
`;this.server_transaction.receiveResponse(n,A,e,_)}reply_sl(n=null,r=null){const a=this.getHeaders("via");if(!n||n<100||n>699)throw new TypeError(`Invalid status_code: ${n}`);if(r&&typeof r!="string"&&!(r instanceof String))throw new TypeError(`Invalid reason_phrase: ${r}`);r=r||xn.REASON_PHRASE[n]||"";let c=`SIP/2.0 ${n} ${r}\r
|
|
104
|
+
`;for(const _ of a)c+=`Via: ${_}\r
|
|
105
105
|
`;let e=this.getHeader("To");if(!this.to_tag&&n>100?e+=`;tag=${pn.newTag()}`:this.to_tag&&!this.s("to").hasParam("tag")&&(e+=`;tag=${this.to_tag}`),c+=`To: ${e}\r
|
|
106
106
|
`,c+=`From: ${this.getHeader("From")}\r
|
|
107
107
|
`,c+=`Call-ID: ${this.call_id}\r
|
|
108
108
|
`,c+=`CSeq: ${this.cseq} ${this.method}\r
|
|
109
|
-
`,this.ua.configuration.extra_headers)for(const
|
|
109
|
+
`,this.ua.configuration.extra_headers)for(const _ of this.ua.configuration.extra_headers)c+=`${_.trim()}\r
|
|
110
110
|
`;c+=`Content-Length: 0\r
|
|
111
111
|
\r
|
|
112
|
-
`,this.transport.send(c)}}class IE extends x_{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var On={OutgoingRequest:Su,InitialOutgoingInviteRequest:rd,IncomingRequest:AE,IncomingResponse:IE};const Za=Qt(On),RE=mn,Us=$n(),zr=new RE("DigestAuthentication");var O_=class{constructor(o){this._credentials=o,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(o){switch(o){case"realm":return this._realm;case"ha1":return this._ha1;default:zr.warn('get() | cannot get "%s" parameter',o);return}}authenticate({method:o,ruri:n,body:r},a,c=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 zr.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return zr.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return zr.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return zr.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return zr.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 zr.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=o,this._uri=n,this._cnonce=c||Us.createRandomToken(12),this._nc+=1;const e=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-e.length)+e,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=Us.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._ha1=this._credentials.ha1;let f,g;return this._qop==="auth"?(f=`${this._method}:${this._uri}`,g=Us.calculateMD5(f),zr.debug('authenticate() | using qop=auth [a2:"%s"]',f),this._response=Us.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${g}`)):this._qop==="auth-int"?(f=`${this._method}:${this._uri}:${Us.calculateMD5(r||"")}`,g=Us.calculateMD5(f),zr.debug('authenticate() | using qop=auth-int [a2:"%s"]',f),this._response=Us.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${g}`)):this._qop===null&&(f=`${this._method}:${this._uri}`,g=Us.calculateMD5(f),zr.debug('authenticate() | using qop=null [a2:"%s"]',f),this._response=Us.calculateMD5(`${this._ha1}:${this._nonce}:${g}`)),zr.debug("authenticate() | response generated"),!0}toString(){const o=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return o.push(`algorithm=${this._algorithm}`),o.push(`username="${this._credentials.username}"`),o.push(`realm="${this._realm}"`),o.push(`nonce="${this._nonce}"`),o.push(`uri="${this._uri}"`),o.push(`response="${this._response}"`),this._opaque&&o.push(`opaque="${this._opaque}"`),this._qop&&(o.push(`qop=${this._qop}`),o.push(`cnonce="${this._cnonce}"`),o.push(`nc=${this._ncHex}`)),`Digest ${o.join(", ")}`}};const $E=Qt(O_),Ps=500,xE=4e3,k_=5e3;var sd={T1:Ps,T2:xE,T4:k_,TIMER_B:64*Ps,TIMER_D:0*Ps,TIMER_F:64*Ps,TIMER_H:64*Ps,TIMER_I:0*Ps,TIMER_J:0*Ps,TIMER_K:0*k_,TIMER_L:64*Ps,TIMER_M:64*Ps,PROVISIONAL_RESPONSE_INTERVAL:6e4};const el=Qt(sd),tl=Tn.EventEmitter,nl=mn,rl=bt,D_=On,os=sd,N_=new nl("NonInviteClientTransaction"),Eu=new nl("InviteClientTransaction"),OE=new nl("AckClientTransaction"),M_=new nl("NonInviteServerTransaction"),Cu=new nl("InviteServerTransaction"),Be={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 kE extends tl{constructor(n,r,a,c){super(),this.type=Be.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=n,this.transport=r,this.request=a,this.eventHandlers=c;let e=`SIP/2.0/${r.via_transport}`;e+=` ${n.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",e),this.ua.newTransaction(this)}get C(){return Be}stateChanged(n){this.state=n,this.emit("stateChanged")}send(){this.stateChanged(Be.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},os.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){N_.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){N_.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(n){const r=n.status_code;if(r<200)switch(this.state){case Be.STATUS_TRYING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(n);break}else switch(this.state){case Be.STATUS_TRYING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_COMPLETED),clearTimeout(this.F),r===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(n),this.K=setTimeout(()=>{this.timer_K()},os.TIMER_K);break;case Be.STATUS_COMPLETED:break}}}class DE extends tl{constructor(n,r,a,c){super(),this.type=Be.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=n,this.transport=r,this.request=a,this.eventHandlers=c,a.transaction=this;let e=`SIP/2.0/${r.via_transport}`;e+=` ${n.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",e),this.ua.newTransaction(this)}get C(){return Be}stateChanged(n){this.state=n,this.emit("stateChanged")}send(){this.stateChanged(Be.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},os.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==Be.STATUS_ACCEPTED&&(Eu.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){Eu.debug(`Timer M expired for transaction ${this.id}`),this.state===Be.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){Eu.debug(`Timer B expired for transaction ${this.id}`),this.state===Be.STATUS_CALLING&&(this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){Eu.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(n){const r=new D_.OutgoingRequest(rl.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",n.getHeader("to")),this.D=setTimeout(()=>{this.timer_D()},os.TIMER_D),this.transport.send(r)}cancel(n){if(this.state!==Be.STATUS_PROCEEDING)return;const r=new D_.OutgoingRequest(rl.CANCEL,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",this.request.getHeader("to")),n&&r.setHeader("reason",n),this.transport.send(r)}receiveResponse(n){const r=n.status_code;if(r>=100&&r<=199)switch(this.state){case Be.STATUS_CALLING:this.stateChanged(Be.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(n);break;case Be.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(n);break}else if(r>=200&&r<=299)switch(this.state){case Be.STATUS_CALLING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},os.TIMER_M),this.eventHandlers.onReceiveResponse(n);break;case Be.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(n);break}else if(r>=300&&r<=699)switch(this.state){case Be.STATUS_CALLING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_COMPLETED),this.sendACK(n),this.eventHandlers.onReceiveResponse(n);break;case Be.STATUS_COMPLETED:this.sendACK(n);break}}}class NE extends tl{constructor(n,r,a,c){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=r,this.request=a,this.eventHandlers=c;let e=`SIP/2.0/${r.via_transport}`;e+=` ${n.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",e)}get C(){return Be}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){OE.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class ME extends tl{constructor(n,r,a){super(),this.type=Be.NON_INVITE_SERVER,this.id=a.via_branch,this.ua=n,this.transport=r,this.request=a,this.last_response="",a.server_transaction=this,this.state=Be.STATUS_TRYING,n.newTransaction(this)}get C(){return Be}stateChanged(n){this.state=n,this.emit("stateChanged")}timer_J(){M_.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,M_.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(n,r,a,c){if(n===100)switch(this.state){case Be.STATUS_TRYING:this.stateChanged(Be.STATUS_PROCEEDING),this.transport.send(r)||this.onTransportError();break;case Be.STATUS_PROCEEDING:this.last_response=r,this.transport.send(r)?a&&a():(this.onTransportError(),c&&c());break}else if(n>=200&&n<=699)switch(this.state){case Be.STATUS_TRYING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_COMPLETED),this.last_response=r,this.J=setTimeout(()=>{this.timer_J()},os.TIMER_J),this.transport.send(r)?a&&a():(this.onTransportError(),c&&c());break;case Be.STATUS_COMPLETED:break}}}class UE extends tl{constructor(n,r,a){super(),this.type=Be.INVITE_SERVER,this.id=a.via_branch,this.ua=n,this.transport=r,this.request=a,this.last_response="",a.server_transaction=this,this.state=Be.STATUS_PROCEEDING,n.newTransaction(this),this.resendProvisionalTimer=null,a.reply(100)}get C(){return Be}stateChanged(n){this.state=n,this.emit("stateChanged")}timer_H(){Cu.debug(`Timer H expired for transaction ${this.id}`),this.state===Be.STATUS_COMPLETED&&Cu.debug("ACK not received, dialog will be terminated"),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){Cu.debug(`Timer L expired for transaction ${this.id}`),this.state===Be.STATUS_ACCEPTED&&(this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,Cu.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(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(n,r,a,c){if(n>=100&&n<=199)switch(this.state){case Be.STATUS_PROCEEDING:this.transport.send(r)||this.onTransportError(),this.last_response=r;break}if(n>100&&n<=199&&this.state===Be.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},os.PROVISIONAL_RESPONSE_INTERVAL));else if(n>=200&&n<=299)switch(this.state){case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_ACCEPTED),this.last_response=r,this.L=setTimeout(()=>{this.timer_L()},os.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case Be.STATUS_ACCEPTED:this.transport.send(r)?a&&a():(this.onTransportError(),c&&c());break}else if(n>=300&&n<=699)switch(this.state){case Be.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(r)?(this.stateChanged(Be.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},os.TIMER_H),a&&a()):(this.onTransportError(),c&&c());break}}}function PE({_transactions:o},n){let r;switch(n.method){case rl.INVITE:if(r=o.ist[n.via_branch],r){switch(r.state){case Be.STATUS_PROCEEDING:r.transport.send(r.last_response);break;case Be.STATUS_ACCEPTED:break}return!0}break;case rl.ACK:if(r=o.ist[n.via_branch],r){if(r.state===Be.STATUS_ACCEPTED)return!1;if(r.state===Be.STATUS_COMPLETED)return r.state=Be.STATUS_CONFIRMED,r.I=setTimeout(()=>{r.timer_I()},os.TIMER_I),!0}else return!1;break;case rl.CANCEL:return r=o.ist[n.via_branch],r?(n.reply_sl(200),r.state!==Be.STATUS_PROCEEDING):(n.reply_sl(481),!0);default:if(r=o.nist[n.via_branch],r){switch(r.state){case Be.STATUS_TRYING:break;case Be.STATUS_PROCEEDING:case Be.STATUS_COMPLETED:r.transport.send(r.last_response);break}return!0}break}}var eo={C:Be,NonInviteClientTransaction:kE,InviteClientTransaction:DE,AckClientTransaction:NE,NonInviteServerTransaction:ME,InviteServerTransaction:UE,checkTransaction:PE};const Ir=Qt(eo),LE=mn,U_=bt,qE=O_,id=eo,HE=new LE("RequestSender"),ad={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var to=class{constructor(o,n,r){this._ua=o,this._eventHandlers=r,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(const a in ad)Object.prototype.hasOwnProperty.call(ad,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=ad[a]));o.status===o.C.STATUS_USER_CLOSED&&(this._method!==U_.BYE||this._method!==U_.ACK)&&this._eventHandlers.onTransportError()}send(){const o={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:n=>{this._receiveResponse(n)}};switch(this._method){case"INVITE":this.clientTransaction=new id.InviteClientTransaction(this._ua,this._ua.transport,this._request,o);break;case"ACK":this.clientTransaction=new id.AckClientTransaction(this._ua,this._ua.transport,this._request,o);break;default:this.clientTransaction=new id.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()}_receiveResponse(o){let n,r;const a=o.status_code;if((a===401||a===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(o.status_code===401?(n=o.parseHeader("www-authenticate"),r="authorization"):(n=o.parseHeader("proxy-authenticate"),r="proxy-authorization"),!n){HE.debug(`${o.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(o);return}if(!this._challenged||!this._staled&&n.stale===!0){if(this._auth||(this._auth=new qE({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(o);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(r,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(o)}else this._eventHandlers.onReceiveResponse(o)}};const sl=Qt(to),zE=mn,od=$n(),ga=bt,P_=On,L_=to,il=new zE("Registrator"),Au=10;var FE=class{constructor(o,n){this._reg_id=1,this._ua=o,this._transport=n,this._registrar=o.configuration.registrar_server,this._expires=o.configuration.register_expires,this._call_id=od.createRandomToken(22),this._cseq=0,this._to_uri=o.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(o){Array.isArray(o)||(o=[]),this._extraHeaders=o.slice()}setExtraContactParams(o){o instanceof Object||(o={}),this._extraContactParams="";for(const n in o)if(Object.prototype.hasOwnProperty.call(o,n)){const r=o[n];this._extraContactParams+=`;${n}`,r&&(this._extraContactParams+=`=${r}`)}}register(){if(this._registering){il.debug("Register request in progress...");return}const o=this._extraHeaders.slice();o.push(`Contact: ${this._contact};expires=${this._expires}${this._extraContactParams}`),o.push(`Expires: ${this._expires}`);const n=new P_.OutgoingRequest(ga.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},o),r=new L_(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,ga.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,ga.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")){il.debug("no Contact header in response to REGISTER, response ignored");break}const c=a.headers.Contact.reduce((d,A)=>d.concat(A.parsed),[]);let e=c.find(d=>this._sipInstance===d.getParam("+sip.instance")&&this._reg_id===parseInt(d.getParam("reg-id")));if(e||(e=c.find(d=>d.uri.user===this._ua.contact.uri.user)),!e){il.debug("no Contact header pointing to us, response ignored");break}let f=e.getParam("expires");!f&&a.hasHeader("expires")&&(f=a.getHeader("expires")),f||(f=this._expires),f=Number(f),f<Au&&(f=Au);const g=f>64?f*1e3/2+Math.floor((f/2-32)*1e3*Math.random()):f*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},g),e.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=e.getParam("temp-gruu").replace(/"/g,"")),e.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=e.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<Au&&(this._expires=Au),this.register()):(il.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,ga.causes.SIP_FAILURE_CODE));break}default:{const c=od.sipErrorCause(a.status_code);this._registrationFailure(a,c)}}}});this._registering=!0,r.send()}unregister(o={}){if(!this._registered){il.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();o.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),n.push("Expires: 0");const r=new P_.OutgoingRequest(ga.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new L_(this._ua,r,{onRequestTimeout:()=>{this._unregistered(null,ga.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,ga.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._unregistered(a);break;default:{const c=od.sipErrorCause(a.status_code);this._unregistered(a,c)}}}}).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(o,n){this._registering=!1,this._ua.registrationFailed({response:o||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:o||null,cause:n}))}_unregistered(o,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:o||null,cause:n||null})}};class BE extends Error{constructor(n,r){super(),this.code=1,this.name="CONFIGURATION_ERROR",this.parameter=n,this.value=r,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}}class VE extends Error{constructor(n){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=n,this.message=`Invalid status: ${n}`}}class jE extends Error{constructor(n){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=n}}class GE extends Error{constructor(n){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=n}}var Ls={ConfigurationError:BE,InvalidStateError:VE,NotSupportedError:jE,NotReadyError:GE};const di=Qt(Ls),ld=bt,Iu=eo,WE=to,ud={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var q_=class{constructor(o,n,r){this._dialog=o,this._ua=o._ua,this._request=n,this._eventHandlers=r,this._reattempt=!1,this._reattemptTimer=null;for(const a in ud)Object.prototype.hasOwnProperty.call(ud,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=ud[a]))}get request(){return this._request}send(){const o=new WE(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:n=>{this._eventHandlers.onAuthenticated(n)},onReceiveResponse:n=>{this._receiveResponse(n)}});if(o.send(),(this._request.method===ld.INVITE||this._request.method===ld.UPDATE&&this._request.body)&&o.clientTransaction.state!==Iu.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;const n=()=>{(o.clientTransaction.state===Iu.C.STATUS_ACCEPTED||o.clientTransaction.state===Iu.C.STATUS_COMPLETED||o.clientTransaction.state===Iu.C.STATUS_TERMINATED)&&(o.clientTransaction.removeListener("stateChanged",n),this._dialog.uac_pending_reply=!1)};o.clientTransaction.on("stateChanged",n)}}_receiveResponse(o){o.status_code===408||o.status_code===481?this._eventHandlers.onDialogError(o):o.method===ld.INVITE&&o.status_code===491?this._reattempt?o.status_code>=200&&o.status_code<300?this._eventHandlers.onSuccessResponse(o):o.status_code>=300&&this._eventHandlers.onErrorResponse(o):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):o.status_code>=200&&o.status_code<300?this._eventHandlers.onSuccessResponse(o):o.status_code>=300&&this._eventHandlers.onErrorResponse(o)}};const KE=Qt(q_),YE=mn,H_=On,hi=bt,al=eo,XE=q_,cd=$n(),dd=new YE("Dialog"),pi={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var z_=class{static get C(){return pi}constructor(o,n,r,a=pi.STATUS_CONFIRMED){if(this._owner=o,this._ua=o._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 H_.IncomingResponse&&(a=n.status_code<200?pi.STATUS_EARLY:pi.STATUS_CONFIRMED);const c=n.parseHeader("contact");r==="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=c.uri,this._route_set=n.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):r==="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=c.uri,this._route_set=n.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),dd.debug(`new ${r} dialog created with status ${this._state===pi.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(o){this._local_seqnum=o}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(o){this._uac_pending_reply=o}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===pi.STATUS_TERMINATED}update(o,n){this._state=pi.STATUS_CONFIRMED,dd.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=o.getHeaders("record-route").reverse())}terminate(){dd.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=pi.STATUS_TERMINATED}sendRequest(o,n={}){const r=cd.cloneArray(n.extraHeaders),a=cd.cloneObject(n.eventHandlers),c=n.body||null,e=this._createRequest(o,r,c);return a.onAuthenticated=()=>{this._local_seqnum+=1},new XE(this,e,a).send(),e}receiveRequest(o){this._checkInDialogRequest(o)&&(o.method===hi.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:o.method===hi.INVITE&&(this._ack_seqnum=o.cseq),this._owner.receiveRequest(o))}_createRequest(o,n,r){n=cd.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=o===hi.CANCEL||o===hi.ACK?this._local_seqnum:this._local_seqnum+=1;return new H_.OutgoingRequest(o,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,r)}_checkInDialogRequest(o){if(!this._remote_seqnum)this._remote_seqnum=o.cseq;else if(o.cseq<this._remote_seqnum)if(o.method===hi.ACK){if(this._ack_seqnum===null||o.cseq!==this._ack_seqnum)return!1}else return o.reply(500),!1;else o.cseq>this._remote_seqnum&&(this._remote_seqnum=o.cseq);if(o.method===hi.INVITE||o.method===hi.UPDATE&&o.body){if(this._uac_pending_reply===!0)o.reply(491);else if(this._uas_pending_reply===!0){const n=(Math.random()*10|0)+1;return o.reply(500,null,[`Retry-After:${n}`]),!1}else{this._uas_pending_reply=!0;const n=()=>{(o.server_transaction.state===al.C.STATUS_ACCEPTED||o.server_transaction.state===al.C.STATUS_COMPLETED||o.server_transaction.state===al.C.STATUS_TERMINATED)&&(o.server_transaction.removeListener("stateChanged",n),this._uas_pending_reply=!1)};o.server_transaction.on("stateChanged",n)}o.hasHeader("contact")&&o.server_transaction.on("stateChanged",()=>{o.server_transaction.state===al.C.STATUS_ACCEPTED&&(this._remote_target=o.parseHeader("contact").uri)})}else o.method===hi.NOTIFY&&o.hasHeader("contact")&&o.server_transaction.on("stateChanged",()=>{o.server_transaction.state===al.C.STATUS_COMPLETED&&(this._remote_target=o.parseHeader("contact").uri)});return!0}};const Ru=Qt(z_);var hd={exports:{}};const JE=Tn.EventEmitter,QE=mn,ZE=bt,eC=Ls,F_=$n(),tC=new QE("RTCSession:DTMF"),B_={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};hd.exports=class extends JE{constructor(o){super(),this._session=o,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(o,n={}){if(o===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 eC.InvalidStateError(this._session.status);const r=F_.cloneArray(n.extraHeaders);if(this.eventHandlers=F_.cloneObject(n.eventHandlers),typeof o=="string")o=o.toUpperCase();else if(typeof o=="number")o=o.toString();else throw new TypeError(`Invalid tone: ${o}`);if(o.match(/^[0-9A-DR#*]$/))this._tone=o;else throw new TypeError(`Invalid tone: ${o}`);this._duration=n.duration,r.push("Content-Type: application/dtmf-relay");let a=`Signal=${this._tone}\r
|
|
112
|
+
`,this.transport.send(c)}}class IE extends x_{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var On={OutgoingRequest:Su,InitialOutgoingInviteRequest:rd,IncomingRequest:AE,IncomingResponse:IE};const Za=Qt(On),RE=mn,Us=$n(),zr=new RE("DigestAuthentication");var O_=class{constructor(o){this._credentials=o,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(o){switch(o){case"realm":return this._realm;case"ha1":return this._ha1;default:zr.warn('get() | cannot get "%s" parameter',o);return}}authenticate({method:o,ruri:n,body:r},a,c=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 zr.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return zr.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return zr.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return zr.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return zr.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 zr.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=o,this._uri=n,this._cnonce=c||Us.createRandomToken(12),this._nc+=1;const e=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-e.length)+e,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=Us.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._ha1=this._credentials.ha1;let _,g;return this._qop==="auth"?(_=`${this._method}:${this._uri}`,g=Us.calculateMD5(_),zr.debug('authenticate() | using qop=auth [a2:"%s"]',_),this._response=Us.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${g}`)):this._qop==="auth-int"?(_=`${this._method}:${this._uri}:${Us.calculateMD5(r||"")}`,g=Us.calculateMD5(_),zr.debug('authenticate() | using qop=auth-int [a2:"%s"]',_),this._response=Us.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${g}`)):this._qop===null&&(_=`${this._method}:${this._uri}`,g=Us.calculateMD5(_),zr.debug('authenticate() | using qop=null [a2:"%s"]',_),this._response=Us.calculateMD5(`${this._ha1}:${this._nonce}:${g}`)),zr.debug("authenticate() | response generated"),!0}toString(){const o=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return o.push(`algorithm=${this._algorithm}`),o.push(`username="${this._credentials.username}"`),o.push(`realm="${this._realm}"`),o.push(`nonce="${this._nonce}"`),o.push(`uri="${this._uri}"`),o.push(`response="${this._response}"`),this._opaque&&o.push(`opaque="${this._opaque}"`),this._qop&&(o.push(`qop=${this._qop}`),o.push(`cnonce="${this._cnonce}"`),o.push(`nc=${this._ncHex}`)),`Digest ${o.join(", ")}`}};const $E=Qt(O_),Ps=500,xE=4e3,k_=5e3;var sd={T1:Ps,T2:xE,T4:k_,TIMER_B:64*Ps,TIMER_D:0*Ps,TIMER_F:64*Ps,TIMER_H:64*Ps,TIMER_I:0*Ps,TIMER_J:0*Ps,TIMER_K:0*k_,TIMER_L:64*Ps,TIMER_M:64*Ps,PROVISIONAL_RESPONSE_INTERVAL:6e4};const el=Qt(sd),tl=Tn.EventEmitter,nl=mn,rl=bt,D_=On,os=sd,N_=new nl("NonInviteClientTransaction"),Eu=new nl("InviteClientTransaction"),OE=new nl("AckClientTransaction"),M_=new nl("NonInviteServerTransaction"),Cu=new nl("InviteServerTransaction"),Be={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 kE extends tl{constructor(n,r,a,c){super(),this.type=Be.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=n,this.transport=r,this.request=a,this.eventHandlers=c;let e=`SIP/2.0/${r.via_transport}`;e+=` ${n.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",e),this.ua.newTransaction(this)}get C(){return Be}stateChanged(n){this.state=n,this.emit("stateChanged")}send(){this.stateChanged(Be.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},os.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){N_.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){N_.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(n){const r=n.status_code;if(r<200)switch(this.state){case Be.STATUS_TRYING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(n);break}else switch(this.state){case Be.STATUS_TRYING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_COMPLETED),clearTimeout(this.F),r===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(n),this.K=setTimeout(()=>{this.timer_K()},os.TIMER_K);break;case Be.STATUS_COMPLETED:break}}}class DE extends tl{constructor(n,r,a,c){super(),this.type=Be.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=n,this.transport=r,this.request=a,this.eventHandlers=c,a.transaction=this;let e=`SIP/2.0/${r.via_transport}`;e+=` ${n.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",e),this.ua.newTransaction(this)}get C(){return Be}stateChanged(n){this.state=n,this.emit("stateChanged")}send(){this.stateChanged(Be.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},os.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==Be.STATUS_ACCEPTED&&(Eu.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){Eu.debug(`Timer M expired for transaction ${this.id}`),this.state===Be.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){Eu.debug(`Timer B expired for transaction ${this.id}`),this.state===Be.STATUS_CALLING&&(this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){Eu.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(n){const r=new D_.OutgoingRequest(rl.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",n.getHeader("to")),this.D=setTimeout(()=>{this.timer_D()},os.TIMER_D),this.transport.send(r)}cancel(n){if(this.state!==Be.STATUS_PROCEEDING)return;const r=new D_.OutgoingRequest(rl.CANCEL,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",this.request.getHeader("to")),n&&r.setHeader("reason",n),this.transport.send(r)}receiveResponse(n){const r=n.status_code;if(r>=100&&r<=199)switch(this.state){case Be.STATUS_CALLING:this.stateChanged(Be.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(n);break;case Be.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(n);break}else if(r>=200&&r<=299)switch(this.state){case Be.STATUS_CALLING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},os.TIMER_M),this.eventHandlers.onReceiveResponse(n);break;case Be.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(n);break}else if(r>=300&&r<=699)switch(this.state){case Be.STATUS_CALLING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_COMPLETED),this.sendACK(n),this.eventHandlers.onReceiveResponse(n);break;case Be.STATUS_COMPLETED:this.sendACK(n);break}}}class NE extends tl{constructor(n,r,a,c){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=r,this.request=a,this.eventHandlers=c;let e=`SIP/2.0/${r.via_transport}`;e+=` ${n.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",e)}get C(){return Be}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){OE.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class ME extends tl{constructor(n,r,a){super(),this.type=Be.NON_INVITE_SERVER,this.id=a.via_branch,this.ua=n,this.transport=r,this.request=a,this.last_response="",a.server_transaction=this,this.state=Be.STATUS_TRYING,n.newTransaction(this)}get C(){return Be}stateChanged(n){this.state=n,this.emit("stateChanged")}timer_J(){M_.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,M_.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(n,r,a,c){if(n===100)switch(this.state){case Be.STATUS_TRYING:this.stateChanged(Be.STATUS_PROCEEDING),this.transport.send(r)||this.onTransportError();break;case Be.STATUS_PROCEEDING:this.last_response=r,this.transport.send(r)?a&&a():(this.onTransportError(),c&&c());break}else if(n>=200&&n<=699)switch(this.state){case Be.STATUS_TRYING:case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_COMPLETED),this.last_response=r,this.J=setTimeout(()=>{this.timer_J()},os.TIMER_J),this.transport.send(r)?a&&a():(this.onTransportError(),c&&c());break;case Be.STATUS_COMPLETED:break}}}class UE extends tl{constructor(n,r,a){super(),this.type=Be.INVITE_SERVER,this.id=a.via_branch,this.ua=n,this.transport=r,this.request=a,this.last_response="",a.server_transaction=this,this.state=Be.STATUS_PROCEEDING,n.newTransaction(this),this.resendProvisionalTimer=null,a.reply(100)}get C(){return Be}stateChanged(n){this.state=n,this.emit("stateChanged")}timer_H(){Cu.debug(`Timer H expired for transaction ${this.id}`),this.state===Be.STATUS_COMPLETED&&Cu.debug("ACK not received, dialog will be terminated"),this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){Cu.debug(`Timer L expired for transaction ${this.id}`),this.state===Be.STATUS_ACCEPTED&&(this.stateChanged(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,Cu.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(Be.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(n,r,a,c){if(n>=100&&n<=199)switch(this.state){case Be.STATUS_PROCEEDING:this.transport.send(r)||this.onTransportError(),this.last_response=r;break}if(n>100&&n<=199&&this.state===Be.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},os.PROVISIONAL_RESPONSE_INTERVAL));else if(n>=200&&n<=299)switch(this.state){case Be.STATUS_PROCEEDING:this.stateChanged(Be.STATUS_ACCEPTED),this.last_response=r,this.L=setTimeout(()=>{this.timer_L()},os.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case Be.STATUS_ACCEPTED:this.transport.send(r)?a&&a():(this.onTransportError(),c&&c());break}else if(n>=300&&n<=699)switch(this.state){case Be.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(r)?(this.stateChanged(Be.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},os.TIMER_H),a&&a()):(this.onTransportError(),c&&c());break}}}function PE({_transactions:o},n){let r;switch(n.method){case rl.INVITE:if(r=o.ist[n.via_branch],r){switch(r.state){case Be.STATUS_PROCEEDING:r.transport.send(r.last_response);break;case Be.STATUS_ACCEPTED:break}return!0}break;case rl.ACK:if(r=o.ist[n.via_branch],r){if(r.state===Be.STATUS_ACCEPTED)return!1;if(r.state===Be.STATUS_COMPLETED)return r.state=Be.STATUS_CONFIRMED,r.I=setTimeout(()=>{r.timer_I()},os.TIMER_I),!0}else return!1;break;case rl.CANCEL:return r=o.ist[n.via_branch],r?(n.reply_sl(200),r.state!==Be.STATUS_PROCEEDING):(n.reply_sl(481),!0);default:if(r=o.nist[n.via_branch],r){switch(r.state){case Be.STATUS_TRYING:break;case Be.STATUS_PROCEEDING:case Be.STATUS_COMPLETED:r.transport.send(r.last_response);break}return!0}break}}var eo={C:Be,NonInviteClientTransaction:kE,InviteClientTransaction:DE,AckClientTransaction:NE,NonInviteServerTransaction:ME,InviteServerTransaction:UE,checkTransaction:PE};const Ir=Qt(eo),LE=mn,U_=bt,qE=O_,id=eo,HE=new LE("RequestSender"),ad={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var to=class{constructor(o,n,r){this._ua=o,this._eventHandlers=r,this._method=n.method,this._request=n,this._auth=null,this._challenged=!1,this._staled=!1;for(const a in ad)Object.prototype.hasOwnProperty.call(ad,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=ad[a]));o.status===o.C.STATUS_USER_CLOSED&&(this._method!==U_.BYE||this._method!==U_.ACK)&&this._eventHandlers.onTransportError()}send(){const o={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:n=>{this._receiveResponse(n)}};switch(this._method){case"INVITE":this.clientTransaction=new id.InviteClientTransaction(this._ua,this._ua.transport,this._request,o);break;case"ACK":this.clientTransaction=new id.AckClientTransaction(this._ua,this._ua.transport,this._request,o);break;default:this.clientTransaction=new id.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()}_receiveResponse(o){let n,r;const a=o.status_code;if((a===401||a===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(o.status_code===401?(n=o.parseHeader("www-authenticate"),r="authorization"):(n=o.parseHeader("proxy-authenticate"),r="proxy-authorization"),!n){HE.debug(`${o.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(o);return}if(!this._challenged||!this._staled&&n.stale===!0){if(this._auth||(this._auth=new qE({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(o);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(r,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(o)}else this._eventHandlers.onReceiveResponse(o)}};const sl=Qt(to),zE=mn,od=$n(),ga=bt,P_=On,L_=to,il=new zE("Registrator"),Au=10;var FE=class{constructor(o,n){this._reg_id=1,this._ua=o,this._transport=n,this._registrar=o.configuration.registrar_server,this._expires=o.configuration.register_expires,this._call_id=od.createRandomToken(22),this._cseq=0,this._to_uri=o.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(o){Array.isArray(o)||(o=[]),this._extraHeaders=o.slice()}setExtraContactParams(o){o instanceof Object||(o={}),this._extraContactParams="";for(const n in o)if(Object.prototype.hasOwnProperty.call(o,n)){const r=o[n];this._extraContactParams+=`;${n}`,r&&(this._extraContactParams+=`=${r}`)}}register(){if(this._registering){il.debug("Register request in progress...");return}const o=this._extraHeaders.slice();o.push(`Contact: ${this._contact};expires=${this._expires}${this._extraContactParams}`),o.push(`Expires: ${this._expires}`);const n=new P_.OutgoingRequest(ga.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},o),r=new L_(this._ua,n,{onRequestTimeout:()=>{this._registrationFailure(null,ga.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,ga.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")){il.debug("no Contact header in response to REGISTER, response ignored");break}const c=a.headers.Contact.reduce((d,A)=>d.concat(A.parsed),[]);let e=c.find(d=>this._sipInstance===d.getParam("+sip.instance")&&this._reg_id===parseInt(d.getParam("reg-id")));if(e||(e=c.find(d=>d.uri.user===this._ua.contact.uri.user)),!e){il.debug("no Contact header pointing to us, response ignored");break}let _=e.getParam("expires");!_&&a.hasHeader("expires")&&(_=a.getHeader("expires")),_||(_=this._expires),_=Number(_),_<Au&&(_=Au);const g=_>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")},g),e.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=e.getParam("temp-gruu").replace(/"/g,"")),e.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=e.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<Au&&(this._expires=Au),this.register()):(il.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,ga.causes.SIP_FAILURE_CODE));break}default:{const c=od.sipErrorCause(a.status_code);this._registrationFailure(a,c)}}}});this._registering=!0,r.send()}unregister(o={}){if(!this._registered){il.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const n=this._extraHeaders.slice();o.all?n.push(`Contact: *${this._extraContactParams}`):n.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),n.push("Expires: 0");const r=new P_.OutgoingRequest(ga.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n);new L_(this._ua,r,{onRequestTimeout:()=>{this._unregistered(null,ga.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,ga.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._unregistered(a);break;default:{const c=od.sipErrorCause(a.status_code);this._unregistered(a,c)}}}}).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(o,n){this._registering=!1,this._ua.registrationFailed({response:o||null,cause:n}),this._registered&&(this._registered=!1,this._ua.unregistered({response:o||null,cause:n}))}_unregistered(o,n){this._registering=!1,this._registered=!1,this._ua.unregistered({response:o||null,cause:n||null})}};class BE extends Error{constructor(n,r){super(),this.code=1,this.name="CONFIGURATION_ERROR",this.parameter=n,this.value=r,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}}class VE extends Error{constructor(n){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=n,this.message=`Invalid status: ${n}`}}class jE extends Error{constructor(n){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=n}}class GE extends Error{constructor(n){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=n}}var Ls={ConfigurationError:BE,InvalidStateError:VE,NotSupportedError:jE,NotReadyError:GE};const di=Qt(Ls),ld=bt,Iu=eo,WE=to,ud={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var q_=class{constructor(o,n,r){this._dialog=o,this._ua=o._ua,this._request=n,this._eventHandlers=r,this._reattempt=!1,this._reattemptTimer=null;for(const a in ud)Object.prototype.hasOwnProperty.call(ud,a)&&(this._eventHandlers[a]||(this._eventHandlers[a]=ud[a]))}get request(){return this._request}send(){const o=new WE(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:n=>{this._eventHandlers.onAuthenticated(n)},onReceiveResponse:n=>{this._receiveResponse(n)}});if(o.send(),(this._request.method===ld.INVITE||this._request.method===ld.UPDATE&&this._request.body)&&o.clientTransaction.state!==Iu.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;const n=()=>{(o.clientTransaction.state===Iu.C.STATUS_ACCEPTED||o.clientTransaction.state===Iu.C.STATUS_COMPLETED||o.clientTransaction.state===Iu.C.STATUS_TERMINATED)&&(o.clientTransaction.removeListener("stateChanged",n),this._dialog.uac_pending_reply=!1)};o.clientTransaction.on("stateChanged",n)}}_receiveResponse(o){o.status_code===408||o.status_code===481?this._eventHandlers.onDialogError(o):o.method===ld.INVITE&&o.status_code===491?this._reattempt?o.status_code>=200&&o.status_code<300?this._eventHandlers.onSuccessResponse(o):o.status_code>=300&&this._eventHandlers.onErrorResponse(o):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):o.status_code>=200&&o.status_code<300?this._eventHandlers.onSuccessResponse(o):o.status_code>=300&&this._eventHandlers.onErrorResponse(o)}};const KE=Qt(q_),YE=mn,H_=On,hi=bt,al=eo,XE=q_,cd=$n(),dd=new YE("Dialog"),pi={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var z_=class{static get C(){return pi}constructor(o,n,r,a=pi.STATUS_CONFIRMED){if(this._owner=o,this._ua=o._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 H_.IncomingResponse&&(a=n.status_code<200?pi.STATUS_EARLY:pi.STATUS_CONFIRMED);const c=n.parseHeader("contact");r==="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=c.uri,this._route_set=n.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):r==="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=c.uri,this._route_set=n.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),dd.debug(`new ${r} dialog created with status ${this._state===pi.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(o){this._local_seqnum=o}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(o){this._uac_pending_reply=o}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===pi.STATUS_TERMINATED}update(o,n){this._state=pi.STATUS_CONFIRMED,dd.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),n==="UAC"&&(this._route_set=o.getHeaders("record-route").reverse())}terminate(){dd.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=pi.STATUS_TERMINATED}sendRequest(o,n={}){const r=cd.cloneArray(n.extraHeaders),a=cd.cloneObject(n.eventHandlers),c=n.body||null,e=this._createRequest(o,r,c);return a.onAuthenticated=()=>{this._local_seqnum+=1},new XE(this,e,a).send(),e}receiveRequest(o){this._checkInDialogRequest(o)&&(o.method===hi.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:o.method===hi.INVITE&&(this._ack_seqnum=o.cseq),this._owner.receiveRequest(o))}_createRequest(o,n,r){n=cd.cloneArray(n),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const a=o===hi.CANCEL||o===hi.ACK?this._local_seqnum:this._local_seqnum+=1;return new H_.OutgoingRequest(o,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,r)}_checkInDialogRequest(o){if(!this._remote_seqnum)this._remote_seqnum=o.cseq;else if(o.cseq<this._remote_seqnum)if(o.method===hi.ACK){if(this._ack_seqnum===null||o.cseq!==this._ack_seqnum)return!1}else return o.reply(500),!1;else o.cseq>this._remote_seqnum&&(this._remote_seqnum=o.cseq);if(o.method===hi.INVITE||o.method===hi.UPDATE&&o.body){if(this._uac_pending_reply===!0)o.reply(491);else if(this._uas_pending_reply===!0){const n=(Math.random()*10|0)+1;return o.reply(500,null,[`Retry-After:${n}`]),!1}else{this._uas_pending_reply=!0;const n=()=>{(o.server_transaction.state===al.C.STATUS_ACCEPTED||o.server_transaction.state===al.C.STATUS_COMPLETED||o.server_transaction.state===al.C.STATUS_TERMINATED)&&(o.server_transaction.removeListener("stateChanged",n),this._uas_pending_reply=!1)};o.server_transaction.on("stateChanged",n)}o.hasHeader("contact")&&o.server_transaction.on("stateChanged",()=>{o.server_transaction.state===al.C.STATUS_ACCEPTED&&(this._remote_target=o.parseHeader("contact").uri)})}else o.method===hi.NOTIFY&&o.hasHeader("contact")&&o.server_transaction.on("stateChanged",()=>{o.server_transaction.state===al.C.STATUS_COMPLETED&&(this._remote_target=o.parseHeader("contact").uri)});return!0}};const Ru=Qt(z_);var hd={exports:{}};const JE=Tn.EventEmitter,QE=mn,ZE=bt,eC=Ls,F_=$n(),tC=new QE("RTCSession:DTMF"),B_={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};hd.exports=class extends JE{constructor(o){super(),this._session=o,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(o,n={}){if(o===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 eC.InvalidStateError(this._session.status);const r=F_.cloneArray(n.extraHeaders);if(this.eventHandlers=F_.cloneObject(n.eventHandlers),typeof o=="string")o=o.toUpperCase();else if(typeof o=="number")o=o.toString();else throw new TypeError(`Invalid tone: ${o}`);if(o.match(/^[0-9A-DR#*]$/))this._tone=o;else throw new TypeError(`Invalid tone: ${o}`);this._duration=n.duration,r.push("Content-Type: application/dtmf-relay");let a=`Signal=${this._tone}\r
|
|
113
113
|
`;a+=`Duration=${this._duration}`,this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(ZE.INFO,{extraHeaders:r,eventHandlers:{onSuccessResponse:c=>{this.emit("succeeded",{originator:"remote",response:c})},onErrorResponse:c=>{this.eventHandlers.onFailed&&this.eventHandlers.onFailed(),this.emit("failed",{originator:"remote",response:c})},onRequestTimeout:()=>{this._session.onRequestTimeout()},onTransportError:()=>{this._session.onTransportError()},onDialogError:()=>{this._session.onDialogError()}},body:a})}init_incoming(o){const n=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,r=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;if(this._direction="incoming",this._request=o,o.reply(200),o.body){const a=o.body.split(`
|
|
114
|
-
`);a.length>=1&&n.test(a[0])&&(this._tone=a[0].replace(n,"$2")),a.length>=2&&r.test(a[1])&&(this._duration=parseInt(a[1].replace(r,"$2"),10))}this._duration||(this._duration=B_.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:o}):tC.debug("invalid INFO DTMF received, discarded")}},hd.exports.C=B_;var V_=hd.exports;const nC=Qt(V_),rC=Tn.EventEmitter,sC=bt,iC=Ls,aC=$n();var j_=class extends rC{constructor(o){super(),this._session=o,this._direction=null,this._contentType=null,this._body=null}get contentType(){return this._contentType}get body(){return this._body}send(o,n,r={}){if(this._direction="outgoing",o===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 iC.InvalidStateError(this._session.status);this._contentType=o,this._body=n;const a=aC.cloneArray(r.extraHeaders);a.push(`Content-Type: ${o}`),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(sC.INFO,{extraHeaders:a,eventHandlers:{onSuccessResponse:c=>{this.emit("succeeded",{originator:"remote",response:c})},onErrorResponse:c=>{this.emit("failed",{originator:"remote",response:c})},onTransportError:()=>{this._session.onTransportError()},onRequestTimeout:()=>{this._session.onRequestTimeout()},onDialogError:()=>{this._session.onDialogError()}},body:n})}init_incoming(o){this._direction="incoming",this.request=o,o.reply(200),this._contentType=o.hasHeader("Content-Type")?o.getHeader("Content-Type").toLowerCase():void 0,this._body=o.body,this._session.newInfo({originator:"remote",info:this,request:o})}};const pd=Qt(j_),oC=mn,G_=bt,lC=new oC("RTCSession:ReferNotifier"),_d={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300};var W_=class{constructor(o,n,r){this._session=o,this._id=n,this._expires=r||_d.expires,this._active=!0,this.notify(100)}notify(o,n){if(lC.debug("notify()"),this._active===!1)return;n=n||G_.REASON_PHRASE[o]||"";let r;o>=200?r="terminated;reason=noresource":r=`active;expires=${this._expires}`,this._session.sendRequest(G_.NOTIFY,{extraHeaders:[`Event: ${_d.event_type};id=${this._id}`,`Subscription-State: ${r}`,`Content-Type: ${_d.body_type}`],body:`SIP/2.0 ${o} ${n}`,eventHandlers:{onErrorResponse(){this._active=!1}}})}};const uC=Qt(W_),cC=Tn.EventEmitter,dC=mn,ol=bt,hC=Hr(),K_=$n(),ya=new dC("RTCSession:ReferSubscriber");var Y_=class extends cC{constructor(o){super(),this._id=null,this._session=o}get id(){return this._id}sendRefer(o,n={}){ya.debug("sendRefer()");const r=K_.cloneArray(n.extraHeaders),a=K_.cloneObject(n.eventHandlers);for(const g in a)Object.prototype.hasOwnProperty.call(a,g)&&this.on(g,a[g]);let c=null;n.replaces&&(c=n.replaces._request.call_id,c+=`;to-tag=${n.replaces._to_tag}`,c+=`;from-tag=${n.replaces._from_tag}`,c=encodeURIComponent(c));const e=`Refer-To: <${o}${c?`?Replaces=${c}`:""}>`;if(r.push(e),!r.some(g=>g.toLowerCase().startsWith("referred-by:"))){const g=`Referred-By: <${this._session._ua._configuration.uri._scheme}:${this._session._ua._configuration.uri._user}@${this._session._ua._configuration.uri._host}>`;r.push(g)}r.push(`Contact: ${this._session.contact}`);const
|
|
115
|
-
`,1)[0],"Status_Line");if(n===-1){ya.debug(`receiveNotify() | error parsing NOTIFY body: "${o.body}"`);return}switch(!0){case/^100$/.test(n.status_code):this.emit("trying",{request:o,status_line:n});break;case/^1[0-9]{2}$/.test(n.status_code):this.emit("progress",{request:o,status_line:n});break;case/^2[0-9]{2}$/.test(n.status_code):this.emit("accepted",{request:o,status_line:n});break;default:this.emit("failed",{request:o,status_line:n});break}}_requestSucceeded(o){ya.debug("REFER succeeded"),ya.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:o})}_requestFailed(o,n){ya.debug("REFER failed"),ya.debug('emit "requestFailed"'),this.emit("requestFailed",{response:o||null,cause:n})}};const pC=Qt(Y_),_C=Tn.EventEmitter,X_=nr,fC=mn,Ve=bt,va=Ls,J_=eo,Jt=$n(),ll=sd,mC=On,$u=z_,gC=to,fr=V_,Q_=j_,yC=W_,vC=Y_,Z_=Ms(),Te=new fC("RTCSession"),Ce={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},xu=["audio","video"];var ef=class jh extends _C{static get C(){return Ce}constructor(n){Te.debug("new"),super(),this._id=null,this._ua=n,this._status=Ce.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:Ve.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return Ce}get causes(){return Ve.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(n){this._data=n}get status(){return this._status}isInProgress(){switch(this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:case Ce.STATUS_INVITE_RECEIVED:case Ce.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case Ce.STATUS_ANSWERED:case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case Ce.STATUS_CANCELED:case Ce.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(n,r={},a){Te.debug("connect()");const c=n,e=Jt.cloneObject(r.eventHandlers),f=Jt.cloneArray(r.extraHeaders),g=Jt.cloneObject(r.mediaConstraints,{audio:!0,video:!0}),d=r.mediaStream||null,A=Jt.cloneObject(r.pcConfig,{iceServers:[]}),S=r.rtcConstraints||null,R=r.rtcOfferConstraints||null;if(this._rtcOfferConstraints=R,this._rtcAnswerConstraints=r.rtcAnswerConstraints||null,this._data=r.data||this._data,n===void 0)throw new TypeError("Not enough arguments");if(this._status!==Ce.STATUS_NULL)throw new va.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new va.NotSupportedError("WebRTC not supported");if(n=this._ua.normalizeTarget(n),!n)throw new TypeError(`Invalid target: ${c}`);this._sessionTimers.enabled&&Jt.isDecimal(r.sessionTimersExpires)&&(r.sessionTimersExpires>=Ve.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=r.sessionTimersExpires:this._sessionTimers.defaultExpires=Ve.SESSION_EXPIRES);for(const W in e)Object.prototype.hasOwnProperty.call(e,W)&&this.on(W,e[W]);this._from_tag=Jt.newTag();const N=r.anonymous||!1,H={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:N,outbound:!0}),N?(H.from_display_name="Anonymous",H.from_uri=new Z_("sip","anonymous","anonymous.invalid"),f.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),f.push("Privacy: id")):r.fromUserName&&(H.from_uri=new Z_("sip",r.fromUserName,this._ua.configuration.uri.host),f.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),r.fromDisplayName&&(H.from_display_name=r.fromDisplayName),f.push(`Contact: ${this._contact}`),f.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&f.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new mC.InitialOutgoingInviteRequest(n,this._ua,H,f),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(A,S),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,a&&a(this),this._newRTCSession("local",this._request),this._sendInitialRequest(g,R,d)}init_incoming(n,r){Te.debug("init_incoming()");let a;const c=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&c!=="application/sdp"){n.reply(415);return}if(this._status=Ce.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(a=n.getHeader("expires")*1e3),n.to_tag=Jt.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),this._failed("local",null,Ve.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),this._failed("system",null,Ve.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),this._newRTCSession("remote",n),this._status!==Ce.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(n={}){Te.debug("answer()");const r=this._request,a=Jt.cloneArray(n.extraHeaders),c=Jt.cloneObject(n.mediaConstraints),e=n.mediaStream||null,f=Jt.cloneObject(n.pcConfig,{iceServers:[]}),g=n.rtcConstraints||null,d=n.rtcAnswerConstraints||null,A=Jt.cloneObject(n.rtcOfferConstraints);let S,R=!1,N=!1,H=!1,W=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=n.rtcOfferConstraints||null,this._data=n.data||this._data,this._direction!=="incoming")throw new va.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==Ce.STATUS_WAITING_FOR_ANSWER)throw new va.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Jt.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=Ve.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=Ve.SESSION_EXPIRES),this._status=Ce.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),a.unshift(`Contact: ${this._contact}`);const G=r.parseSDP();Array.isArray(G.media)||(G.media=[G.media]);for(const K of G.media)K.type==="audio"&&(R=!0,(!K.direction||K.direction==="sendrecv")&&(H=!0)),K.type==="video"&&(N=!0,(!K.direction||K.direction==="sendrecv")&&(W=!0));if(e&&c.audio===!1){S=e.getAudioTracks();for(const K of S)e.removeTrack(K)}if(e&&c.video===!1){S=e.getVideoTracks();for(const K of S)e.removeTrack(K)}!e&&c.audio===void 0&&(c.audio=H),!e&&c.video===void 0&&(c.video=W),!e&&!R&&!A.offerToReceiveAudio&&(c.audio=!1),!e&&!N&&!A.offerToReceiveVideo&&(c.video=!1),this._createRTCConnection(f,g),Promise.resolve().then(()=>{if(e)return e;if(c.audio||c.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(c).catch(K=>{throw this._status===Ce.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,Ve.causes.USER_DENIED_MEDIA_ACCESS),Te.warn('emit "getusermediafailed" [error:%o]',K),this.emit("getusermediafailed",K),new Error("getUserMedia() failed"))})}).then(K=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=K,K&&K.getTracks().forEach(ae=>{this._connection.addTrack(ae,K)})}).then(()=>{if(this._late_sdp)return;const K={originator:"remote",type:"offer",sdp:r.body};Te.debug('emit "sdp"'),this.emit("sdp",K);const ae=new RTCSessionDescription({type:"offer",sdp:K.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(ae)).catch(ee=>{throw r.reply(488),this._failed("system",null,Ve.causes.WEBRTC_ERROR),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',ee),this.emit("peerconnection:setremotedescriptionfailed",ee),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",d).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(K=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,a),r.reply(200,null,a,K,()=>{this._status=Ce.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,K),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,Ve.causes.CONNECTION_ERROR)})}).catch(K=>{this._status!==Ce.STATUS_TERMINATED&&Te.warn(K)})}terminate(n={}){Te.debug("terminate()");const r=n.cause||Ve.causes.BYE,a=Jt.cloneArray(n.extraHeaders),c=n.body;let e,f=n.status_code,g=n.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new va.InvalidStateError(this._status);switch(this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(Te.debug("canceling session"),f&&(f<200||f>=700))throw new TypeError(`Invalid status_code: ${f}`);f&&(g=g||Ve.REASON_PHRASE[f]||"",e=`SIP ;cause=${f} ;text="${g}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=Ce.STATUS_CANCELED,this._failed("local",null,Ve.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(Te.debug("rejecting session"),f=f||480,f<300||f>=700)throw new TypeError(`Invalid status_code: ${f}`);this._request.reply(f,g,a,c),this._failed("local",null,Ve.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(Te.debug("terminating session"),g=n.reason_phrase||Ve.REASON_PHRASE[f]||"",f&&(f<200||f>=700))throw new TypeError(`Invalid status_code: ${f}`);if(f&&a.push(`Reason: SIP ;cause=${f}; text="${g}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==J_.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:A})=>{A===Ve.ACK&&(this.sendRequest(Ve.BYE,{extraHeaders:a,body:c}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===J_.C.STATUS_TERMINATED&&(this.sendRequest(Ve.BYE,{extraHeaders:a,body:c}),d.terminate())}),this._ended("local",null,r),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(Ve.BYE,{extraHeaders:a,body:c}),this._ended("local",null,r)}}sendDTMF(n,r={}){Te.debug("sendDTMF() | tones: %s",n);let a=0,c=r.duration||null,e=r.interToneGap||null;const f=r.transportType||Ve.DTMF_TRANSPORT.INFO;if(n===void 0)throw new TypeError("Not enough arguments");if(this._status!==Ce.STATUS_CONFIRMED&&this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_1XX_RECEIVED)throw new va.InvalidStateError(this._status);if(f!==Ve.DTMF_TRANSPORT.INFO&&f!==Ve.DTMF_TRANSPORT.RFC2833)throw new TypeError(`invalid transportType: ${f}`);if(typeof n=="number"&&(n=n.toString()),!n||typeof n!="string"||!n.match(/^[0-9A-DR#*,]+$/i))throw new TypeError(`Invalid tones: ${n}`);if(c&&!Jt.isDecimal(c))throw new TypeError(`Invalid tone duration: ${c}`);if(c?c<fr.C.MIN_DURATION?(Te.debug(`"duration" value is lower than the minimum allowed, setting it to ${fr.C.MIN_DURATION} milliseconds`),c=fr.C.MIN_DURATION):c>fr.C.MAX_DURATION?(Te.debug(`"duration" value is greater than the maximum allowed, setting it to ${fr.C.MAX_DURATION} milliseconds`),c=fr.C.MAX_DURATION):c=Math.abs(c):c=fr.C.DEFAULT_DURATION,r.duration=c,e&&!Jt.isDecimal(e))throw new TypeError(`Invalid interToneGap: ${e}`);if(e?e<fr.C.MIN_INTER_TONE_GAP?(Te.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${fr.C.MIN_INTER_TONE_GAP} milliseconds`),e=fr.C.MIN_INTER_TONE_GAP):e=Math.abs(e):e=fr.C.DEFAULT_INTER_TONE_GAP,f===Ve.DTMF_TRANSPORT.RFC2833){const d=this._getDTMFRTPSender();d&&(n=d.toneBuffer+n,d.insertDTMF(n,c,e));return}if(this._tones){this._tones+=n;return}this._tones=n,g.call(this);function g(){let d;if(this._status===Ce.STATUS_TERMINATED||!this._tones||a>=this._tones.length){this._tones=null;return}const A=this._tones[a];if(a+=1,A===",")d=2e3;else{const S=new fr(this);r.eventHandlers={onFailed:()=>{this._tones=null}},S.send(A,r),d=c+e}setTimeout(g.bind(this),d)}}sendInfo(n,r,a={}){if(Te.debug("sendInfo()"),this._status!==Ce.STATUS_CONFIRMED&&this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_1XX_RECEIVED)throw new va.InvalidStateError(this._status);new Q_(this).send(n,r,a)}mute(n={audio:!0,video:!1}){Te.debug("mute()");let r=!1,a=!1;this._audioMuted===!1&&n.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&n.video&&(a=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||a===!0)&&this._onmute({audio:r,video:a})}unmute(n={audio:!0,video:!0}){Te.debug("unmute()");let r=!1,a=!1;this._audioMuted===!0&&n.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&n.video&&(a=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||a===!0)&&this._onunmute({audio:r,video:a})}hold(n={},r){if(Te.debug("hold()"),this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ve.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:n.extraHeaders}),!0}unhold(n={},r){if(Te.debug("unhold()"),this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ve.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:n.extraHeaders}),!0}renegotiate(n={},r){Te.debug("renegotiate()");const a=n.rtcOfferConstraints||null;if(this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const c={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ve.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:c,rtcOfferConstraints:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:c,rtcOfferConstraints:a,extraHeaders:n.extraHeaders}),!0}refer(n,r){Te.debug("refer()");const a=n;if(this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED)return!1;if(n=this._ua.normalizeTarget(n),!n)throw new TypeError(`Invalid target: ${a}`);const c=new vC(this);c.sendRefer(n,r);const e=c.id;return this._referSubscribers[e]=c,c.on("requestFailed",()=>{delete this._referSubscribers[e]}),c.on("accepted",()=>{delete this._referSubscribers[e]}),c.on("failed",()=>{delete this._referSubscribers[e]}),c}sendRequest(n,r){return Te.debug("sendRequest()"),this._dialog.sendRequest(n,r)}receiveRequest(n){if(Te.debug("receiveRequest()"),n.method===Ve.CANCEL)(this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED)&&(this._status=Ce.STATUS_CANCELED,this._request.reply(487),this._failed("remote",n,Ve.causes.CANCELED));else switch(n.method){case Ve.ACK:if(this._status!==Ce.STATUS_WAITING_FOR_ACK)return;if(this._status=Ce.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:Ve.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};Te.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(c=>{this.terminate({cause:Ve.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})}else this._is_confirmed||this._confirmed("remote",n);break;case Ve.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,Ve.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,Ve.causes.BYE)):n.reply(403,"Wrong Status");break;case Ve.INVITE:this._status===Ce.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case Ve.INFO:if(this._status===Ce.STATUS_1XX_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED||this._status===Ce.STATUS_WAITING_FOR_ACK||this._status===Ce.STATUS_CONFIRMED){const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new fr(this).init_incoming(n):r!==void 0?new Q_(this).init_incoming(n):n.reply(415)}else n.reply(403,"Wrong Status");break;case Ve.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case Ve.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case Ve.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){Te.warn("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ve.causes.CONNECTION_ERROR,cause:Ve.causes.CONNECTION_ERROR})}onRequestTimeout(){Te.warn("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Ve.causes.REQUEST_TIMEOUT,cause:Ve.causes.REQUEST_TIMEOUT})}onDialogError(){Te.warn("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ve.causes.DIALOG_ERROR,cause:Ve.causes.DIALOG_ERROR})}newDTMF(n){Te.debug("newDTMF()"),this.emit("newDTMF",n)}newInfo(n){Te.debug("newInfo()"),this.emit("newInfo",n)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Te.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Te.debug("_isReadyToReOffer() | session not established yet"),!1):(Te.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Te.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Te.debug("close() | closing local MediaStream"),Jt.closeMediaStream(this._localMediaStream)),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){Te.warn("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(n,r){let a=ll.T1;function c(){this._status===Ce.STATUS_WAITING_FOR_ACK&&(n.reply(200,null,[`Contact: ${this._contact}`],r),a<ll.T2&&(a=a*2,a>ll.T2&&(a=ll.T2)),this._timers.invite2xxTimer=setTimeout(c.bind(this),a))}this._timers.invite2xxTimer=setTimeout(c.bind(this),a)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ACK&&(Te.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(Ve.BYE),this._ended("remote",null,Ve.causes.NO_ACK))},ll.TIMER_H)}_createRTCConnection(n,r){this._connection=new RTCPeerConnection(n,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:Ve.causes.RTP_TIMEOUT,status_code:408,reason_phrase:Ve.causes.RTP_TIMEOUT})}),Te.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(n,r){if(Te.debug("createLocalDescription()"),n!=="offer"&&n!=="answer")throw new Error(`createLocalDescription() | invalid type "${n}"`);const a=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>n==="offer"?a.createOffer(r).catch(c=>(Te.warn('emit "peerconnection:createofferfailed" [error:%o]',c),this.emit("peerconnection:createofferfailed",c),Promise.reject(c))):a.createAnswer(r).catch(c=>(Te.warn('emit "peerconnection:createanswerfailed" [error:%o]',c),this.emit("peerconnection:createanswerfailed",c),Promise.reject(c)))).then(c=>a.setLocalDescription(c).catch(e=>(this._rtcReady=!0,Te.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',e),this.emit("peerconnection:setlocaldescriptionfailed",e),Promise.reject(e)))).then(()=>{const c=r&&r.iceRestart;if(a.iceGatheringState==="complete"&&!c||a.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const e={originator:"local",type:n,sdp:a.localDescription.sdp};return Te.debug('emit "sdp"'),this.emit("sdp",e),Promise.resolve(e.sdp)}return new Promise(e=>{let f=!1,g,d;this._iceReady=!1;const A=()=>{a.removeEventListener("icecandidate",g),a.removeEventListener("icegatheringstatechange",d),f=!0,this._rtcReady=!0,this._iceReady=!0;const S={originator:"local",type:n,sdp:a.localDescription.sdp};Te.debug('emit "sdp"'),this.emit("sdp",S),e(S.sdp)};a.addEventListener("icecandidate",g=S=>{const R=S.candidate;R?this.emit("icecandidate",{candidate:R,ready:A}):f||A()}),a.addEventListener("icegatheringstatechange",d=()=>{a.iceGatheringState==="complete"&&!f&&A()})})})}_createDialog(n,r,a){const c=r==="UAS"?n.to_tag:n.from_tag,e=r==="UAS"?n.from_tag:n.to_tag,f=n.call_id+c+e;let g=this._earlyDialogs[f];if(a)return g?!0:(g=new $u(this,n,r,$u.C.STATUS_EARLY),g.error?(Te.debug(g.error),this._failed("remote",n,Ve.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[f]=g,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,g)return g.update(n,r),this._dialog=g,delete this._earlyDialogs[f],!0;const d=new $u(this,n,r);return d.error?(Te.debug(d.error),this._failed("remote",n,Ve.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(n){Te.debug("receiveReinvite()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,a={request:n,callback:void 0,reject:e.bind(this)};let c=!1;function e(g={}){c=!0;const d=g.status_code||403,A=g.reason_phrase||"",S=Jt.cloneArray(g.extraHeaders);if(this._status!==Ce.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);n.reply(d,A,S)}if(this.emit("reinvite",a),c)return;if(this._late_sdp=!1,!n.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(g=>{f.call(this,g)}).catch(()=>{n.reply(500)});return}if(r!=="application/sdp"){Te.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(g=>{this._status!==Ce.STATUS_TERMINATED&&f.call(this,g)}).catch(g=>{Te.warn(g)});function f(g){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,d),this._late_sdp&&(g=this._mangleOffer(g)),n.reply(200,null,d,g,()=>{this._status=Ce.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,g),this._setACKTimer()}),typeof a.callback=="function"&&a.callback()}}_receiveUpdate(n){Te.debug("receiveUpdate()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,a={request:n,callback:void 0,reject:e.bind(this)};let c=!1;function e(g={}){c=!0;const d=g.status_code||403,A=g.reason_phrase||"",S=Jt.cloneArray(g.extraHeaders);if(this._status!==Ce.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);n.reply(d,A,S)}if(this.emit("update",a),c)return;if(!n.body){f.call(this,null);return}if(r!=="application/sdp"){Te.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(g=>{this._status!==Ce.STATUS_TERMINATED&&f.call(this,g)}).catch(g=>{Te.warn(g)});function f(g){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,d),n.reply(200,null,d,g),typeof a.callback=="function"&&a.callback()}}_processInDialogSdpOffer(n){Te.debug("_processInDialogSdpOffer()");const r=n.parseSDP();let a=!1;for(const f of r.media){if(xu.indexOf(f.type)===-1)continue;const g=f.direction||r.direction||"sendrecv";if(g==="sendonly"||g==="inactive")a=!0;else{a=!1;break}}const c={originator:"remote",type:"offer",sdp:n.body};Te.debug('emit "sdp"'),this.emit("sdp",c);const e=new RTCSessionDescription({type:"offer",sdp:c.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(e).catch(f=>{throw n.reply(488),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',f),this.emit("peerconnection:setremotedescriptionfailed",f),f})}).then(()=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&a===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&a===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(f=>{throw n.reply(500),Te.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',f),f})}).catch(f=>{Te.warn("_processInDialogSdpOffer() failed [error: %o]",f)}),this._connectionPromiseQueue}_receiveRefer(n){if(Te.debug("receiveRefer()"),!n.refer_to){Te.debug("no Refer-To header field present in REFER"),n.reply(400);return}if(n.refer_to.uri.scheme!==Ve.SIP){Te.debug("Refer-To header field points to a non-SIP URI scheme"),n.reply(416);return}n.reply(202);const r=new yC(this,n.cseq);Te.debug('emit "refer"'),this.emit("refer",{request:n,accept:(e,f)=>{a.call(this,e,f)},reject:()=>{c.call(this)}});function a(e,f={}){if(e=typeof e=="function"?e:null,this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED)return!1;const g=new jh(this._ua);if(g.on("progress",({response:d})=>{r.notify(d.status_code,d.reason_phrase)}),g.on("accepted",({response:d})=>{r.notify(d.status_code,d.reason_phrase)}),g.on("_failed",({message:d,cause:A})=>{d?r.notify(d.status_code,d.reason_phrase):r.notify(487,A)}),n.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(n.refer_to.uri.getHeader("replaces"));f.extraHeaders=Jt.cloneArray(f.extraHeaders),f.extraHeaders.push(`Replaces: ${d}`)}g.connect(n.refer_to.uri.toAor(),f,e)}function c(){r.notify(603)}}_receiveNotify(n){switch(Te.debug("receiveNotify()"),n.event||n.reply(400),n.event.event){case"refer":{let r,a;if(n.event.params&&n.event.params.id)r=n.event.params.id,a=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)a=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{n.reply(400,"Missing event id parameter");return}if(!a){n.reply(481,"Subscription does not exist");return}a.receiveNotify(n),n.reply(200);break}default:n.reply(489)}}_receiveReplaces(n){Te.debug("receiveReplaces()");function r(c){if(this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED)return!1;const e=new jh(this._ua);e.on("confirmed",()=>{this.terminate()}),e.init_incoming(n,c)}function a(){Te.debug("Replaced INVITE rejected by the user"),n.reply(486)}this.emit("replaces",{request:n,accept:c=>{r.call(this,c)},reject:()=>{a.call(this)}})}_sendInitialRequest(n,r,a){const c=new gC(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});Promise.resolve().then(()=>{if(a)return a;if(n.audio||n.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(n).catch(e=>{throw this._status===Ce.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,Ve.causes.USER_DENIED_MEDIA_ACCESS),Te.warn('emit "getusermediafailed" [error:%o]',e),this.emit("getusermediafailed",e),e)})}).then(e=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=e,e&&e.getTracks().forEach(f=>{this._connection.addTrack(f,e)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(f=>{throw this._failed("local",null,Ve.causes.WEBRTC_ERROR),f})}).then(e=>{if(this._is_canceled||this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");this._request.body=e,this._status=Ce.STATUS_INVITE_SENT,Te.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),c.send()}).catch(e=>{this._status!==Ce.STATUS_TERMINATED&&Te.warn(e)})}_getDTMFRTPSender(){const n=this._connection.getSenders().find(r=>r.track&&r.track.kind==="audio");if(!(n&&n.dtmf)){Te.warn("sendDTMF() | no local audio track to send DTMF with");return}return n.dtmf}_receiveInviteResponse(n){if(Te.debug("receiveInviteResponse()"),this._dialog&&n.status_code>=200&&n.status_code<=299)if(this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.sendRequest(Ve.ACK);return}else{const r=new $u(this,n,"UAC");if(r.error!==void 0){Te.debug(r.error);return}this.sendRequest(Ve.ACK),this.sendRequest(Ve.BYE);return}if(this._is_canceled){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(n.status_code):this._status=Ce.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){Te.debug("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=Ce.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};Te.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",n)).catch(c=>{Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(this._status=Ce.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,Ve.causes.MISSING_SDP),this._failed("remote",n,Ve.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;const r={originator:"remote",type:"answer",sdp:n.body};Te.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(c=>this._connection.setLocalDescription(c)).catch(c=>{this._acceptAndTerminate(n,500,c.toString()),this._failed("local",n,Ve.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(a).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(Ve.ACK),this._confirmed("local",null)}).catch(c=>{this._acceptAndTerminate(n,488,"Not Acceptable Here"),this._failed("remote",n,Ve.causes.BAD_MEDIA_DESCRIPTION),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})});break}default:{const r=Jt.sipErrorCause(n.status_code);this._failed("remote",n,r)}}}_sendReinvite(n={}){Te.debug("sendReinvite()");const r=Jt.cloneArray(n.extraHeaders),a=Jt.cloneObject(n.eventHandlers),c=n.rtcOfferConstraints||this._rtcOfferConstraints||null;let e=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",c)).then(d=>{d=this._mangleOffer(d);const A={originator:"local",type:"offer",sdp:d};Te.debug('emit "sdp"'),this.emit("sdp",A),this.sendRequest(Ve.INVITE,{extraHeaders:r,body:d,eventHandlers:{onSuccessResponse:S=>{f.call(this,S),e=!0},onErrorResponse:S=>{g.call(this,S)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{g()});function f(d){if(this._status===Ce.STATUS_TERMINATED||(this.sendRequest(Ve.ACK),e))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){g.call(this);return}}else{g.call(this);return}const A={originator:"remote",type:"answer",sdp:d.body};Te.debug('emit "sdp"'),this.emit("sdp",A);const S=new RTCSessionDescription({type:"answer",sdp:A.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(S)).then(()=>{a.succeeded&&a.succeeded(d)}).catch(R=>{g.call(this),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),this.emit("peerconnection:setremotedescriptionfailed",R)})}function g(d){a.failed&&a.failed(d)}}_sendUpdate(n={}){Te.debug("sendUpdate()");const r=Jt.cloneArray(n.extraHeaders),a=Jt.cloneObject(n.eventHandlers),c=n.rtcOfferConstraints||this._rtcOfferConstraints||null,e=n.sdpOffer||!1;let f=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),e?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",c)).then(A=>{A=this._mangleOffer(A);const S={originator:"local",type:"offer",sdp:A};Te.debug('emit "sdp"'),this.emit("sdp",S),this.sendRequest(Ve.UPDATE,{extraHeaders:r,body:A,eventHandlers:{onSuccessResponse:R=>{g.call(this,R),f=!0},onErrorResponse:R=>{d.call(this,R)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{d.call(this)})):this.sendRequest(Ve.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:A=>{g.call(this,A)},onErrorResponse:A=>{d.call(this,A)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function g(A){if(this._status!==Ce.STATUS_TERMINATED&&!f)if(this._handleSessionTimersInIncomingResponse(A),e){if(A.body){if(!A.hasHeader("Content-Type")||A.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const S={originator:"remote",type:"answer",sdp:A.body};Te.debug('emit "sdp"'),this.emit("sdp",S);const R=new RTCSessionDescription({type:"answer",sdp:S.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(R)).then(()=>{a.succeeded&&a.succeeded(A)}).catch(N=>{d.call(this),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',N),this.emit("peerconnection:setremotedescriptionfailed",N)})}else a.succeeded&&a.succeeded(A)}function d(A){a.failed&&a.failed(A)}}_acceptAndTerminate(n,r,a){Te.debug("acceptAndTerminate()");const c=[];r&&(a=a||Ve.REASON_PHRASE[r]||"",c.push(`Reason: SIP ;cause=${r}; text="${a}"`)),(this._dialog||this._createDialog(n,"UAC"))&&(this.sendRequest(Ve.ACK),this.sendRequest(Ve.BYE,{extraHeaders:c})),this._status=Ce.STATUS_TERMINATED}_mangleOffer(n){if(!this._localHold&&!this._remoteHold)return n;if(n=X_.parse(n),this._localHold&&!this._remoteHold){Te.debug("mangleOffer() | me on hold, mangling offer");for(const r of n.media)xu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){Te.debug("mangleOffer() | both on hold, mangling offer");for(const r of n.media)xu.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){Te.debug("mangleOffer() | remote on hold, mangling offer");for(const r of n.media)xu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return X_.write(n)}_setLocalMediaStatus(){let n=!0,r=!0;(this._localHold||this._remoteHold)&&(n=!1,r=!1),this._audioMuted&&(n=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!n),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(n,r){if(!this._sessionTimers.enabled)return;let a;n.session_expires&&n.session_expires>=Ve.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,a=n.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,a="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${a}`),this._sessionTimers.refresher=a==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=Ve.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const n=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==Ce.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Te.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===Ve.UPDATE?this._sendUpdate():this._sendReinvite())},n*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==Ce.STATUS_TERMINATED&&(Te.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:Ve.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},n*1100)}_toggleMuteAudio(n){const r=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="audio");for(const a of r)a.track.enabled=!n}_toggleMuteVideo(n){const r=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="video");for(const a of r)a.track.enabled=!n}_newRTCSession(n,r){Te.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:n,session:this,request:r})}_connecting(n){Te.debug("session connecting"),Te.debug('emit "connecting"'),this.emit("connecting",{request:n})}_progress(n,r){Te.debug("session progress"),Te.debug('emit "progress"'),this.emit("progress",{originator:n,response:r||null})}_accepted(n,r){Te.debug("session accepted"),this._start_time=new Date,Te.debug('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){Te.debug("session confirmed"),this._is_confirmed=!0,Te.debug('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,a){Te.debug("session ended"),this._end_time=new Date,this._close(),Te.debug('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:a})}_failed(n,r,a){Te.debug("session failed"),Te.debug('emit "_failed"'),this.emit("_failed",{originator:n,message:r||null,cause:a}),this._close(),Te.debug('emit "failed"'),this.emit("failed",{originator:n,message:r||null,cause:a})}_onhold(n){Te.debug("session onhold"),this._setLocalMediaStatus(),Te.debug('emit "hold"'),this.emit("hold",{originator:n})}_onunhold(n){Te.debug("session onunhold"),this._setLocalMediaStatus(),Te.debug('emit "unhold"'),this.emit("unhold",{originator:n})}_onmute({audio:n,video:r}){Te.debug("session onmute"),this._setLocalMediaStatus(),Te.debug('emit "muted"'),this.emit("muted",{audio:n,video:r})}_onunmute({audio:n,video:r}){Te.debug("session onunmute"),this._setLocalMediaStatus(),Te.debug('emit "unmuted"'),this.emit("unmuted",{audio:n,video:r})}};const TC=Qt(ef),bC=Tn.EventEmitter,wC=mn,fd=bt,SC=On,ul=$n(),EC=to,tf=Ls,CC=Ms(),Ou=new wC("Message");var AC=class extends bC{constructor(o){super(),this._ua=o,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(o,n,r={}){const a=o;if(o===void 0||n===void 0)throw new TypeError("Not enough arguments");if(o=this._ua.normalizeTarget(o),!o)throw new TypeError(`Invalid target: ${a}`);const c=ul.cloneArray(r.extraHeaders),e=ul.cloneObject(r.eventHandlers),f=r.contentType||"text/plain",g={};r.fromUserName&&(g.from_uri=new CC("sip",r.fromUserName,this._ua.configuration.uri.host),c.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),r.fromDisplayName&&(g.from_display_name=r.fromDisplayName);for(const A in e)Object.prototype.hasOwnProperty.call(e,A)&&this.on(A,e[A]);c.push(`Content-Type: ${f}`),this._request=new SC.OutgoingRequest(fd.MESSAGE,o,this._ua,g,c),n&&(this._request.body=n);const d=new EC(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:A=>{this._receiveResponse(A)}});this._newMessage("local",this._request),d.send()}init_incoming(o){this._request=o,this._newMessage("remote",o),this._is_replied||(this._is_replied=!0,o.reply(200)),this._close()}accept(o={}){const n=ul.cloneArray(o.extraHeaders),r=o.body;if(this._direction!=="incoming")throw new tf.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,n,r)}reject(o={}){const n=o.status_code||480,r=o.reason_phrase,a=ul.cloneArray(o.extraHeaders),c=o.body;if(this._direction!=="incoming")throw new tf.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,r,a,c)}_receiveResponse(o){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):this._succeeded("remote",o);break;default:{const n=ul.sipErrorCause(o.status_code);this._failed("remote",o,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,fd.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,fd.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(o,n){o==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):o==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newMessage(this,{originator:o,message:this,request:n})}_failed(o,n,r){Ou.debug("MESSAGE failed"),this._close(),Ou.debug('emit "failed"'),this.emit("failed",{originator:o,response:n||null,cause:r})}_succeeded(o,n){Ou.debug("MESSAGE succeeded"),this._close(),Ou.debug('emit "succeeded"'),this.emit("succeeded",{originator:o,response:n})}};const IC=Tn.EventEmitter,RC=mn,md=bt,$C=On,cl=$n(),xC=to,nf=Ls,ku=new RC("Options");var OC=class extends IC{constructor(o){super(),this._ua=o,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(o,n,r={}){const a=o;if(o===void 0)throw new TypeError("A target is required for OPTIONS");if(o=this._ua.normalizeTarget(o),!o)throw new TypeError(`Invalid target: ${a}`);const c=cl.cloneArray(r.extraHeaders),e=cl.cloneObject(r.eventHandlers),f=r.contentType||"application/sdp";for(const d in e)Object.prototype.hasOwnProperty.call(e,d)&&this.on(d,e[d]);c.push(`Content-Type: ${f}`),this._request=new $C.OutgoingRequest(md.OPTIONS,o,this._ua,null,c),n&&(this._request.body=n);const g=new xC(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:d=>{this._receiveResponse(d)}});this._newOptions("local",this._request),g.send()}init_incoming(o){this._request=o,this._newOptions("remote",o),this._is_replied||(this._is_replied=!0,o.reply(200)),this._close()}accept(o={}){const n=cl.cloneArray(o.extraHeaders),r=o.body;if(this._direction!=="incoming")throw new nf.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,n,r)}reject(o={}){const n=o.status_code||480,r=o.reason_phrase,a=cl.cloneArray(o.extraHeaders),c=o.body;if(this._direction!=="incoming")throw new nf.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,r,a,c)}_receiveResponse(o){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):this._succeeded("remote",o);break;default:{const n=cl.sipErrorCause(o.status_code);this._failed("remote",o,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,md.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,md.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(o,n){o==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):o==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newOptions(this,{originator:o,message:this,request:n})}_failed(o,n,r){ku.debug("OPTIONS failed"),this._close(),ku.debug('emit "failed"'),this.emit("failed",{originator:o,response:n||null,cause:r})}_succeeded(o,n){ku.debug("OPTIONS succeeded"),this._close(),ku.debug('emit "succeeded"'),this.emit("succeeded",{originator:o,response:n})}},gd={};const kC=mn,yd=$n(),DC=Hr(),dl=new kC("Socket");gd.isSocket=o=>{if(Array.isArray(o))return!1;if(typeof o>"u")return dl.warn("undefined JsSIP.Socket instance"),!1;try{if(!yd.isString(o.url))throw dl.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!yd.isString(o.via_transport))throw dl.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(DC.parse(o.sip_uri,"SIP_URI")===-1)throw dl.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(n=>{if(!yd.isFunction(o[n]))throw dl.warn(`missing or invalid JsSIP.Socket method: ${n}`),new Error(`Missing or invalid JsSIP.Socket method: ${n}`)})}catch{return!1}return!0};const NC=mn,MC=gd,rf=bt,sr=new NC("Transport"),Rr={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:rf.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:rf.CONNECTION_RECOVERY_MAX_INTERVAL}};var sf=class{constructor(o,n=Rr.recovery_options){sr.debug("new()"),this.status=Rr.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(r){sr.warn(`cannot use TextDecoder: ${r}`)}if(typeof o>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");o instanceof Array||(o=[o]),o.forEach(function(r){if(!MC.isSocket(r.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(r.weight&&!Number(r.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:r.socket,weight:r.weight||0,status:Rr.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(sr.debug("connect()"),this.isConnected()){sr.debug("Transport is already connected");return}else if(this.isConnecting()){sr.debug("Transport is connecting");return}this.close_requested=!1,this.status=Rr.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(){sr.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=Rr.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(o){if(sr.debug("send()"),!this.isConnected())return sr.warn("unable to send message, transport is not connected"),!1;const n=o.toString();return sr.debug(`sending message:
|
|
114
|
+
`);a.length>=1&&n.test(a[0])&&(this._tone=a[0].replace(n,"$2")),a.length>=2&&r.test(a[1])&&(this._duration=parseInt(a[1].replace(r,"$2"),10))}this._duration||(this._duration=B_.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:o}):tC.debug("invalid INFO DTMF received, discarded")}},hd.exports.C=B_;var V_=hd.exports;const nC=Qt(V_),rC=Tn.EventEmitter,sC=bt,iC=Ls,aC=$n();var j_=class extends rC{constructor(o){super(),this._session=o,this._direction=null,this._contentType=null,this._body=null}get contentType(){return this._contentType}get body(){return this._body}send(o,n,r={}){if(this._direction="outgoing",o===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 iC.InvalidStateError(this._session.status);this._contentType=o,this._body=n;const a=aC.cloneArray(r.extraHeaders);a.push(`Content-Type: ${o}`),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(sC.INFO,{extraHeaders:a,eventHandlers:{onSuccessResponse:c=>{this.emit("succeeded",{originator:"remote",response:c})},onErrorResponse:c=>{this.emit("failed",{originator:"remote",response:c})},onTransportError:()=>{this._session.onTransportError()},onRequestTimeout:()=>{this._session.onRequestTimeout()},onDialogError:()=>{this._session.onDialogError()}},body:n})}init_incoming(o){this._direction="incoming",this.request=o,o.reply(200),this._contentType=o.hasHeader("Content-Type")?o.getHeader("Content-Type").toLowerCase():void 0,this._body=o.body,this._session.newInfo({originator:"remote",info:this,request:o})}};const pd=Qt(j_),oC=mn,G_=bt,lC=new oC("RTCSession:ReferNotifier"),_d={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300};var W_=class{constructor(o,n,r){this._session=o,this._id=n,this._expires=r||_d.expires,this._active=!0,this.notify(100)}notify(o,n){if(lC.debug("notify()"),this._active===!1)return;n=n||G_.REASON_PHRASE[o]||"";let r;o>=200?r="terminated;reason=noresource":r=`active;expires=${this._expires}`,this._session.sendRequest(G_.NOTIFY,{extraHeaders:[`Event: ${_d.event_type};id=${this._id}`,`Subscription-State: ${r}`,`Content-Type: ${_d.body_type}`],body:`SIP/2.0 ${o} ${n}`,eventHandlers:{onErrorResponse(){this._active=!1}}})}};const uC=Qt(W_),cC=Tn.EventEmitter,dC=mn,ol=bt,hC=Hr(),K_=$n(),ya=new dC("RTCSession:ReferSubscriber");var Y_=class extends cC{constructor(o){super(),this._id=null,this._session=o}get id(){return this._id}sendRefer(o,n={}){ya.debug("sendRefer()");const r=K_.cloneArray(n.extraHeaders),a=K_.cloneObject(n.eventHandlers);for(const g in a)Object.prototype.hasOwnProperty.call(a,g)&&this.on(g,a[g]);let c=null;n.replaces&&(c=n.replaces._request.call_id,c+=`;to-tag=${n.replaces._to_tag}`,c+=`;from-tag=${n.replaces._from_tag}`,c=encodeURIComponent(c));const e=`Refer-To: <${o}${c?`?Replaces=${c}`:""}>`;if(r.push(e),!r.some(g=>g.toLowerCase().startsWith("referred-by:"))){const g=`Referred-By: <${this._session._ua._configuration.uri._scheme}:${this._session._ua._configuration.uri._user}@${this._session._ua._configuration.uri._host}>`;r.push(g)}r.push(`Contact: ${this._session.contact}`);const _=this._session.sendRequest(ol.REFER,{extraHeaders:r,eventHandlers:{onSuccessResponse:g=>{this._requestSucceeded(g)},onErrorResponse:g=>{this._requestFailed(g,ol.causes.REJECTED)},onTransportError:()=>{this._requestFailed(null,ol.causes.CONNECTION_ERROR)},onRequestTimeout:()=>{this._requestFailed(null,ol.causes.REQUEST_TIMEOUT)},onDialogError:()=>{this._requestFailed(null,ol.causes.DIALOG_ERROR)}}});this._id=_.cseq}receiveNotify(o){if(ya.debug("receiveNotify()"),!o.body)return;const n=hC.parse(o.body.trim().split(`\r
|
|
115
|
+
`,1)[0],"Status_Line");if(n===-1){ya.debug(`receiveNotify() | error parsing NOTIFY body: "${o.body}"`);return}switch(!0){case/^100$/.test(n.status_code):this.emit("trying",{request:o,status_line:n});break;case/^1[0-9]{2}$/.test(n.status_code):this.emit("progress",{request:o,status_line:n});break;case/^2[0-9]{2}$/.test(n.status_code):this.emit("accepted",{request:o,status_line:n});break;default:this.emit("failed",{request:o,status_line:n});break}}_requestSucceeded(o){ya.debug("REFER succeeded"),ya.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:o})}_requestFailed(o,n){ya.debug("REFER failed"),ya.debug('emit "requestFailed"'),this.emit("requestFailed",{response:o||null,cause:n})}};const pC=Qt(Y_),_C=Tn.EventEmitter,X_=nr,fC=mn,Ve=bt,va=Ls,J_=eo,Jt=$n(),ll=sd,mC=On,$u=z_,gC=to,fr=V_,Q_=j_,yC=W_,vC=Y_,Z_=Ms(),Te=new fC("RTCSession"),Ce={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},xu=["audio","video"];var ef=class jh extends _C{static get C(){return Ce}constructor(n){Te.debug("new"),super(),this._id=null,this._ua=n,this._status=Ce.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:Ve.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return Ce}get causes(){return Ve.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(n){this._data=n}get status(){return this._status}isInProgress(){switch(this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:case Ce.STATUS_INVITE_RECEIVED:case Ce.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case Ce.STATUS_ANSWERED:case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case Ce.STATUS_CANCELED:case Ce.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(n,r={},a){Te.debug("connect()");const c=n,e=Jt.cloneObject(r.eventHandlers),_=Jt.cloneArray(r.extraHeaders),g=Jt.cloneObject(r.mediaConstraints,{audio:!0,video:!0}),d=r.mediaStream||null,A=Jt.cloneObject(r.pcConfig,{iceServers:[]}),S=r.rtcConstraints||null,R=r.rtcOfferConstraints||null;if(this._rtcOfferConstraints=R,this._rtcAnswerConstraints=r.rtcAnswerConstraints||null,this._data=r.data||this._data,n===void 0)throw new TypeError("Not enough arguments");if(this._status!==Ce.STATUS_NULL)throw new va.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new va.NotSupportedError("WebRTC not supported");if(n=this._ua.normalizeTarget(n),!n)throw new TypeError(`Invalid target: ${c}`);this._sessionTimers.enabled&&Jt.isDecimal(r.sessionTimersExpires)&&(r.sessionTimersExpires>=Ve.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=r.sessionTimersExpires:this._sessionTimers.defaultExpires=Ve.SESSION_EXPIRES);for(const W in e)Object.prototype.hasOwnProperty.call(e,W)&&this.on(W,e[W]);this._from_tag=Jt.newTag();const N=r.anonymous||!1,H={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:N,outbound:!0}),N?(H.from_display_name="Anonymous",H.from_uri=new Z_("sip","anonymous","anonymous.invalid"),_.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),_.push("Privacy: id")):r.fromUserName&&(H.from_uri=new Z_("sip",r.fromUserName,this._ua.configuration.uri.host),_.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),r.fromDisplayName&&(H.from_display_name=r.fromDisplayName),_.push(`Contact: ${this._contact}`),_.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&_.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new mC.InitialOutgoingInviteRequest(n,this._ua,H,_),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(A,S),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,a&&a(this),this._newRTCSession("local",this._request),this._sendInitialRequest(g,R,d)}init_incoming(n,r){Te.debug("init_incoming()");let a;const c=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&c!=="application/sdp"){n.reply(415);return}if(this._status=Ce.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(a=n.getHeader("expires")*1e3),n.to_tag=Jt.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ce.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),this._failed("local",null,Ve.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),this._failed("system",null,Ve.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),this._newRTCSession("remote",n),this._status!==Ce.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(n={}){Te.debug("answer()");const r=this._request,a=Jt.cloneArray(n.extraHeaders),c=Jt.cloneObject(n.mediaConstraints),e=n.mediaStream||null,_=Jt.cloneObject(n.pcConfig,{iceServers:[]}),g=n.rtcConstraints||null,d=n.rtcAnswerConstraints||null,A=Jt.cloneObject(n.rtcOfferConstraints);let S,R=!1,N=!1,H=!1,W=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=n.rtcOfferConstraints||null,this._data=n.data||this._data,this._direction!=="incoming")throw new va.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==Ce.STATUS_WAITING_FOR_ANSWER)throw new va.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Jt.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=Ve.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=Ve.SESSION_EXPIRES),this._status=Ce.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),a.unshift(`Contact: ${this._contact}`);const G=r.parseSDP();Array.isArray(G.media)||(G.media=[G.media]);for(const K of G.media)K.type==="audio"&&(R=!0,(!K.direction||K.direction==="sendrecv")&&(H=!0)),K.type==="video"&&(N=!0,(!K.direction||K.direction==="sendrecv")&&(W=!0));if(e&&c.audio===!1){S=e.getAudioTracks();for(const K of S)e.removeTrack(K)}if(e&&c.video===!1){S=e.getVideoTracks();for(const K of S)e.removeTrack(K)}!e&&c.audio===void 0&&(c.audio=H),!e&&c.video===void 0&&(c.video=W),!e&&!R&&!A.offerToReceiveAudio&&(c.audio=!1),!e&&!N&&!A.offerToReceiveVideo&&(c.video=!1),this._createRTCConnection(_,g),Promise.resolve().then(()=>{if(e)return e;if(c.audio||c.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(c).catch(K=>{throw this._status===Ce.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,Ve.causes.USER_DENIED_MEDIA_ACCESS),Te.warn('emit "getusermediafailed" [error:%o]',K),this.emit("getusermediafailed",K),new Error("getUserMedia() failed"))})}).then(K=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=K,K&&K.getTracks().forEach(ae=>{this._connection.addTrack(ae,K)})}).then(()=>{if(this._late_sdp)return;const K={originator:"remote",type:"offer",sdp:r.body};Te.debug('emit "sdp"'),this.emit("sdp",K);const ae=new RTCSessionDescription({type:"offer",sdp:K.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(ae)).catch(ee=>{throw r.reply(488),this._failed("system",null,Ve.causes.WEBRTC_ERROR),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',ee),this.emit("peerconnection:setremotedescriptionfailed",ee),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",d).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(K=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,a),r.reply(200,null,a,K,()=>{this._status=Ce.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,K),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,Ve.causes.CONNECTION_ERROR)})}).catch(K=>{this._status!==Ce.STATUS_TERMINATED&&Te.warn(K)})}terminate(n={}){Te.debug("terminate()");const r=n.cause||Ve.causes.BYE,a=Jt.cloneArray(n.extraHeaders),c=n.body;let e,_=n.status_code,g=n.reason_phrase;if(this._status===Ce.STATUS_TERMINATED)throw new va.InvalidStateError(this._status);switch(this._status){case Ce.STATUS_NULL:case Ce.STATUS_INVITE_SENT:case Ce.STATUS_1XX_RECEIVED:if(Te.debug("canceling session"),_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);_&&(g=g||Ve.REASON_PHRASE[_]||"",e=`SIP ;cause=${_} ;text="${g}"`),this._status===Ce.STATUS_NULL||this._status===Ce.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===Ce.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=Ce.STATUS_CANCELED,this._failed("local",null,Ve.causes.CANCELED);break;case Ce.STATUS_WAITING_FOR_ANSWER:case Ce.STATUS_ANSWERED:if(Te.debug("rejecting session"),_=_||480,_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);this._request.reply(_,g,a,c),this._failed("local",null,Ve.causes.REJECTED);break;case Ce.STATUS_WAITING_FOR_ACK:case Ce.STATUS_CONFIRMED:if(Te.debug("terminating session"),g=n.reason_phrase||Ve.REASON_PHRASE[_]||"",_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);if(_&&a.push(`Reason: SIP ;cause=${_}; text="${g}"`),this._status===Ce.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==J_.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:A})=>{A===Ve.ACK&&(this.sendRequest(Ve.BYE,{extraHeaders:a,body:c}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===J_.C.STATUS_TERMINATED&&(this.sendRequest(Ve.BYE,{extraHeaders:a,body:c}),d.terminate())}),this._ended("local",null,r),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(Ve.BYE,{extraHeaders:a,body:c}),this._ended("local",null,r)}}sendDTMF(n,r={}){Te.debug("sendDTMF() | tones: %s",n);let a=0,c=r.duration||null,e=r.interToneGap||null;const _=r.transportType||Ve.DTMF_TRANSPORT.INFO;if(n===void 0)throw new TypeError("Not enough arguments");if(this._status!==Ce.STATUS_CONFIRMED&&this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_1XX_RECEIVED)throw new va.InvalidStateError(this._status);if(_!==Ve.DTMF_TRANSPORT.INFO&&_!==Ve.DTMF_TRANSPORT.RFC2833)throw new TypeError(`invalid transportType: ${_}`);if(typeof n=="number"&&(n=n.toString()),!n||typeof n!="string"||!n.match(/^[0-9A-DR#*,]+$/i))throw new TypeError(`Invalid tones: ${n}`);if(c&&!Jt.isDecimal(c))throw new TypeError(`Invalid tone duration: ${c}`);if(c?c<fr.C.MIN_DURATION?(Te.debug(`"duration" value is lower than the minimum allowed, setting it to ${fr.C.MIN_DURATION} milliseconds`),c=fr.C.MIN_DURATION):c>fr.C.MAX_DURATION?(Te.debug(`"duration" value is greater than the maximum allowed, setting it to ${fr.C.MAX_DURATION} milliseconds`),c=fr.C.MAX_DURATION):c=Math.abs(c):c=fr.C.DEFAULT_DURATION,r.duration=c,e&&!Jt.isDecimal(e))throw new TypeError(`Invalid interToneGap: ${e}`);if(e?e<fr.C.MIN_INTER_TONE_GAP?(Te.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${fr.C.MIN_INTER_TONE_GAP} milliseconds`),e=fr.C.MIN_INTER_TONE_GAP):e=Math.abs(e):e=fr.C.DEFAULT_INTER_TONE_GAP,_===Ve.DTMF_TRANSPORT.RFC2833){const d=this._getDTMFRTPSender();d&&(n=d.toneBuffer+n,d.insertDTMF(n,c,e));return}if(this._tones){this._tones+=n;return}this._tones=n,g.call(this);function g(){let d;if(this._status===Ce.STATUS_TERMINATED||!this._tones||a>=this._tones.length){this._tones=null;return}const A=this._tones[a];if(a+=1,A===",")d=2e3;else{const S=new fr(this);r.eventHandlers={onFailed:()=>{this._tones=null}},S.send(A,r),d=c+e}setTimeout(g.bind(this),d)}}sendInfo(n,r,a={}){if(Te.debug("sendInfo()"),this._status!==Ce.STATUS_CONFIRMED&&this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_1XX_RECEIVED)throw new va.InvalidStateError(this._status);new Q_(this).send(n,r,a)}mute(n={audio:!0,video:!1}){Te.debug("mute()");let r=!1,a=!1;this._audioMuted===!1&&n.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&n.video&&(a=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||a===!0)&&this._onmute({audio:r,video:a})}unmute(n={audio:!0,video:!0}){Te.debug("unmute()");let r=!1,a=!1;this._audioMuted===!0&&n.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&n.video&&(a=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||a===!0)&&this._onunmute({audio:r,video:a})}hold(n={},r){if(Te.debug("hold()"),this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ve.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:n.extraHeaders}),!0}unhold(n={},r){if(Te.debug("unhold()"),this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ve.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:n.extraHeaders}),!0}renegotiate(n={},r){Te.debug("renegotiate()");const a=n.rtcOfferConstraints||null;if(this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const c={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ve.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:c,rtcOfferConstraints:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:c,rtcOfferConstraints:a,extraHeaders:n.extraHeaders}),!0}refer(n,r){Te.debug("refer()");const a=n;if(this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED)return!1;if(n=this._ua.normalizeTarget(n),!n)throw new TypeError(`Invalid target: ${a}`);const c=new vC(this);c.sendRefer(n,r);const e=c.id;return this._referSubscribers[e]=c,c.on("requestFailed",()=>{delete this._referSubscribers[e]}),c.on("accepted",()=>{delete this._referSubscribers[e]}),c.on("failed",()=>{delete this._referSubscribers[e]}),c}sendRequest(n,r){return Te.debug("sendRequest()"),this._dialog.sendRequest(n,r)}receiveRequest(n){if(Te.debug("receiveRequest()"),n.method===Ve.CANCEL)(this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED)&&(this._status=Ce.STATUS_CANCELED,this._request.reply(487),this._failed("remote",n,Ve.causes.CANCELED));else switch(n.method){case Ve.ACK:if(this._status!==Ce.STATUS_WAITING_FOR_ACK)return;if(this._status=Ce.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:Ve.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};Te.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(c=>{this.terminate({cause:Ve.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})}else this._is_confirmed||this._confirmed("remote",n);break;case Ve.BYE:this._status===Ce.STATUS_CONFIRMED||this._status===Ce.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,Ve.causes.BYE)):this._status===Ce.STATUS_INVITE_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,Ve.causes.BYE)):n.reply(403,"Wrong Status");break;case Ve.INVITE:this._status===Ce.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case Ve.INFO:if(this._status===Ce.STATUS_1XX_RECEIVED||this._status===Ce.STATUS_WAITING_FOR_ANSWER||this._status===Ce.STATUS_ANSWERED||this._status===Ce.STATUS_WAITING_FOR_ACK||this._status===Ce.STATUS_CONFIRMED){const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new fr(this).init_incoming(n):r!==void 0?new Q_(this).init_incoming(n):n.reply(415)}else n.reply(403,"Wrong Status");break;case Ve.UPDATE:this._status===Ce.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case Ve.REFER:this._status===Ce.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case Ve.NOTIFY:this._status===Ce.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){Te.warn("onTransportError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ve.causes.CONNECTION_ERROR,cause:Ve.causes.CONNECTION_ERROR})}onRequestTimeout(){Te.warn("onRequestTimeout()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Ve.causes.REQUEST_TIMEOUT,cause:Ve.causes.REQUEST_TIMEOUT})}onDialogError(){Te.warn("onDialogError()"),this._status!==Ce.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ve.causes.DIALOG_ERROR,cause:Ve.causes.DIALOG_ERROR})}newDTMF(n){Te.debug("newDTMF()"),this.emit("newDTMF",n)}newInfo(n){Te.debug("newInfo()"),this.emit("newInfo",n)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Te.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Te.debug("_isReadyToReOffer() | session not established yet"),!1):(Te.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Te.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Te.debug("close() | closing local MediaStream"),Jt.closeMediaStream(this._localMediaStream)),this._status!==Ce.STATUS_TERMINATED){if(this._status=Ce.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){Te.warn("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(n,r){let a=ll.T1;function c(){this._status===Ce.STATUS_WAITING_FOR_ACK&&(n.reply(200,null,[`Contact: ${this._contact}`],r),a<ll.T2&&(a=a*2,a>ll.T2&&(a=ll.T2)),this._timers.invite2xxTimer=setTimeout(c.bind(this),a))}this._timers.invite2xxTimer=setTimeout(c.bind(this),a)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===Ce.STATUS_WAITING_FOR_ACK&&(Te.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(Ve.BYE),this._ended("remote",null,Ve.causes.NO_ACK))},ll.TIMER_H)}_createRTCConnection(n,r){this._connection=new RTCPeerConnection(n,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:Ve.causes.RTP_TIMEOUT,status_code:408,reason_phrase:Ve.causes.RTP_TIMEOUT})}),Te.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(n,r){if(Te.debug("createLocalDescription()"),n!=="offer"&&n!=="answer")throw new Error(`createLocalDescription() | invalid type "${n}"`);const a=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>n==="offer"?a.createOffer(r).catch(c=>(Te.warn('emit "peerconnection:createofferfailed" [error:%o]',c),this.emit("peerconnection:createofferfailed",c),Promise.reject(c))):a.createAnswer(r).catch(c=>(Te.warn('emit "peerconnection:createanswerfailed" [error:%o]',c),this.emit("peerconnection:createanswerfailed",c),Promise.reject(c)))).then(c=>a.setLocalDescription(c).catch(e=>(this._rtcReady=!0,Te.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',e),this.emit("peerconnection:setlocaldescriptionfailed",e),Promise.reject(e)))).then(()=>{const c=r&&r.iceRestart;if(a.iceGatheringState==="complete"&&!c||a.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const e={originator:"local",type:n,sdp:a.localDescription.sdp};return Te.debug('emit "sdp"'),this.emit("sdp",e),Promise.resolve(e.sdp)}return new Promise(e=>{let _=!1,g,d;this._iceReady=!1;const A=()=>{a.removeEventListener("icecandidate",g),a.removeEventListener("icegatheringstatechange",d),_=!0,this._rtcReady=!0,this._iceReady=!0;const S={originator:"local",type:n,sdp:a.localDescription.sdp};Te.debug('emit "sdp"'),this.emit("sdp",S),e(S.sdp)};a.addEventListener("icecandidate",g=S=>{const R=S.candidate;R?this.emit("icecandidate",{candidate:R,ready:A}):_||A()}),a.addEventListener("icegatheringstatechange",d=()=>{a.iceGatheringState==="complete"&&!_&&A()})})})}_createDialog(n,r,a){const c=r==="UAS"?n.to_tag:n.from_tag,e=r==="UAS"?n.from_tag:n.to_tag,_=n.call_id+c+e;let g=this._earlyDialogs[_];if(a)return g?!0:(g=new $u(this,n,r,$u.C.STATUS_EARLY),g.error?(Te.debug(g.error),this._failed("remote",n,Ve.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[_]=g,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,g)return g.update(n,r),this._dialog=g,delete this._earlyDialogs[_],!0;const d=new $u(this,n,r);return d.error?(Te.debug(d.error),this._failed("remote",n,Ve.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(n){Te.debug("receiveReinvite()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,a={request:n,callback:void 0,reject:e.bind(this)};let c=!1;function e(g={}){c=!0;const d=g.status_code||403,A=g.reason_phrase||"",S=Jt.cloneArray(g.extraHeaders);if(this._status!==Ce.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);n.reply(d,A,S)}if(this.emit("reinvite",a),c)return;if(this._late_sdp=!1,!n.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(g=>{_.call(this,g)}).catch(()=>{n.reply(500)});return}if(r!=="application/sdp"){Te.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(g=>{this._status!==Ce.STATUS_TERMINATED&&_.call(this,g)}).catch(g=>{Te.warn(g)});function _(g){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,d),this._late_sdp&&(g=this._mangleOffer(g)),n.reply(200,null,d,g,()=>{this._status=Ce.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,g),this._setACKTimer()}),typeof a.callback=="function"&&a.callback()}}_receiveUpdate(n){Te.debug("receiveUpdate()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,a={request:n,callback:void 0,reject:e.bind(this)};let c=!1;function e(g={}){c=!0;const d=g.status_code||403,A=g.reason_phrase||"",S=Jt.cloneArray(g.extraHeaders);if(this._status!==Ce.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);n.reply(d,A,S)}if(this.emit("update",a),c)return;if(!n.body){_.call(this,null);return}if(r!=="application/sdp"){Te.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(g=>{this._status!==Ce.STATUS_TERMINATED&&_.call(this,g)}).catch(g=>{Te.warn(g)});function _(g){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,d),n.reply(200,null,d,g),typeof a.callback=="function"&&a.callback()}}_processInDialogSdpOffer(n){Te.debug("_processInDialogSdpOffer()");const r=n.parseSDP();let a=!1;for(const _ of r.media){if(xu.indexOf(_.type)===-1)continue;const g=_.direction||r.direction||"sendrecv";if(g==="sendonly"||g==="inactive")a=!0;else{a=!1;break}}const c={originator:"remote",type:"offer",sdp:n.body};Te.debug('emit "sdp"'),this.emit("sdp",c);const e=new RTCSessionDescription({type:"offer",sdp:c.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(e).catch(_=>{throw n.reply(488),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',_),this.emit("peerconnection:setremotedescriptionfailed",_),_})}).then(()=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&a===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&a===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(_=>{throw n.reply(500),Te.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',_),_})}).catch(_=>{Te.warn("_processInDialogSdpOffer() failed [error: %o]",_)}),this._connectionPromiseQueue}_receiveRefer(n){if(Te.debug("receiveRefer()"),!n.refer_to){Te.debug("no Refer-To header field present in REFER"),n.reply(400);return}if(n.refer_to.uri.scheme!==Ve.SIP){Te.debug("Refer-To header field points to a non-SIP URI scheme"),n.reply(416);return}n.reply(202);const r=new yC(this,n.cseq);Te.debug('emit "refer"'),this.emit("refer",{request:n,accept:(e,_)=>{a.call(this,e,_)},reject:()=>{c.call(this)}});function a(e,_={}){if(e=typeof e=="function"?e:null,this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED)return!1;const g=new jh(this._ua);if(g.on("progress",({response:d})=>{r.notify(d.status_code,d.reason_phrase)}),g.on("accepted",({response:d})=>{r.notify(d.status_code,d.reason_phrase)}),g.on("_failed",({message:d,cause:A})=>{d?r.notify(d.status_code,d.reason_phrase):r.notify(487,A)}),n.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(n.refer_to.uri.getHeader("replaces"));_.extraHeaders=Jt.cloneArray(_.extraHeaders),_.extraHeaders.push(`Replaces: ${d}`)}g.connect(n.refer_to.uri.toAor(),_,e)}function c(){r.notify(603)}}_receiveNotify(n){switch(Te.debug("receiveNotify()"),n.event||n.reply(400),n.event.event){case"refer":{let r,a;if(n.event.params&&n.event.params.id)r=n.event.params.id,a=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)a=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{n.reply(400,"Missing event id parameter");return}if(!a){n.reply(481,"Subscription does not exist");return}a.receiveNotify(n),n.reply(200);break}default:n.reply(489)}}_receiveReplaces(n){Te.debug("receiveReplaces()");function r(c){if(this._status!==Ce.STATUS_WAITING_FOR_ACK&&this._status!==Ce.STATUS_CONFIRMED)return!1;const e=new jh(this._ua);e.on("confirmed",()=>{this.terminate()}),e.init_incoming(n,c)}function a(){Te.debug("Replaced INVITE rejected by the user"),n.reply(486)}this.emit("replaces",{request:n,accept:c=>{r.call(this,c)},reject:()=>{a.call(this)}})}_sendInitialRequest(n,r,a){const c=new gC(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});Promise.resolve().then(()=>{if(a)return a;if(n.audio||n.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(n).catch(e=>{throw this._status===Ce.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,Ve.causes.USER_DENIED_MEDIA_ACCESS),Te.warn('emit "getusermediafailed" [error:%o]',e),this.emit("getusermediafailed",e),e)})}).then(e=>{if(this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=e,e&&e.getTracks().forEach(_=>{this._connection.addTrack(_,e)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(_=>{throw this._failed("local",null,Ve.causes.WEBRTC_ERROR),_})}).then(e=>{if(this._is_canceled||this._status===Ce.STATUS_TERMINATED)throw new Error("terminated");this._request.body=e,this._status=Ce.STATUS_INVITE_SENT,Te.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),c.send()}).catch(e=>{this._status!==Ce.STATUS_TERMINATED&&Te.warn(e)})}_getDTMFRTPSender(){const n=this._connection.getSenders().find(r=>r.track&&r.track.kind==="audio");if(!(n&&n.dtmf)){Te.warn("sendDTMF() | no local audio track to send DTMF with");return}return n.dtmf}_receiveInviteResponse(n){if(Te.debug("receiveInviteResponse()"),this._dialog&&n.status_code>=200&&n.status_code<=299)if(this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.sendRequest(Ve.ACK);return}else{const r=new $u(this,n,"UAC");if(r.error!==void 0){Te.debug(r.error);return}this.sendRequest(Ve.ACK),this.sendRequest(Ve.BYE);return}if(this._is_canceled){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==Ce.STATUS_INVITE_SENT&&this._status!==Ce.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(n.status_code):this._status=Ce.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){Te.debug("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=Ce.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};Te.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",n)).catch(c=>{Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(this._status=Ce.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,Ve.causes.MISSING_SDP),this._failed("remote",n,Ve.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;const r={originator:"remote",type:"answer",sdp:n.body};Te.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(c=>this._connection.setLocalDescription(c)).catch(c=>{this._acceptAndTerminate(n,500,c.toString()),this._failed("local",n,Ve.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(a).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(Ve.ACK),this._confirmed("local",null)}).catch(c=>{this._acceptAndTerminate(n,488,"Not Acceptable Here"),this._failed("remote",n,Ve.causes.BAD_MEDIA_DESCRIPTION),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})});break}default:{const r=Jt.sipErrorCause(n.status_code);this._failed("remote",n,r)}}}_sendReinvite(n={}){Te.debug("sendReinvite()");const r=Jt.cloneArray(n.extraHeaders),a=Jt.cloneObject(n.eventHandlers),c=n.rtcOfferConstraints||this._rtcOfferConstraints||null;let e=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",c)).then(d=>{d=this._mangleOffer(d);const A={originator:"local",type:"offer",sdp:d};Te.debug('emit "sdp"'),this.emit("sdp",A),this.sendRequest(Ve.INVITE,{extraHeaders:r,body:d,eventHandlers:{onSuccessResponse:S=>{_.call(this,S),e=!0},onErrorResponse:S=>{g.call(this,S)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{g()});function _(d){if(this._status===Ce.STATUS_TERMINATED||(this.sendRequest(Ve.ACK),e))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){g.call(this);return}}else{g.call(this);return}const A={originator:"remote",type:"answer",sdp:d.body};Te.debug('emit "sdp"'),this.emit("sdp",A);const S=new RTCSessionDescription({type:"answer",sdp:A.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(S)).then(()=>{a.succeeded&&a.succeeded(d)}).catch(R=>{g.call(this),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),this.emit("peerconnection:setremotedescriptionfailed",R)})}function g(d){a.failed&&a.failed(d)}}_sendUpdate(n={}){Te.debug("sendUpdate()");const r=Jt.cloneArray(n.extraHeaders),a=Jt.cloneObject(n.eventHandlers),c=n.rtcOfferConstraints||this._rtcOfferConstraints||null,e=n.sdpOffer||!1;let _=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),e?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",c)).then(A=>{A=this._mangleOffer(A);const S={originator:"local",type:"offer",sdp:A};Te.debug('emit "sdp"'),this.emit("sdp",S),this.sendRequest(Ve.UPDATE,{extraHeaders:r,body:A,eventHandlers:{onSuccessResponse:R=>{g.call(this,R),_=!0},onErrorResponse:R=>{d.call(this,R)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{d.call(this)})):this.sendRequest(Ve.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:A=>{g.call(this,A)},onErrorResponse:A=>{d.call(this,A)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function g(A){if(this._status!==Ce.STATUS_TERMINATED&&!_)if(this._handleSessionTimersInIncomingResponse(A),e){if(A.body){if(!A.hasHeader("Content-Type")||A.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const S={originator:"remote",type:"answer",sdp:A.body};Te.debug('emit "sdp"'),this.emit("sdp",S);const R=new RTCSessionDescription({type:"answer",sdp:S.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(R)).then(()=>{a.succeeded&&a.succeeded(A)}).catch(N=>{d.call(this),Te.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',N),this.emit("peerconnection:setremotedescriptionfailed",N)})}else a.succeeded&&a.succeeded(A)}function d(A){a.failed&&a.failed(A)}}_acceptAndTerminate(n,r,a){Te.debug("acceptAndTerminate()");const c=[];r&&(a=a||Ve.REASON_PHRASE[r]||"",c.push(`Reason: SIP ;cause=${r}; text="${a}"`)),(this._dialog||this._createDialog(n,"UAC"))&&(this.sendRequest(Ve.ACK),this.sendRequest(Ve.BYE,{extraHeaders:c})),this._status=Ce.STATUS_TERMINATED}_mangleOffer(n){if(!this._localHold&&!this._remoteHold)return n;if(n=X_.parse(n),this._localHold&&!this._remoteHold){Te.debug("mangleOffer() | me on hold, mangling offer");for(const r of n.media)xu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){Te.debug("mangleOffer() | both on hold, mangling offer");for(const r of n.media)xu.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){Te.debug("mangleOffer() | remote on hold, mangling offer");for(const r of n.media)xu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return X_.write(n)}_setLocalMediaStatus(){let n=!0,r=!0;(this._localHold||this._remoteHold)&&(n=!1,r=!1),this._audioMuted&&(n=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!n),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(n,r){if(!this._sessionTimers.enabled)return;let a;n.session_expires&&n.session_expires>=Ve.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,a=n.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,a="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${a}`),this._sessionTimers.refresher=a==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=Ve.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const n=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==Ce.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Te.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===Ve.UPDATE?this._sendUpdate():this._sendReinvite())},n*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==Ce.STATUS_TERMINATED&&(Te.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:Ve.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},n*1100)}_toggleMuteAudio(n){const r=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="audio");for(const a of r)a.track.enabled=!n}_toggleMuteVideo(n){const r=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="video");for(const a of r)a.track.enabled=!n}_newRTCSession(n,r){Te.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:n,session:this,request:r})}_connecting(n){Te.debug("session connecting"),Te.debug('emit "connecting"'),this.emit("connecting",{request:n})}_progress(n,r){Te.debug("session progress"),Te.debug('emit "progress"'),this.emit("progress",{originator:n,response:r||null})}_accepted(n,r){Te.debug("session accepted"),this._start_time=new Date,Te.debug('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){Te.debug("session confirmed"),this._is_confirmed=!0,Te.debug('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,a){Te.debug("session ended"),this._end_time=new Date,this._close(),Te.debug('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:a})}_failed(n,r,a){Te.debug("session failed"),Te.debug('emit "_failed"'),this.emit("_failed",{originator:n,message:r||null,cause:a}),this._close(),Te.debug('emit "failed"'),this.emit("failed",{originator:n,message:r||null,cause:a})}_onhold(n){Te.debug("session onhold"),this._setLocalMediaStatus(),Te.debug('emit "hold"'),this.emit("hold",{originator:n})}_onunhold(n){Te.debug("session onunhold"),this._setLocalMediaStatus(),Te.debug('emit "unhold"'),this.emit("unhold",{originator:n})}_onmute({audio:n,video:r}){Te.debug("session onmute"),this._setLocalMediaStatus(),Te.debug('emit "muted"'),this.emit("muted",{audio:n,video:r})}_onunmute({audio:n,video:r}){Te.debug("session onunmute"),this._setLocalMediaStatus(),Te.debug('emit "unmuted"'),this.emit("unmuted",{audio:n,video:r})}};const TC=Qt(ef),bC=Tn.EventEmitter,wC=mn,fd=bt,SC=On,ul=$n(),EC=to,tf=Ls,CC=Ms(),Ou=new wC("Message");var AC=class extends bC{constructor(o){super(),this._ua=o,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(o,n,r={}){const a=o;if(o===void 0||n===void 0)throw new TypeError("Not enough arguments");if(o=this._ua.normalizeTarget(o),!o)throw new TypeError(`Invalid target: ${a}`);const c=ul.cloneArray(r.extraHeaders),e=ul.cloneObject(r.eventHandlers),_=r.contentType||"text/plain",g={};r.fromUserName&&(g.from_uri=new CC("sip",r.fromUserName,this._ua.configuration.uri.host),c.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),r.fromDisplayName&&(g.from_display_name=r.fromDisplayName);for(const A in e)Object.prototype.hasOwnProperty.call(e,A)&&this.on(A,e[A]);c.push(`Content-Type: ${_}`),this._request=new SC.OutgoingRequest(fd.MESSAGE,o,this._ua,g,c),n&&(this._request.body=n);const d=new EC(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:A=>{this._receiveResponse(A)}});this._newMessage("local",this._request),d.send()}init_incoming(o){this._request=o,this._newMessage("remote",o),this._is_replied||(this._is_replied=!0,o.reply(200)),this._close()}accept(o={}){const n=ul.cloneArray(o.extraHeaders),r=o.body;if(this._direction!=="incoming")throw new tf.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,n,r)}reject(o={}){const n=o.status_code||480,r=o.reason_phrase,a=ul.cloneArray(o.extraHeaders),c=o.body;if(this._direction!=="incoming")throw new tf.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,r,a,c)}_receiveResponse(o){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):this._succeeded("remote",o);break;default:{const n=ul.sipErrorCause(o.status_code);this._failed("remote",o,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,fd.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,fd.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(o,n){o==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):o==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newMessage(this,{originator:o,message:this,request:n})}_failed(o,n,r){Ou.debug("MESSAGE failed"),this._close(),Ou.debug('emit "failed"'),this.emit("failed",{originator:o,response:n||null,cause:r})}_succeeded(o,n){Ou.debug("MESSAGE succeeded"),this._close(),Ou.debug('emit "succeeded"'),this.emit("succeeded",{originator:o,response:n})}};const IC=Tn.EventEmitter,RC=mn,md=bt,$C=On,cl=$n(),xC=to,nf=Ls,ku=new RC("Options");var OC=class extends IC{constructor(o){super(),this._ua=o,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(o,n,r={}){const a=o;if(o===void 0)throw new TypeError("A target is required for OPTIONS");if(o=this._ua.normalizeTarget(o),!o)throw new TypeError(`Invalid target: ${a}`);const c=cl.cloneArray(r.extraHeaders),e=cl.cloneObject(r.eventHandlers),_=r.contentType||"application/sdp";for(const d in e)Object.prototype.hasOwnProperty.call(e,d)&&this.on(d,e[d]);c.push(`Content-Type: ${_}`),this._request=new $C.OutgoingRequest(md.OPTIONS,o,this._ua,null,c),n&&(this._request.body=n);const g=new xC(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:d=>{this._receiveResponse(d)}});this._newOptions("local",this._request),g.send()}init_incoming(o){this._request=o,this._newOptions("remote",o),this._is_replied||(this._is_replied=!0,o.reply(200)),this._close()}accept(o={}){const n=cl.cloneArray(o.extraHeaders),r=o.body;if(this._direction!=="incoming")throw new nf.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,n,r)}reject(o={}){const n=o.status_code||480,r=o.reason_phrase,a=cl.cloneArray(o.extraHeaders),c=o.body;if(this._direction!=="incoming")throw new nf.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,r,a,c)}_receiveResponse(o){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(o.status_code):break;case/^2[0-9]{2}$/.test(o.status_code):this._succeeded("remote",o);break;default:{const n=cl.sipErrorCause(o.status_code);this._failed("remote",o,n);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,md.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,md.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(o,n){o==="remote"?(this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from):o==="local"&&(this._direction="outgoing",this._local_identity=n.from,this._remote_identity=n.to),this._ua.newOptions(this,{originator:o,message:this,request:n})}_failed(o,n,r){ku.debug("OPTIONS failed"),this._close(),ku.debug('emit "failed"'),this.emit("failed",{originator:o,response:n||null,cause:r})}_succeeded(o,n){ku.debug("OPTIONS succeeded"),this._close(),ku.debug('emit "succeeded"'),this.emit("succeeded",{originator:o,response:n})}},gd={};const kC=mn,yd=$n(),DC=Hr(),dl=new kC("Socket");gd.isSocket=o=>{if(Array.isArray(o))return!1;if(typeof o>"u")return dl.warn("undefined JsSIP.Socket instance"),!1;try{if(!yd.isString(o.url))throw dl.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!yd.isString(o.via_transport))throw dl.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(DC.parse(o.sip_uri,"SIP_URI")===-1)throw dl.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(n=>{if(!yd.isFunction(o[n]))throw dl.warn(`missing or invalid JsSIP.Socket method: ${n}`),new Error(`Missing or invalid JsSIP.Socket method: ${n}`)})}catch{return!1}return!0};const NC=mn,MC=gd,rf=bt,sr=new NC("Transport"),Rr={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:rf.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:rf.CONNECTION_RECOVERY_MAX_INTERVAL}};var sf=class{constructor(o,n=Rr.recovery_options){sr.debug("new()"),this.status=Rr.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(r){sr.warn(`cannot use TextDecoder: ${r}`)}if(typeof o>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");o instanceof Array||(o=[o]),o.forEach(function(r){if(!MC.isSocket(r.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(r.weight&&!Number(r.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:r.socket,weight:r.weight||0,status:Rr.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(sr.debug("connect()"),this.isConnected()){sr.debug("Transport is already connected");return}else if(this.isConnecting()){sr.debug("Transport is connecting");return}this.close_requested=!1,this.status=Rr.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(){sr.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=Rr.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(o){if(sr.debug("send()"),!this.isConnected())return sr.warn("unable to send message, transport is not connected"),!1;const n=o.toString();return sr.debug(`sending message:
|
|
116
116
|
|
|
117
117
|
${n}
|
|
118
118
|
`),this.socket.send(n)}isConnected(){return this.status===Rr.STATUS_CONNECTED}isConnecting(){return this.status===Rr.STATUS_CONNECTING}_reconnect(){this.recover_attempts+=1;let 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),sr.debug(`reconnection attempt: ${this.recover_attempts}. next connection attempt in ${o} seconds`),this.recovery_timer=setTimeout(()=>{!this.close_requested&&!(this.isConnected()||this.isConnecting())&&(this._getSocket(),this.connect())},o*1e3)}_getSocket(){let o=[];if(this.sockets.forEach(r=>{r.status!==Rr.SOCKET_STATUS_ERROR&&(o.length===0?o.push(r):r.weight>o[0].weight?o=[r]:r.weight===o[0].weight&&o.push(r))}),o.length===0){this.sockets.forEach(r=>{r.status=Rr.SOCKET_STATUS_READY}),this._getSocket();return}const n=Math.floor(Math.random()*o.length);this.socket=o[n].socket}_onConnect(){this.recover_attempts=0,this.status=Rr.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}_onDisconnect(o,n,r){this.status=Rr.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:o,code:n,reason:r}),!this.close_requested&&(this.sockets.forEach(function(a){this.socket===a.socket&&(a.status=Rr.SOCKET_STATUS_ERROR)},this),this._reconnect(o))}_onData(o){if(o===`\r
|
|
@@ -123,18 +123,18 @@ ${o}
|
|
|
123
123
|
|
|
124
124
|
${o}
|
|
125
125
|
`);this.ondata({transport:this,message:o})}};const UC=Qt(sf);var af={};const PC=mn,vd=Hr(),Td=On,Du=new PC("Parser");af.parseMessage=(o,n)=>{let r,a,c=o.indexOf(`\r
|
|
126
|
-
`);if(c===-1){Du.warn("parseMessage() | no CRLF found, not a SIP message");return}const e=o.substring(0,c);let
|
|
127
|
-
`,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function qC(o,n,r,a){let c;const e=n.indexOf(":",r),
|
|
126
|
+
`);if(c===-1){Du.warn("parseMessage() | no CRLF found, not a SIP message");return}const e=o.substring(0,c);let _=vd.parse(e,"Request_Response");if(_===-1){Du.warn(`parseMessage() | error parsing first line of SIP message: "${e}"`);return}else _.status_code?(r=new Td.IncomingResponse,r.status_code=_.status_code,r.reason_phrase=_.reason_phrase):(r=new Td.IncomingRequest(n),r.method=_.method,r.ruri=_.uri);r.data=o;let g=c+2;for(;;){if(c=LC(o,g),c===-2){a=g+2;break}else if(c===-1){Du.warn("parseMessage() | malformed message");return}if(_=qC(r,o,g,c),_!==!0){Du.warn("parseMessage() |",_.error);return}g=c+2}if(r.hasHeader("content-length")){const d=r.getHeader("content-length");r.body=o.substr(a,d)}else r.body=o.substring(a);return r};function LC(o,n){let r=n,a=0,c=0;if(o.substring(r,r+2).match(/(^\r\n)/))return-2;for(;a===0;){if(c=o.indexOf(`\r
|
|
127
|
+
`,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function qC(o,n,r,a){let c;const e=n.indexOf(":",r),_=n.substring(r,e).trim(),g=n.substring(e+1,a).trim();switch(_.toLowerCase()){case"via":case"v":o.addHeader("via",g),o.getHeaders("via").length===1?(c=o.parseHeader("Via"),c&&(o.via=c,o.via_branch=c.branch)):c=0;break;case"from":case"f":o.setHeader("from",g),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",g),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=vd.parse(g,"Record_Route"),c===-1)c=void 0;else for(const d of c)o.addHeader("record-route",g.substring(d.possition,d.offset)),o.headers["Record-Route"][o.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":o.setHeader("call-id",g),c=o.parseHeader("call-id"),c&&(o.call_id=g);break;case"contact":case"m":if(c=vd.parse(g,"Contact"),c===-1)c=void 0;else for(const d of c)o.addHeader("contact",g.substring(d.possition,d.offset)),o.headers.Contact[o.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":o.setHeader("content-length",g),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",g),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",g),c=o.parseHeader("cseq"),c&&(o.cseq=c.value),o instanceof Td.IncomingResponse&&(o.method=c.method);break;case"max-forwards":o.setHeader("max-forwards",g),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",g),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",g),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",g),c=o.parseHeader("session-expires"),c&&(o.session_expires=c.expires,o.session_expires_refresher=c.refresher);break;case"refer-to":case"r":o.setHeader("refer-to",g),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",g),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",g),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(_,g),c=0}return c===void 0?{error:`error parsing header "${_}"`}:!0}const HC=mn,of=bt,lf=On,bd=$n(),wd=new HC("sanityCheck"),zC=[XC],FC=[VC,jC,GC,WC],BC=[KC,YC];let jt,ls,uf;var cf=(o,n,r)=>{jt=o,ls=n,uf=r;for(const a of zC)if(a()===!1)return!1;if(jt instanceof lf.IncomingRequest){for(const a of FC)if(a()===!1)return!1}else if(jt instanceof lf.IncomingResponse){for(const a of BC)if(a()===!1)return!1}return!0};function VC(){if(jt.s("to").uri.scheme!=="sip")return hl(416),!1}function jC(){if(!jt.to_tag&&jt.call_id.substr(0,5)===ls.configuration.jssip_id)return hl(482),!1}function GC(){const o=bd.str_utf8_length(jt.body),n=jt.getHeader("content-length");if(o<n)return hl(400),!1}function WC(){const o=jt.from_tag,n=jt.call_id,r=jt.cseq;let a;if(!jt.to_tag)if(jt.method===of.INVITE){if(ls._transactions.ist[jt.via_branch])return!1;for(const c in ls._transactions.ist)if(Object.prototype.hasOwnProperty.call(ls._transactions.ist,c)&&(a=ls._transactions.ist[c],a.request.from_tag===o&&a.request.call_id===n&&a.request.cseq===r))return hl(482),!1}else{if(ls._transactions.nist[jt.via_branch])return!1;for(const c in ls._transactions.nist)if(Object.prototype.hasOwnProperty.call(ls._transactions.nist,c)&&(a=ls._transactions.nist[c],a.request.from_tag===o&&a.request.call_id===n&&a.request.cseq===r))return hl(482),!1}}function KC(){if(jt.getHeaders("via").length>1)return wd.debug("more than one Via header field present in the response, dropping the response"),!1}function YC(){const o=bd.str_utf8_length(jt.body),n=jt.getHeader("content-length");if(o<n)return wd.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function XC(){const o=["from","to","call_id","cseq","via"];for(const n of o)if(!jt.hasHeader(n))return wd.debug(`missing mandatory header field : ${n}, dropping the response`),!1}function hl(o){const n=jt.getHeaders("via");let r,a=`SIP/2.0 ${o} ${of.REASON_PHRASE[o]}\r
|
|
128
128
|
`;for(const c of n)a+=`Via: ${c}\r
|
|
129
129
|
`;r=jt.getHeader("To"),jt.to_tag||(r+=`;tag=${bd.newTag()}`),a+=`To: ${r}\r
|
|
130
130
|
`,a+=`From: ${jt.getHeader("From")}\r
|
|
131
131
|
`,a+=`Call-ID: ${jt.call_id}\r
|
|
132
132
|
`,a+=`CSeq: ${jt.cseq} ${jt.method}\r
|
|
133
133
|
`,a+=`\r
|
|
134
|
-
`,uf.send(a)}const JC=Qt(cf);var pl={};const no=$n(),Ta=bt,Sd=Hr(),df=Ms(),Ed=gd,Cd=Ls;pl.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:Ta.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:Ta.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:Ta.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${no.createRandomToken(12)}.invalid`};const Nu={mandatory:{sockets(o){const n=[];if(Ed.isSocket(o))n.push({socket:o});else if(Array.isArray(o)&&o.length)for(const r of o)Object.prototype.hasOwnProperty.call(r,"socket")&&Ed.isSocket(r.socket)?n.push(r):Ed.isSocket(r)&&n.push({socket:r});else return;return n},uri(o){/^sip:/i.test(o)||(o=`${Ta.SIP}:${o}`);const n=df.parse(o);if(n)return n.user?n:void 0}},optional:{authorization_user(o){if(Sd.parse(`"${o}"`,"quoted_string")!==-1)return o},authorization_jwt(o){if(typeof o=="string")return o},user_agent(o){if(typeof o=="string")return o},connection_recovery_max_interval(o){if(no.isDecimal(o)){const n=Number(o);if(n>0)return n}},connection_recovery_min_interval(o){if(no.isDecimal(o)){const n=Number(o);if(n>0)return n}},contact_uri(o){if(typeof o=="string"){const n=Sd.parse(o,"SIP_URI");if(n!==-1)return n}},display_name(o){return o},instance_id(o){if(/^uuid:/i.test(o)&&(o=o.substr(5)),Sd.parse(o,"uuid")!==-1)return o},no_answer_timeout(o){if(no.isDecimal(o)){const n=Number(o);if(n>0)return n}},session_timers(o){if(typeof o=="boolean")return o},session_timers_refresh_method(o){if(typeof o=="string"&&(o=o.toUpperCase(),o===Ta.INVITE||o===Ta.UPDATE))return o},session_timers_force_refresher(o){if(typeof o=="boolean")return o},password(o){return String(o)},realm(o){return String(o)},ha1(o){return String(o)},register(o){if(typeof o=="boolean")return o},register_expires(o){if(no.isDecimal(o)){const n=Number(o);if(n>0)return n}},registrar_server(o){/^sip:/i.test(o)||(o=`${Ta.SIP}:${o}`);const n=df.parse(o);if(n)return n.user?void 0:n},use_preloaded_route(o){if(typeof o=="boolean")return o},extra_headers(o){const n=[];if(Array.isArray(o)&&o.length)for(const r of o)typeof r=="string"&&n.push(r);else return;return n}}};pl.load=(o,n)=>{for(const r in Nu.mandatory)if(n.hasOwnProperty(r)){const a=n[r],c=Nu.mandatory[r](a);if(c!==void 0)o[r]=c;else throw new Cd.ConfigurationError(r,a)}else throw new Cd.ConfigurationError(r);for(const r in Nu.optional)if(n.hasOwnProperty(r)){const a=n[r];if(no.isEmpty(a))continue;const c=Nu.optional[r](a);if(c!==void 0)o[r]=c;else throw new Cd.ConfigurationError(r,a)}};const QC=Tn.EventEmitter,ZC=mn,kn=bt,eA=FE,hf=ef,pf=AC,_f=OC,Ad=eo,tA=sf,Mu=$n(),nA=Ls,rA=Ms(),sA=af,Id=On,iA=cf,Rd=pl,Kt=new ZC("UA"),Dn={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var ff=class extends QC{static get C(){return Dn}constructor(o){if(Kt.debug("new() [configuration:%o]",o),super(),this._cache={credentials:{}},this._configuration=Object.assign({},Rd.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=Dn.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,o===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(o)}catch(n){throw this._status=Dn.STATUS_NOT_READY,this._error=Dn.CONFIGURATION_ERROR,n}this._registrator=new eA(this)}get C(){return Dn}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){Kt.debug("start()"),this._status===Dn.STATUS_INIT?this._transport.connect():this._status===Dn.STATUS_USER_CLOSED?(Kt.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Dn.STATUS_INIT,this._transport.connect()):this._status===Dn.STATUS_READY?Kt.debug("UA is in READY status, not restarted"):Kt.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){Kt.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(o){Kt.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(o)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(o,n){Kt.debug("call()");const r=new hf(this);return r.connect(o,n),r}sendMessage(o,n,r){Kt.debug("sendMessage()");const a=new pf(this);return a.send(o,n,r),a}sendOptions(o,n,r){Kt.debug("sendOptions()");const a=new _f(this);return a.send(o,n,r),a}terminateSessions(o){Kt.debug("terminateSessions()");for(const n in this._sessions)this._sessions[n].isEnded()||this._sessions[n].terminate(o)}stop(){if(Kt.debug("stop()"),this._dynConfiguration={},this._status===Dn.STATUS_USER_CLOSED){Kt.debug("UA already closed");return}this._registrator.close();const o=Object.keys(this._sessions).length;for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){Kt.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch{}}for(const n in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,n))try{this._applicants[n].close()}catch{}this._status=Dn.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&&o===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(o){return Mu.normalizeTarget(o,this._configuration.hostport_params)}get(o){switch(o){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:Kt.warn('get() | cannot get "%s" parameter in runtime',o);return}}set(o,n){switch(o){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 Kt.warn('set() | cannot set "%s" parameter in runtime',o),!1}return!0}newTransaction(o){this._transactions[o.type][o.id]=o,this.emit("newTransaction",{transaction:o})}destroyTransaction(o){delete this._transactions[o.type][o.id],this.emit("transactionDestroyed",{transaction:o})}newDialog(o){this._dialogs[o.id]=o}destroyDialog(o){delete this._dialogs[o.id]}newMessage(o,n){this._applicants[o]=o,this.emit("newMessage",n)}newOptions(o,n){this._applicants[o]=o,this.emit("newOptions",n)}destroyMessage(o){delete this._applicants[o]}newRTCSession(o,n){this._sessions[o.id]=o,this.emit("newRTCSession",n)}destroyRTCSession(o){delete this._sessions[o.id]}registered(o){this.emit("registered",o)}unregistered(o){this.emit("unregistered",o)}registrationFailed(o){this.emit("registrationFailed",o)}receiveRequest(o){const n=o.method;if(o.ruri.user!==this._configuration.uri.user&&o.ruri.user!==this._contact.uri.user){Kt.debug("Request-URI does not point to us"),o.method!==kn.ACK&&o.reply_sl(404);return}if(o.ruri.scheme===kn.SIPS){o.reply_sl(416);return}if(Ad.checkTransaction(this,o))return;if(n===kn.INVITE?new Ad.InviteServerTransaction(this,this._transport,o):n!==kn.ACK&&n!==kn.CANCEL&&new Ad.NonInviteServerTransaction(this,this._transport,o),n===kn.OPTIONS){if(this.listeners("newOptions").length===0){o.reply(200);return}new _f(this).init_incoming(o)}else if(n===kn.MESSAGE){if(this.listeners("newMessage").length===0){o.reply(405);return}new pf(this).init_incoming(o)}else if(n===kn.INVITE&&!o.to_tag&&this.listeners("newRTCSession").length===0){o.reply(405);return}let r,a;if(o.to_tag)r=this._findDialog(o.call_id,o.from_tag,o.to_tag),r?r.receiveRequest(o):n===kn.NOTIFY?(a=this._findSession(o),a?a.receiveRequest(o):(Kt.debug("received NOTIFY request for a non existent subscription"),o.reply(481,"Subscription does not exist"))):n!==kn.ACK&&o.reply(481);else switch(n){case kn.INVITE:if(window.RTCPeerConnection)if(o.hasHeader("replaces")){const c=o.replaces;r=this._findDialog(c.call_id,c.from_tag,c.to_tag),r?(a=r.owner,a.isEnded()?o.reply(603):a.receiveRequest(o)):o.reply(481)}else a=new hf(this),a.init_incoming(o);else Kt.warn("INVITE received but WebRTC is not supported"),o.reply(488);break;case kn.BYE:o.reply(481);break;case kn.CANCEL:a=this._findSession(o),a?a.receiveRequest(o):Kt.debug("received CANCEL request for a non existent session");break;case kn.ACK:break;case kn.NOTIFY:this.emit("sipEvent",{event:o.event,request:o}),o.reply(200);break;default:o.reply(405);break}}_findSession({call_id:o,from_tag:n,to_tag:r}){const a=o+n,c=this._sessions[a],e=o+r,f=this._sessions[e];return c||f||null}_findDialog(o,n,r){let a=o+n+r,c=this._dialogs[a];return c||(a=o+r+n,c=this._dialogs[a],c||null)}_loadConfig(o){try{Rd.load(this._configuration,o)}catch(a){throw a}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Mu.newUUID()),this._configuration.jssip_id=Mu.createRandomToken(5);const n=this._configuration.uri.clone();n.user=null,this._configuration.hostport_params=n.toString().replace(/^sip:/i,"");try{this._transport=new tA(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=aA.bind(this),this._transport.onconnect=oA.bind(this),this._transport.ondisconnect=lA.bind(this),this._transport.ondata=uA.bind(this)}catch(a){throw Kt.warn(a),new nA.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 rA("sip",Mu.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 c=a.anonymous||null,e=a.outbound||null;let f="<";return c?f+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":f+=this.pub_gruu||this.uri.toString(),e&&(c?!this.temp_gruu:!this.pub_gruu)&&(f+=";ob"),f+=">",f}};const r=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(r.indexOf(a)!==-1?Object.defineProperty(this._configuration,a,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,a,{writable:!1,configurable:!1}));Kt.debug("configuration parameters after validation:");for(const a in this._configuration)if(Object.prototype.hasOwnProperty.call(Rd.settings,a))switch(a){case"uri":case"registrar_server":Kt.debug(`- ${a}: ${this._configuration[a]}`);break;case"password":case"ha1":case"authorization_jwt":Kt.debug(`- ${a}: NOT SHOWN`);break;default:Kt.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}};function aA(o){this.emit("connecting",o)}function oA(o){this._status!==Dn.STATUS_USER_CLOSED&&(this._status=Dn.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function lA(o){const n=["nict","ict","nist","ist"];for(const r of n)for(const a in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],a)&&this._transactions[r][a].onTransportError();this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==Dn.STATUS_USER_CLOSED&&(this._status=Dn.STATUS_NOT_READY,this._error=Dn.NETWORK_ERROR)}function uA(o){const n=o.transport;let r=o.message;if(r=sA.parseMessage(r,this),!!r&&!(this._status===Dn.STATUS_USER_CLOSED&&r instanceof Id.IncomingRequest)&&iA(r,this,n)){if(r instanceof Id.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Id.IncomingResponse){let a;switch(r.method){case kn.INVITE:a=this._transactions.ict[r.via_branch],a&&a.receiveResponse(r);break;case kn.ACK:break;default:a=this._transactions.nict[r.via_branch],a&&a.receiveResponse(r);break}}}}const cA=Qt(ff);for(var Nn=[],$d=0;$d<256;++$d)Nn.push(($d+256).toString(16).slice(1));function dA(o,n=0){return(Nn[o[n+0]]+Nn[o[n+1]]+Nn[o[n+2]]+Nn[o[n+3]]+"-"+Nn[o[n+4]]+Nn[o[n+5]]+"-"+Nn[o[n+6]]+Nn[o[n+7]]+"-"+Nn[o[n+8]]+Nn[o[n+9]]+"-"+Nn[o[n+10]]+Nn[o[n+11]]+Nn[o[n+12]]+Nn[o[n+13]]+Nn[o[n+14]]+Nn[o[n+15]]).toLowerCase()}var Uu,hA=new Uint8Array(16);function pA(){if(!Uu&&(Uu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Uu))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Uu(hA)}var _A=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const mf={randomUUID:_A};function gf(o,n,r){if(mf.randomUUID&&!n&&!o)return mf.randomUUID();o=o||{};var a=o.random||(o.rng||pA)();if(a[6]=a[6]&15|64,a[8]=a[8]&63|128,n){r=r||0;for(var c=0;c<16;++c)n[r+c]=a[c];return n}return dA(a)}var kt=$n();const qs=Qt(kt),xd=new wu("Dialog"),_i={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class Pu{static get C(){return _i}constructor(n,r,a,c=_i.STATUS_CONFIRMED){if(this._owner=n,this._ua=n._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,r instanceof On.IncomingResponse&&(c=r.status_code<200?_i.STATUS_EARLY:_i.STATUS_CONFIRMED),a==="UAS"){this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=c,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri;let e=r.getHeaders("to")[0].split(";")[0];e=e.match(/<([^>]*)>/)[1],this._remote_target=e,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(a==="UAC"){this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=c,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri;let e=r.getHeaders("to")[0].split(";")[0];e=e.match(/<([^>]*)>/)[1],this._remote_target=e,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),xd.debug(`new ${a} dialog created with status ${this._state===_i.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(n){this._local_seqnum=n}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(n){this._uac_pending_reply=n}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===_i.STATUS_TERMINATED}update(n,r){this._state=_i.STATUS_CONFIRMED,xd.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),r==="UAC"&&(this._route_set=n.getHeaders("record-route").reverse())}terminate(){xd.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=_i.STATUS_TERMINATED}sendRequest(n,r={}){const a=qs.cloneArray(r.extraHeaders),c=qs.cloneObject(r.eventHandlers),e=r.body||null,f=this._createRequest(n,a,e);return c.onAuthenticated=()=>{this._local_seqnum+=1},new KE(this,f,c).send(),f}receiveRequest(n){this._checkInDialogRequest(n)&&(n.method===oe.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:n.method===oe.INVITE&&(this._ack_seqnum=n.cseq),this._owner.receiveRequest(n))}_createRequest(n,r,a){r=qs.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const c=n===oe.CANCEL||n===oe.ACK?this._local_seqnum:this._local_seqnum+=1;return new On.OutgoingRequest(n,this._remote_target,this._ua,{cseq:c,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},r,a)}_checkInDialogRequest(n){if(!this._remote_seqnum)this._remote_seqnum=n.cseq;else if(n.cseq<this._remote_seqnum)if(n.method===oe.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===oe.INVITE||n.method===oe.UPDATE&&n.body){if(this._uac_pending_reply===!0)n.reply(491);else if(this._uas_pending_reply===!0){const r=(Math.random()*10|0)+1;return n.reply(500,null,[`Retry-After:${r}`]),!1}else{this._uas_pending_reply=!0;const r=()=>{(n.server_transaction.state===Ir.C.STATUS_ACCEPTED||n.server_transaction.state===Ir.C.STATUS_COMPLETED||n.server_transaction.state===Ir.C.STATUS_TERMINATED)&&(n.server_transaction.removeListener("stateChanged",r),this._uas_pending_reply=!1)};n.server_transaction.on("stateChanged",r)}n.hasHeader("contact")&&n.server_transaction.on("stateChanged",()=>{n.server_transaction.state===Ir.C.STATUS_ACCEPTED&&(this._remote_target=n.parseHeader("contact").uri)})}else n.method===oe.NOTIFY&&n.hasHeader("contact")&&n.server_transaction.on("stateChanged",()=>{n.server_transaction.state===Ir.C.STATUS_COMPLETED&&(this._remote_target=n.parseHeader("contact").uri)});return!0}}class fA{constructor(n,r){rs(this,"plugin",null),rs(this,"rtcpPeer",null),rs(this,"handleId",0),rs(this,"info",null),rs(this,"joinResult",null),rs(this,"state",{}),rs(this,"stream",null),rs(this,"loaded",!1),rs(this,"aTracks",[]),rs(this,"vTracks",[]),this.info=n,this.plugin=r,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(n){var r;this.state={...this.state,...n||{}},(r=this.plugin)==null||r.session.emit("member:update",this.memberInfo)}updateMemberStateFromMessage(n){var r,a,c,e;const f=(a=(r=n?.plugindata)==null?void 0:r.data)==null?void 0:a.newStatePublisher,g=((e=(c=n?.plugindata)==null?void 0:c.data)==null?void 0:e.publisher_state).find(d=>d.id===f);this.updateMemberState(g?.state)}hangup(){this.rtcpPeer&&(this.rtcpPeer.close(),this.rtcpPeer=null),this.stream&&this.stream.getTracks().forEach(n=>{n.stop()})}}class Fr{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(n){return Fr.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind===n):[]}static async getMicrophoneList(){return(await Fr.getDevices("audioinput")).map((n,r)=>({...n,deviceId:n.deviceId,label:n.label||`microphone ${r+1}`,kind:n.kind,groupId:n.groupId}))}static async getSpeakerList(){return(await Fr.getDevices("audiooutput")).map((n,r)=>({...n,deviceId:n.deviceId,label:n.label||`speaker ${r+1}`,kind:n.kind,groupId:n.groupId}))}static async getCameraList(){return(await Fr.getDevices("videoinput")).map((n,r)=>({...n,deviceId:n.deviceId,label:n.label||`camera ${r+1}`,kind:n.kind,groupId:n.groupId}))}static stopStreamTracks(n){n&&n.getTracks().forEach(r=>{r.stop()})}static async getMediaFromInputs({videoInput:n,audioInput:r}){let a,c;n==="default"?a=!0:n&&n!=="default"&&(a={deviceId:{exact:n}}),r==="default"?c=!0:r&&r!=="default"&&(c={deviceId:{exact:r}});const e={audio:c,video:a};return Fr.getUserMedia(e)}static async getUserMedia(n){return await navigator.mediaDevices.getUserMedia(n)}static async changeAudioOutput(n,r){if(!(!n||!r))if(typeof n.sinkId<"u")try{await n.setSinkId(r)}catch(a){let c=a;a.name==="SecurityError"&&(c=`You need to use HTTPS for selecting audio output device: ${a}`),console.error(c)}else console.warn("Browser does not support output device selection.")}static toggleAudioMute(n){const r=n.getAudioTracks();if(r.length!==0)return r.forEach(a=>{a.enabled=!a.enabled}),r[0].enabled}static toggleVideoMute(n){const r=n.getVideoTracks();if(r.length!==0)return r.forEach(a=>{a.enabled=!a.enabled}),r[0].enabled}static async getStream(n={video:!0,audio:!0}){try{const r=await navigator.mediaDevices.getUserMedia(n);let a=r.getTracks();return n.video?a=r.getVideoTracks():n.audio&&(a=r.getAudioTracks()),a.length===0?{stream:r,track:null}:{stream:r,track:a[0]}}catch(r){return console.warn(r),{stream:null,track:null}}}}var mA=Ms();const ba=Qt(mA),ir={LEAVE:"Leave",DETACH:"Detach",AUDIO_CHANGE:"AudioChange",VIDEO_CHANGE:"VideoChange",STATE:"State",ICE:"Ice",CONFIGURE:"Configure",TRICKLE:"Trickle",SUBSCRIBER:"Subscriber",PUBLISHER:"Publisher"},we=new wu("JanusSession"),gA="/opt/recordings/",Ie={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},Lu=["audio","video"];class qu extends Tn.EventEmitter{static get C(){return Ie}constructor(n){we.debug("new"),super(),this._id=null,this._ua=n,this._status=Ie.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:oe.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 Ie}get causes(){return oe.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(n){this._data=n}get status(){return this._status}isInProgress(){switch(this._status){case Ie.STATUS_NULL:case Ie.STATUS_INVITE_SENT:case Ie.STATUS_1XX_RECEIVED:case Ie.STATUS_INVITE_RECEIVED:case Ie.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case Ie.STATUS_ANSWERED:case Ie.STATUS_WAITING_FOR_ACK:case Ie.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case Ie.STATUS_CANCELED:case Ie.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(n){return`PTYPE: ${n}`}generateOpaqueId(){return`videoroomtest-${gf().replace(/-/g,"").slice(0,12)}`}connect(n,r,a={},c){we.debug("connect()"),this.display_name=r;const e=n,f=kt.cloneObject(a.eventHandlers),g=kt.cloneArray(a.extraHeaders),d=kt.cloneObject(a.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={...d};const A=a.mediaStream||null,S=kt.cloneObject(a.pcConfig,{iceServers:[]}),R=a.rtcConstraints||null,N=a.rtcOfferConstraints||null;if(this._rtcOfferConstraints=N,this._rtcAnswerConstraints=a.rtcAnswerConstraints||null,this._data=a.data||this._data,n===void 0)throw new TypeError("Not enough arguments");if(this._status!==Ie.STATUS_NULL)throw new di.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new di.NotSupportedError("WebRTC not supported");if(n=this._ua.normalizeTarget(n),this.room_id=n.user,this.target=n,!n)throw new TypeError(`Invalid target: ${e}`);this._sessionTimers.enabled&&kt.isDecimal(a.sessionTimersExpires)&&(a.sessionTimersExpires>=oe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=a.sessionTimersExpires:this._sessionTimers.defaultExpires=oe.SESSION_EXPIRES);for(const G in f)Object.prototype.hasOwnProperty.call(f,G)&&this.on(G,f[G]);this._from_tag=kt.newTag();const H=a.anonymous||!1,W={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:H,outbound:!0}),H?(W.from_display_name="Anonymous",W.from_uri=new ba("sip","anonymous","anonymous.invalid"),g.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),g.push("Privacy: id")):a.fromUserName&&(W.from_uri=new ba("sip",a.fromUserName,this._ua.configuration.uri.host),g.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),a.fromDisplayName&&(W.from_display_name=a.fromDisplayName),g.push(`Contact: ${this._contact}`),g.push("Content-Type: application/json"),this._sessionTimers.enabled&&g.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new On.InitialOutgoingInviteRequest(n,this._ua,W,g),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(S,R),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,c&&c(this),this._newJanusSession("local",this._request),this._sendInitialRequest(d,N,A)}_overrideSenderTracks(n,r){n.getTracks().forEach(a=>{r.getSenders().forEach(async c=>{c.track.kind===a.kind&&(a.kind==="audio"&&!this.isAudioOn&&(a.enabled=!1),a.kind==="video"&&!this.isVideoOn&&(a.enabled=!1),await c.replaceTrack(a))})})}init_incoming(n,r){we.debug("init_incoming()");let a;const c=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&c!=="application/sdp"){n.reply(415);return}if(this._status=Ie.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(a=n.getHeader("expires")*1e3),n.to_tag=kt.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ie.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),this._failed("local",null,oe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ie.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),this._failed("system",null,oe.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),this._newJanusSession("remote",n),this._status!==Ie.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(n={}){we.debug("answer()");const r=this._request,a=kt.cloneArray(n.extraHeaders),c=kt.cloneObject(n.mediaConstraints),e=n.mediaStream||null,f=kt.cloneObject(n.pcConfig,{iceServers:[]}),g=n.rtcConstraints||null,d=n.rtcAnswerConstraints||null,A=kt.cloneObject(n.rtcOfferConstraints);let S,R=!1,N=!1,H=!1,W=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=n.rtcOfferConstraints||null,this._data=n.data||this._data,this._direction!=="incoming")throw new di.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==Ie.STATUS_WAITING_FOR_ANSWER)throw new di.InvalidStateError(this._status);if(this._sessionTimers.enabled&&kt.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=oe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=oe.SESSION_EXPIRES),this._status=Ie.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),a.unshift(`Contact: ${this._contact}`);const G=r.parseSDP();Array.isArray(G.media)||(G.media=[G.media]);for(const K of G.media)K.type==="audio"&&(R=!0,(!K.direction||K.direction==="sendrecv")&&(H=!0)),K.type==="video"&&(N=!0,(!K.direction||K.direction==="sendrecv")&&(W=!0));if(e&&c.audio===!1){S=e.getAudioTracks();for(const K of S)e.removeTrack(K)}if(e&&c.video===!1){S=e.getVideoTracks();for(const K of S)e.removeTrack(K)}!e&&c.audio===void 0&&(c.audio=H),!e&&c.video===void 0&&(c.video=W),!e&&!R&&!A.offerToReceiveAudio&&(c.audio=!1),!e&&!N&&!A.offerToReceiveVideo&&(c.video=!1),this._createRTCConnection(f,g),Promise.resolve().then(()=>{if(e)return e;if(c.audio||c.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(K=>{throw this._status===Ie.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,oe.causes.USER_DENIED_MEDIA_ACCESS),we.warn('emit "getusermediafailed" [error:%o]',K),this.emit("getusermediafailed",K),new Error("getUserMedia() failed"))})}).then(K=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=K,K&&K.getTracks().forEach(ae=>{this._connection.addTrack(ae,K)})}).then(()=>{if(this._late_sdp)return;const K={originator:"remote",type:"offer",sdp:r.body};we.debug('emit "sdp"'),this.emit("sdp",K);const ae=new RTCSessionDescription({type:"offer",sdp:K.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(ae)).catch(ee=>{throw r.reply(488),this._failed("system",null,oe.causes.WEBRTC_ERROR),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',ee),this.emit("peerconnection:setremotedescriptionfailed",ee),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",d).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(K=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,a),r.reply(200,null,a,K,()=>{this._status=Ie.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,K),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,oe.causes.CONNECTION_ERROR)})}).catch(K=>{this._status!==Ie.STATUS_TERMINATED&&we.warn(K)})}terminate(n={}){we.debug("terminate()");const r=n.cause||oe.causes.BYE,a=kt.cloneArray(n.extraHeaders),c=n.body;let e,f=n.status_code,g=n.reason_phrase;if(this._status===Ie.STATUS_TERMINATED)throw new di.InvalidStateError(this._status);switch(this._status){case Ie.STATUS_NULL:case Ie.STATUS_INVITE_SENT:case Ie.STATUS_1XX_RECEIVED:if(we.debug("canceling session"),f&&(f<200||f>=700))throw new TypeError(`Invalid status_code: ${f}`);f&&(g=g||oe.REASON_PHRASE[f]||"",e=`SIP ;cause=${f} ;text="${g}"`),this._status===Ie.STATUS_NULL||this._status===Ie.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===Ie.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=Ie.STATUS_CANCELED,this._failed("local",null,oe.causes.CANCELED);break;case Ie.STATUS_WAITING_FOR_ANSWER:case Ie.STATUS_ANSWERED:if(we.debug("rejecting session"),f=f||480,f<300||f>=700)throw new TypeError(`Invalid status_code: ${f}`);this._request.reply(f,g,a,c),this._failed("local",null,oe.causes.REJECTED);break;case Ie.STATUS_WAITING_FOR_ACK:case Ie.STATUS_CONFIRMED:if(we.debug("terminating session"),g=n.reason_phrase||oe.REASON_PHRASE[f]||"",f&&(f<200||f>=700))throw new TypeError(`Invalid status_code: ${f}`);if(f&&a.push(`Reason: SIP ;cause=${f}; text="${g}"`),this._status===Ie.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ir.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:A})=>{A===oe.ACK&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ir.C.STATUS_TERMINATED&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate(),this.closeSession())}),this._ended("local",null,r),this._dialog=d,this._ua.newDialog(d)}else{const d={janus:"leave"},A=["Content-Type: application/json",this.getPTypeHeader(ir.LEAVE)];this.sendRequest(oe.BYE,{extraHeaders:A,body:JSON.stringify(d)}),this.closeSession(),this._ended("local",null,r)}}}configureMedia(n){this.isAudioOn=n.audio,this.isVideoOn=n.video}enableAudio(n){const r={janus:"message",body:{audio:n},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(ir.AUDIO_CHANGE)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{c.status_code===200&&(this._ua.emit("changeAudioState",n),this.sendStateMessage({audio:n}))}}})}startAudio(){Fr.toggleAudioMute(this.stream),this._toggleMuteAudio(!1),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Fr.toggleAudioMute(this.stream),this._toggleMuteAudio(!0),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(n){const r={janus:"message",body:{video:n},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(ir.VIDEO_CHANGE)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{c.status_code===200&&(this._ua.emit("changeVideoState",n),this.sendStateMessage({video:n}))}}})}startVideo(){Fr.toggleVideoMute(this.stream),this._toggleMuteVideo(!1),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Fr.toggleVideoMute(this.stream),this._toggleMuteVideo(!0),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(n){const r={janus:"message",body:{request:"state",data:n},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(ir.STATE)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r)})}sendInfo(n,r,a={}){if(we.debug("sendInfo()"),this._status!==Ie.STATUS_CONFIRMED&&this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_1XX_RECEIVED)throw new di.InvalidStateError(this._status);new pd(this).send(n,r,a)}mute(n={audio:!0,video:!1}){we.debug("mute()");let r=!1,a=!1;this._audioMuted===!1&&n.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&n.video&&(a=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||a===!0)&&this._onmute({audio:r,video:a})}unmute(n={audio:!0,video:!0}){we.debug("unmute()");let r=!1,a=!1;this._audioMuted===!0&&n.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&n.video&&(a=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||a===!0)&&this._onunmute({audio:r,video:a})}hold(n={},r){if(we.debug("hold()"),this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:n.extraHeaders}),!0}unhold(n={},r){if(we.debug("unhold()"),this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:n.extraHeaders}),!0}renegotiate(n={},r){we.debug("renegotiate()");const a=n.rtcOfferConstraints||null;if(this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const c={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:c,rtcOfferConstraints:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:c,rtcOfferConstraints:a,extraHeaders:n.extraHeaders}),!0}refer(n,r){we.debug("refer()");const a=n;if(this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED)return!1;if(n=this._ua.normalizeTarget(n),!n)throw new TypeError(`Invalid target: ${a}`);const c=new pC(this);c.sendRefer(n,r);const e=c.id;return this._referSubscribers[e]=c,c.on("requestFailed",()=>{delete this._referSubscribers[e]}),c.on("accepted",()=>{delete this._referSubscribers[e]}),c.on("failed",()=>{delete this._referSubscribers[e]}),c}sendRequest(n,r){return we.debug("sendRequest()"),this._dialog.sendRequest(n,r)}receiveNotify(n){we.debug("receiveRequest()")}receiveRequest(n){if(we.debug("receiveRequest()"),n.method===oe.CANCEL)(this._status===Ie.STATUS_WAITING_FOR_ANSWER||this._status===Ie.STATUS_ANSWERED)&&(this._status=Ie.STATUS_CANCELED,this._request.reply(487),this._failed("remote",n,oe.causes.CANCELED));else switch(n.method){case oe.ACK:if(this._status!==Ie.STATUS_WAITING_FOR_ACK)return;if(this._status=Ie.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:oe.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};we.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(c=>{this.terminate({cause:oe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})}else this._is_confirmed||this._confirmed("remote",n);break;case oe.BYE:this._status===Ie.STATUS_CONFIRMED||this._status===Ie.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,oe.causes.BYE)):this._status===Ie.STATUS_INVITE_RECEIVED||this._status===Ie.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,oe.causes.BYE)):n.reply(403,"Wrong Status");break;case oe.INVITE:this._status===Ie.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case oe.INFO:if(this._status===Ie.STATUS_1XX_RECEIVED||this._status===Ie.STATUS_WAITING_FOR_ANSWER||this._status===Ie.STATUS_ANSWERED||this._status===Ie.STATUS_WAITING_FOR_ACK||this._status===Ie.STATUS_CONFIRMED){const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new nC(this).init_incoming(n):r!==void 0?new pd(this).init_incoming(n):n.reply(415)}else n.reply(403,"Wrong Status");break;case oe.UPDATE:this._status===Ie.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case oe.REFER:this._status===Ie.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case oe.NOTIFY:this._status===Ie.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){we.warn("onTransportError()"),this._status!==Ie.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.CONNECTION_ERROR,cause:oe.causes.CONNECTION_ERROR})}onRequestTimeout(){we.warn("onRequestTimeout()"),this._status!==Ie.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:oe.causes.REQUEST_TIMEOUT,cause:oe.causes.REQUEST_TIMEOUT})}onDialogError(){we.warn("onDialogError()"),this._status!==Ie.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.DIALOG_ERROR,cause:oe.causes.DIALOG_ERROR})}newDTMF(n){we.debug("newDTMF()"),this.emit("newDTMF",n)}newInfo(n){we.debug("newInfo()"),this.emit("newInfo",n)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(we.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(we.debug("_isReadyToReOffer() | session not established yet"),!1):(we.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(we.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(we.debug("close() | closing local MediaStream"),kt.closeMediaStream(this._localMediaStream)),this._status!==Ie.STATUS_TERMINATED){if(this._status=Ie.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){we.warn("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(n,r){let a=el.T1;function c(){this._status===Ie.STATUS_WAITING_FOR_ACK&&(n.reply(200,null,[`Contact: ${this._contact}`],r),a<el.T2&&(a=a*2,a>el.T2&&(a=el.T2)),this._timers.invite2xxTimer=setTimeout(c.bind(this),a))}this._timers.invite2xxTimer=setTimeout(c.bind(this),a)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===Ie.STATUS_WAITING_FOR_ACK&&(we.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(oe.BYE),this._ended("remote",null,oe.causes.NO_ACK))},el.TIMER_H)}_createRTCConnection(n,r){this.stunServers,this._connection=new RTCPeerConnection(n,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:oe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:oe.causes.RTP_TIMEOUT})});let a;const c=e=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||e.candidate&&(this._candidates.push(e.candidate),clearTimeout(a),a=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=c,we.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(n,r){if(we.debug("createLocalDescription()"),n!=="offer"&&n!=="answer")throw new Error(`createLocalDescription() | invalid type "${n}"`);const a=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>n==="offer"?a.createOffer(r).catch(c=>(we.warn('emit "peerconnection:createofferfailed" [error:%o]',c),this.emit("peerconnection:createofferfailed",c),Promise.reject(c))):a.createAnswer(r).catch(c=>(we.warn('emit "peerconnection:createanswerfailed" [error:%o]',c),this.emit("peerconnection:createanswerfailed",c),Promise.reject(c)))).then(c=>(this.jsepOffer=c,a.setLocalDescription(c).catch(e=>(this._rtcReady=!0,we.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',e),this.emit("peerconnection:setlocaldescriptionfailed",e),Promise.reject(e))))).then(()=>{const c=r&&r.iceRestart;if(a.iceGatheringState==="complete"&&!c||a.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const e={originator:"local",type:n,sdp:a.localDescription.sdp};return we.debug('emit "sdp"'),this.emit("sdp",e),Promise.resolve(e.sdp)}return new Promise(e=>{let f=!1,g,d;this._iceReady=!1;const A=()=>{a.removeEventListener("icecandidate",g),a.removeEventListener("icegatheringstatechange",d),f=!0,this._rtcReady=!0,this._iceReady=!0;const S={originator:"local",type:n,sdp:a.localDescription.sdp};we.debug('emit "sdp"'),this.emit("sdp",S),e(S.sdp)};a.addEventListener("icecandidate",g=S=>{const R=S.candidate;R?this.emit("icecandidate",{candidate:R,ready:A}):f||A()}),a.addEventListener("icegatheringstatechange",d=()=>{a.iceGatheringState==="complete"&&!f&&A()})})})}_createDialog(n,r,a){const c=r==="UAS"?n.to_tag:n.from_tag,e=r==="UAS"?n.from_tag:n.to_tag,f=n.call_id+c+e;let g=this._earlyDialogs[f];if(a)return g?!0:(g=new Pu(this,n,r,Pu.C.STATUS_EARLY),g.error?(we.debug(g.error),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[f]=g,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,g)return g.update(n,r),this._dialog=g,delete this._earlyDialogs[f],!0;const d=new Pu(this,n,r);return d.error?(we.debug(d.error),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(n){we.debug("receiveReinvite()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,a={request:n,callback:void 0,reject:e.bind(this)};let c=!1;function e(g={}){c=!0;const d=g.status_code||403,A=g.reason_phrase||"",S=kt.cloneArray(g.extraHeaders);if(this._status!==Ie.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);n.reply(d,A,S)}if(this.emit("reinvite",a),c)return;if(this._late_sdp=!1,!n.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(g=>{f.call(this,g)}).catch(()=>{n.reply(500)});return}if(r!=="application/sdp"){we.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(g=>{this._status!==Ie.STATUS_TERMINATED&&f.call(this,g)}).catch(g=>{we.warn(g)});function f(g){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,d),this._late_sdp&&(g=this._mangleOffer(g)),n.reply(200,null,d,g,()=>{this._status=Ie.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,g),this._setACKTimer()}),typeof a.callback=="function"&&a.callback()}}_receiveUpdate(n){we.debug("receiveUpdate()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,a={request:n,callback:void 0,reject:e.bind(this)};let c=!1;function e(g={}){c=!0;const d=g.status_code||403,A=g.reason_phrase||"",S=kt.cloneArray(g.extraHeaders);if(this._status!==Ie.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);n.reply(d,A,S)}if(this.emit("update",a),c)return;if(!n.body){f.call(this,null);return}if(r!=="application/sdp"){we.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(g=>{this._status!==Ie.STATUS_TERMINATED&&f.call(this,g)}).catch(g=>{we.warn(g)});function f(g){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,d),n.reply(200,null,d,g),typeof a.callback=="function"&&a.callback()}}_processInDialogSdpOffer(n){we.debug("_processInDialogSdpOffer()");const r=n.parseSDP();let a=!1;for(const f of r.media){if(Lu.indexOf(f.type)===-1)continue;const g=f.direction||r.direction||"sendrecv";if(g==="sendonly"||g==="inactive")a=!0;else{a=!1;break}}const c={originator:"remote",type:"offer",sdp:n.body};we.debug('emit "sdp"'),this.emit("sdp",c);const e=new RTCSessionDescription({type:"offer",sdp:c.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(e).catch(f=>{throw n.reply(488),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',f),this.emit("peerconnection:setremotedescriptionfailed",f),f})}).then(()=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&a===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&a===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(f=>{throw n.reply(500),we.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',f),f})}).catch(f=>{we.warn("_processInDialogSdpOffer() failed [error: %o]",f)}),this._connectionPromiseQueue}_receiveRefer(n){if(we.debug("receiveRefer()"),!n.refer_to){we.debug("no Refer-To header field present in REFER"),n.reply(400);return}if(n.refer_to.uri.scheme!==oe.SIP){we.debug("Refer-To header field points to a non-SIP URI scheme"),n.reply(416);return}n.reply(202);const r=new uC(this,n.cseq);we.debug('emit "refer"'),this.emit("refer",{request:n,accept:(e,f)=>{a.call(this,e,f)},reject:()=>{c.call(this)}});function a(e,f={}){if(e=typeof e=="function"?e:null,this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED)return!1;const g=new qu(this._ua);if(g.on("progress",({response:d})=>{r.notify(d.status_code,d.reason_phrase)}),g.on("accepted",({response:d})=>{r.notify(d.status_code,d.reason_phrase)}),g.on("_failed",({message:d,cause:A})=>{d?r.notify(d.status_code,d.reason_phrase):r.notify(487,A)}),n.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(n.refer_to.uri.getHeader("replaces"));f.extraHeaders=kt.cloneArray(f.extraHeaders),f.extraHeaders.push(`Replaces: ${d}`)}g.connect(n.refer_to.uri.toAor(),f,e)}function c(){r.notify(603)}}_receiveNotify(n){switch(we.debug("receiveNotify()"),n.event||n.reply(400),n.event.event){case"refer":{let r,a;if(n.event.params&&n.event.params.id)r=n.event.params.id,a=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)a=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{n.reply(400,"Missing event id parameter");return}if(!a){n.reply(481,"Subscription does not exist");return}a.receiveNotify(n),n.reply(200);break}default:n.reply(489)}}_receiveReplaces(n){we.debug("receiveReplaces()");function r(c){if(this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED)return!1;const e=new qu(this._ua);e.on("confirmed",()=>{this.terminate()}),e.init_incoming(n,c)}function a(){we.debug("Replaced INVITE rejected by the user"),n.reply(486)}this.emit("replaces",{request:n,accept:c=>{r.call(this,c)},reject:()=>{a.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(n,r,a){this.ackSent=!1,this.publisherSubscribeSent=!1;const c=new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});Promise.resolve().then(()=>{if(a)return a;if(n.audio||n.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(e=>{throw this._status===Ie.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,oe.causes.USER_DENIED_MEDIA_ACCESS),we.warn('emit "getusermediafailed" [error:%o]',e),this.emit("getusermediafailed",e),e)})}).then(e=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=e,e&&e.getTracks().forEach(f=>{this._connection.addTrack(f,e)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(f=>{throw this._failed("local",null,oe.causes.WEBRTC_ERROR),f})}).then(e=>{if(this._is_canceled||this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");const f={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},g=JSON.stringify(f);this._request.body=g,this._status=Ie.STATUS_INVITE_SENT,we.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),c.send()}).catch(e=>{this._status!==Ie.STATUS_TERMINATED&&we.warn(e)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async changeMediaConstraints(n){this.mediaConstraints={...n},await this.processPlugins(),this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}async loadStream(){const n={};this.isAudioOn?this.mediaConstraints.audio?n.audio=this.mediaConstraints.audio:n.audio=!0:n.audio=!1,this.isVideoOn?this.mediaConstraints.video?n.video=this.mediaConstraints.video:n.video=!0:n.video=!1;let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch{try{n.video=!1,r=await navigator.mediaDevices.getUserMedia(n)}catch{n.audio=!1,n.video=!1,r=await navigator.mediaDevices.getUserMedia(n)}}return r}addTracks(n){this._connection.getSenders().forEach(r=>{this._connection.removeTrack(r)}),n.forEach(r=>{this._connection.addTrack(r)})}getRecordFileName(){return gA+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let n=0;n<this.iceCandidates.length;n++)await this._connection.addIceCandidate(this.iceCandidates[n]);this.iceCandidates=[]}async _sendConfigureMessage(n){const r=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handle_id,session_id:this.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...n},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...r]},c=["Content-Type: application/json",this.getPTypeHeader(ir.ICE)];this.sendRequest(oe.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{this.isConfigureSent=!0;const f=e.data.split(`\r
|
|
135
|
-
`),g=f[f.length-1],d=JSON.parse(g);await this._connection.setRemoteDescription(d.jsep),this._candidates=[]}}})}_sendMemberStartMessage(n,r){const a={janus:"message",body:{request:"start",room:this.room_id},handle_id:n.handleId,session_id:this.session_id,jsep:r},c=["Content-Type: application/json",this.getPTypeHeader(ir.CONFIGURE)];this.sendRequest(oe.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{e.status_code===200&&await n.rtcpPeer.setLocalDescription(r)}}})}_sendTrickleMessage(n){const r={trickles:[...n.map(c=>({janus:"trickle",candidate:c,handle_id:this.handle_id,session_id:this.session_id}))]},a=[this.getPTypeHeader(ir.TRICKLE)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{}}})}async _answerAttachedStream(n,r){let a=null;const c=async d=>{if(!n.rtcpPeer||n.loaded)return;{n.loaded=!0;const H={audio:!0,video:!0};await new Promise(W=>{setTimeout(W,100)}),a=await n.rtcpPeer.createAnswer(H),this._sendMemberStartMessage(n,a)}const A=d.streams[0].getAudioTracks(),S=d.streams[0].getVideoTracks(),R=[];A[0]&&R.push(A[0]),S[0]&&R.push(S[0]);const N=new MediaStream(R);n.stream=N,this._ua.emit("memberJoin",n.memberInfo)};let e,f=[];const g=d=>{n.rtcpPeer.signalingState!=="stable"&&n.rtcpPeer.signalingState!=="have-local-offer"||(f.push(d.candidate||null),clearTimeout(e),e=setTimeout(()=>{this._sendTrickleMessage(f)},500))};n.rtcpPeer=new RTCPeerConnection,n.rtcpPeer.ontrack=c,n.rtcpPeer.onicecandidate=g,n.rtcpPeer.sender=r.sender,await n.rtcpPeer.setRemoteDescription(r.jsep)}_sendJoinMemberRequest(n){const r={janus:"message",body:{request:"join",room:this.room_id,feed:n.info.id,ptype:"subscriber"},handle_id:n.handleId,session_id:this.session_id},a=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(oe.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{var e,f;if(c.status_code===200){const g=JSON.parse(c.body);(f=(e=g?.plugindata)==null?void 0:e.data)!=null&&f.id&&await this._answerAttachedStream(n,g)}}}})}_attachMember(n){const r={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},a=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{if(c.status_code===200){const e=JSON.parse(c.body).data.id;n.handleId=e,this._sendJoinMemberRequest(n)}}}})}_detachMember(n){const r={janus:"detach",handle_id:n.handleId,session_id:this.session_id},a=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r)}),Fr.stopStreamTracks(n.memberInfo.stream),this._ua.emit("memberHangup",n.memberInfo)}receivePublishers(n){var r,a,c,e,f,g,d,A;const S={...this.memberList};(a=(r=n?.plugindata)==null?void 0:r.data)==null||a.publishers.forEach(R=>{delete S[R.id],!this.memberList[R.id]&&!this.myFeedList.includes(R.id)&&R.clientID!==this.client_id&&(this.memberList[R.id]=new fA(R,this),this._attachMember(this.memberList[R.id]))}),((e=(c=n?.plugindata)==null?void 0:c.data)==null?void 0:e.videoroom)==="synced"&&Object.keys(S).forEach(R=>{S[R].hangup(),delete this.memberList[R]}),this.publishers=(g=(f=n?.plugindata)==null?void 0:f.data)==null?void 0:g.publishers,this.private_id=(A=(d=n?.plugindata)==null?void 0:d.data)==null?void 0:A.private_id}receiveUnpublished(n){const r=this.memberList[n];r&&(r.hangup(),this._detachMember(r),delete this.memberList[n])}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 n=this._ua.processStreamPlugins;let r=await this.loadStream();for(const a of n)r=await a.process(r);this.stream.getTracks().forEach(a=>{this.stream.removeTrack(a),a.stop()}),r.getTracks().forEach(a=>{this.stream.addTrack(a)})}async resyncPlugins(n){const r=this._ua.processStreamPlugins.filter(a=>a.type===n);for(const a of r)a.running&&a.terminate();if(n==="video"){let a=await this.loadStream();for(const c of r)c.running&&(a=await c.start(a));this.stream.getTracks().forEach(c=>{this.stream.removeTrack(c),c.stop()}),a.getTracks().forEach(c=>{this.stream.addTrack(c)}),this._overrideSenderTracks(this.stream,this._connection),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}else{const a=this._ua.newStreamPlugins.find(f=>f.type===n);let c=a.getStream().clone();for(const f of r)f.running&&(c=await f.start(c));const e=a.getConnection();this._overrideSenderTracks(c,e),this._ua.emit("changePluginStream",{type:n,stream:c})}}stopProcessPlugins(n){const r=this._ua.processStreamPlugins.filter(a=>a.type===n);for(const a of r)a.running&&a.kill()}_receiveInviteResponse(n){if(we.debug("receiveInviteResponse()"),this._dialog&&n.status_code>=200&&n.status_code<=299&&!this.ackSent)if(this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.ackSent=!0,this.sendRequest(oe.ACK);return}else{const r=new Pu(this,n,"UAC");if(r.error!==void 0){we.debug(r.error);return}this.sendRequest(oe.ACK),this.sendRequest(oe.BYE);return}if(this.ackSent&&!this.publisherSubscribeSent){const r=JSON.parse(n.body);this.setupMediaStream().then(()=>{this.session_id=r.session_id,this.handle_id=r.data.id,this.client_id=gf();const a={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},c=[this.getPTypeHeader(ir.PUBLISHER)];this.sendRequest(oe.SUBSCRIBE,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{var f,g,d,A;if(e.status_code===200){if(this.subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((g=(f=S.plugindata)==null?void 0:f.data)==null?void 0:g.videoroom)==="joined"&&this.myFeedList.push(S.plugindata.data.id),(A=(d=S.plugindata)==null?void 0:d.data)!=null&&A.publishers&&this.receivePublishers(S)}catch(S){console.error(S)}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){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==Ie.STATUS_INVITE_SENT&&this._status!==Ie.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(n.status_code):this._status=Ie.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){we.debug("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=Ie.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};we.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",n)).catch(c=>{we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(this._status=Ie.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,oe.causes.MISSING_SDP),this._failed("remote",n,oe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;break}default:{const r=kt.sipErrorCause(n.status_code);this._failed("remote",n,r)}}}_sendReinvite(n={}){we.debug("sendReinvite()");const r=kt.cloneArray(n.extraHeaders),a=kt.cloneObject(n.eventHandlers),c=n.rtcOfferConstraints||this._rtcOfferConstraints||null;let e=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",c)).then(d=>{d=this._mangleOffer(d);const A={originator:"local",type:"offer",sdp:d};we.debug('emit "sdp"'),this.emit("sdp",A),this.sendRequest(oe.INVITE,{extraHeaders:r,body:d,eventHandlers:{onSuccessResponse:S=>{f.call(this,S),e=!0},onErrorResponse:S=>{g.call(this,S)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{g()});function f(d){if(this._status===Ie.STATUS_TERMINATED||(this.sendRequest(oe.ACK),e))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){g.call(this);return}}else{g.call(this);return}const A={originator:"remote",type:"answer",sdp:d.body};we.debug('emit "sdp"'),this.emit("sdp",A);const S=new RTCSessionDescription({type:"answer",sdp:A.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(S)).then(()=>{a.succeeded&&a.succeeded(d)}).catch(R=>{g.call(this),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),this.emit("peerconnection:setremotedescriptionfailed",R)})}function g(d){a.failed&&a.failed(d)}}_sendUpdate(n={}){we.debug("sendUpdate()");const r=kt.cloneArray(n.extraHeaders),a=kt.cloneObject(n.eventHandlers),c=n.rtcOfferConstraints||this._rtcOfferConstraints||null,e=n.sdpOffer||!1;let f=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),e?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",c)).then(A=>{A=this._mangleOffer(A);const S={originator:"local",type:"offer",sdp:A};we.debug('emit "sdp"'),this.emit("sdp",S),this.sendRequest(oe.UPDATE,{extraHeaders:r,body:A,eventHandlers:{onSuccessResponse:R=>{g.call(this,R),f=!0},onErrorResponse:R=>{d.call(this,R)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{d.call(this)})):this.sendRequest(oe.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:A=>{g.call(this,A)},onErrorResponse:A=>{d.call(this,A)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function g(A){if(this._status!==Ie.STATUS_TERMINATED&&!f)if(this._handleSessionTimersInIncomingResponse(A),e){if(A.body){if(!A.hasHeader("Content-Type")||A.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const S={originator:"remote",type:"answer",sdp:A.body};we.debug('emit "sdp"'),this.emit("sdp",S);const R=new RTCSessionDescription({type:"answer",sdp:S.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(R)).then(()=>{a.succeeded&&a.succeeded(A)}).catch(N=>{d.call(this),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',N),this.emit("peerconnection:setremotedescriptionfailed",N)})}else a.succeeded&&a.succeeded(A)}function d(A){a.failed&&a.failed(A)}}_acceptAndTerminate(n,r,a){we.debug("acceptAndTerminate()");const c=[];r&&(a=a||oe.REASON_PHRASE[r]||"",c.push(`Reason: SIP ;cause=${r}; text="${a}"`)),(this._dialog||this._createDialog(n,"UAC"))&&(this.sendRequest(oe.ACK),this.sendRequest(oe.BYE,{extraHeaders:c})),this._status=Ie.STATUS_TERMINATED}_mangleOffer(n){if(!this._localHold&&!this._remoteHold)return n;if(n=nr.parse(n),this._localHold&&!this._remoteHold){we.debug("mangleOffer() | me on hold, mangling offer");for(const r of n.media)Lu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){we.debug("mangleOffer() | both on hold, mangling offer");for(const r of n.media)Lu.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){we.debug("mangleOffer() | remote on hold, mangling offer");for(const r of n.media)Lu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return nr.write(n)}_setLocalMediaStatus(){let n=!0,r=!0;(this._localHold||this._remoteHold)&&(n=!1,r=!1),this._audioMuted&&(n=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!n),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(n,r){if(!this._sessionTimers.enabled)return;let a;n.session_expires&&n.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,a=n.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,a="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${a}`),this._sessionTimers.refresher=a==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const n=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==Ie.STATUS_TERMINATED&&this._isReadyToReOffer()&&(we.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===oe.UPDATE?this._sendUpdate():this._sendReinvite())},n*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==Ie.STATUS_TERMINATED&&(we.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:oe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},n*1100)}_toggleMuteAudio(n){const r=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="audio");for(const a of r)a.track.enabled=!n}_toggleMuteVideo(n){const r=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="video");for(const a of r)a.track.enabled=!n}_newJanusSession(n,r){we.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:n,session:this,request:r})}_connecting(n){we.debug("session connecting"),we.debug('emit "connecting"'),this.emit("connecting",{request:n})}_progress(n,r){we.debug("session progress"),we.debug('emit "progress"'),this.emit("progress",{originator:n,response:r||null})}_accepted(n,r){we.debug("session accepted"),this._start_time=new Date,we.debug('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){we.debug("session confirmed"),this._is_confirmed=!0,we.debug('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,a){we.debug("session ended"),this._end_time=new Date,this._close(),we.debug('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:a})}_failed(n,r,a){we.debug("session failed"),we.debug('emit "_failed"'),this.emit("_failed",{originator:n,message:r||null,cause:a}),this._close(),we.debug('emit "failed"'),this.emit("failed",{originator:n,message:r||null,cause:a})}_onhold(n){we.debug("session onhold"),this._setLocalMediaStatus(),we.debug('emit "hold"'),this.emit("hold",{originator:n})}_onunhold(n){we.debug("session onunhold"),this._setLocalMediaStatus(),we.debug('emit "unhold"'),this.emit("unhold",{originator:n})}_onmute({audio:n,video:r}){we.debug("session onmute"),this._setLocalMediaStatus(),we.debug('emit "muted"'),this.emit("muted",{audio:n,video:r})}_onunmute({audio:n,video:r}){we.debug("session onunmute"),this._setLocalMediaStatus(),we.debug('emit "unmuted"'),this.emit("unmuted",{audio:n,video:r})}}class ro{constructor(n){if(this.headers={},n.length>0){let r=!1;const a=n.split(`\r
|
|
134
|
+
`,uf.send(a)}const JC=Qt(cf);var pl={};const no=$n(),Ta=bt,Sd=Hr(),df=Ms(),Ed=gd,Cd=Ls;pl.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:Ta.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:Ta.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:Ta.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${no.createRandomToken(12)}.invalid`};const Nu={mandatory:{sockets(o){const n=[];if(Ed.isSocket(o))n.push({socket:o});else if(Array.isArray(o)&&o.length)for(const r of o)Object.prototype.hasOwnProperty.call(r,"socket")&&Ed.isSocket(r.socket)?n.push(r):Ed.isSocket(r)&&n.push({socket:r});else return;return n},uri(o){/^sip:/i.test(o)||(o=`${Ta.SIP}:${o}`);const n=df.parse(o);if(n)return n.user?n:void 0}},optional:{authorization_user(o){if(Sd.parse(`"${o}"`,"quoted_string")!==-1)return o},authorization_jwt(o){if(typeof o=="string")return o},user_agent(o){if(typeof o=="string")return o},connection_recovery_max_interval(o){if(no.isDecimal(o)){const n=Number(o);if(n>0)return n}},connection_recovery_min_interval(o){if(no.isDecimal(o)){const n=Number(o);if(n>0)return n}},contact_uri(o){if(typeof o=="string"){const n=Sd.parse(o,"SIP_URI");if(n!==-1)return n}},display_name(o){return o},instance_id(o){if(/^uuid:/i.test(o)&&(o=o.substr(5)),Sd.parse(o,"uuid")!==-1)return o},no_answer_timeout(o){if(no.isDecimal(o)){const n=Number(o);if(n>0)return n}},session_timers(o){if(typeof o=="boolean")return o},session_timers_refresh_method(o){if(typeof o=="string"&&(o=o.toUpperCase(),o===Ta.INVITE||o===Ta.UPDATE))return o},session_timers_force_refresher(o){if(typeof o=="boolean")return o},password(o){return String(o)},realm(o){return String(o)},ha1(o){return String(o)},register(o){if(typeof o=="boolean")return o},register_expires(o){if(no.isDecimal(o)){const n=Number(o);if(n>0)return n}},registrar_server(o){/^sip:/i.test(o)||(o=`${Ta.SIP}:${o}`);const n=df.parse(o);if(n)return n.user?void 0:n},use_preloaded_route(o){if(typeof o=="boolean")return o},extra_headers(o){const n=[];if(Array.isArray(o)&&o.length)for(const r of o)typeof r=="string"&&n.push(r);else return;return n}}};pl.load=(o,n)=>{for(const r in Nu.mandatory)if(n.hasOwnProperty(r)){const a=n[r],c=Nu.mandatory[r](a);if(c!==void 0)o[r]=c;else throw new Cd.ConfigurationError(r,a)}else throw new Cd.ConfigurationError(r);for(const r in Nu.optional)if(n.hasOwnProperty(r)){const a=n[r];if(no.isEmpty(a))continue;const c=Nu.optional[r](a);if(c!==void 0)o[r]=c;else throw new Cd.ConfigurationError(r,a)}};const QC=Tn.EventEmitter,ZC=mn,kn=bt,eA=FE,hf=ef,pf=AC,_f=OC,Ad=eo,tA=sf,Mu=$n(),nA=Ls,rA=Ms(),sA=af,Id=On,iA=cf,Rd=pl,Kt=new ZC("UA"),Dn={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var ff=class extends QC{static get C(){return Dn}constructor(o){if(Kt.debug("new() [configuration:%o]",o),super(),this._cache={credentials:{}},this._configuration=Object.assign({},Rd.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=Dn.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,o===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(o)}catch(n){throw this._status=Dn.STATUS_NOT_READY,this._error=Dn.CONFIGURATION_ERROR,n}this._registrator=new eA(this)}get C(){return Dn}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){Kt.debug("start()"),this._status===Dn.STATUS_INIT?this._transport.connect():this._status===Dn.STATUS_USER_CLOSED?(Kt.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Dn.STATUS_INIT,this._transport.connect()):this._status===Dn.STATUS_READY?Kt.debug("UA is in READY status, not restarted"):Kt.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){Kt.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(o){Kt.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(o)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(o,n){Kt.debug("call()");const r=new hf(this);return r.connect(o,n),r}sendMessage(o,n,r){Kt.debug("sendMessage()");const a=new pf(this);return a.send(o,n,r),a}sendOptions(o,n,r){Kt.debug("sendOptions()");const a=new _f(this);return a.send(o,n,r),a}terminateSessions(o){Kt.debug("terminateSessions()");for(const n in this._sessions)this._sessions[n].isEnded()||this._sessions[n].terminate(o)}stop(){if(Kt.debug("stop()"),this._dynConfiguration={},this._status===Dn.STATUS_USER_CLOSED){Kt.debug("UA already closed");return}this._registrator.close();const o=Object.keys(this._sessions).length;for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){Kt.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch{}}for(const n in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,n))try{this._applicants[n].close()}catch{}this._status=Dn.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&&o===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(o){return Mu.normalizeTarget(o,this._configuration.hostport_params)}get(o){switch(o){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:Kt.warn('get() | cannot get "%s" parameter in runtime',o);return}}set(o,n){switch(o){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 Kt.warn('set() | cannot set "%s" parameter in runtime',o),!1}return!0}newTransaction(o){this._transactions[o.type][o.id]=o,this.emit("newTransaction",{transaction:o})}destroyTransaction(o){delete this._transactions[o.type][o.id],this.emit("transactionDestroyed",{transaction:o})}newDialog(o){this._dialogs[o.id]=o}destroyDialog(o){delete this._dialogs[o.id]}newMessage(o,n){this._applicants[o]=o,this.emit("newMessage",n)}newOptions(o,n){this._applicants[o]=o,this.emit("newOptions",n)}destroyMessage(o){delete this._applicants[o]}newRTCSession(o,n){this._sessions[o.id]=o,this.emit("newRTCSession",n)}destroyRTCSession(o){delete this._sessions[o.id]}registered(o){this.emit("registered",o)}unregistered(o){this.emit("unregistered",o)}registrationFailed(o){this.emit("registrationFailed",o)}receiveRequest(o){const n=o.method;if(o.ruri.user!==this._configuration.uri.user&&o.ruri.user!==this._contact.uri.user){Kt.debug("Request-URI does not point to us"),o.method!==kn.ACK&&o.reply_sl(404);return}if(o.ruri.scheme===kn.SIPS){o.reply_sl(416);return}if(Ad.checkTransaction(this,o))return;if(n===kn.INVITE?new Ad.InviteServerTransaction(this,this._transport,o):n!==kn.ACK&&n!==kn.CANCEL&&new Ad.NonInviteServerTransaction(this,this._transport,o),n===kn.OPTIONS){if(this.listeners("newOptions").length===0){o.reply(200);return}new _f(this).init_incoming(o)}else if(n===kn.MESSAGE){if(this.listeners("newMessage").length===0){o.reply(405);return}new pf(this).init_incoming(o)}else if(n===kn.INVITE&&!o.to_tag&&this.listeners("newRTCSession").length===0){o.reply(405);return}let r,a;if(o.to_tag)r=this._findDialog(o.call_id,o.from_tag,o.to_tag),r?r.receiveRequest(o):n===kn.NOTIFY?(a=this._findSession(o),a?a.receiveRequest(o):(Kt.debug("received NOTIFY request for a non existent subscription"),o.reply(481,"Subscription does not exist"))):n!==kn.ACK&&o.reply(481);else switch(n){case kn.INVITE:if(window.RTCPeerConnection)if(o.hasHeader("replaces")){const c=o.replaces;r=this._findDialog(c.call_id,c.from_tag,c.to_tag),r?(a=r.owner,a.isEnded()?o.reply(603):a.receiveRequest(o)):o.reply(481)}else a=new hf(this),a.init_incoming(o);else Kt.warn("INVITE received but WebRTC is not supported"),o.reply(488);break;case kn.BYE:o.reply(481);break;case kn.CANCEL:a=this._findSession(o),a?a.receiveRequest(o):Kt.debug("received CANCEL request for a non existent session");break;case kn.ACK:break;case kn.NOTIFY:this.emit("sipEvent",{event:o.event,request:o}),o.reply(200);break;default:o.reply(405);break}}_findSession({call_id:o,from_tag:n,to_tag:r}){const a=o+n,c=this._sessions[a],e=o+r,_=this._sessions[e];return c||_||null}_findDialog(o,n,r){let a=o+n+r,c=this._dialogs[a];return c||(a=o+r+n,c=this._dialogs[a],c||null)}_loadConfig(o){try{Rd.load(this._configuration,o)}catch(a){throw a}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Mu.newUUID()),this._configuration.jssip_id=Mu.createRandomToken(5);const n=this._configuration.uri.clone();n.user=null,this._configuration.hostport_params=n.toString().replace(/^sip:/i,"");try{this._transport=new tA(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=aA.bind(this),this._transport.onconnect=oA.bind(this),this._transport.ondisconnect=lA.bind(this),this._transport.ondata=uA.bind(this)}catch(a){throw Kt.warn(a),new nA.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 rA("sip",Mu.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 c=a.anonymous||null,e=a.outbound||null;let _="<";return c?_+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":_+=this.pub_gruu||this.uri.toString(),e&&(c?!this.temp_gruu:!this.pub_gruu)&&(_+=";ob"),_+=">",_}};const r=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const a in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,a)&&(r.indexOf(a)!==-1?Object.defineProperty(this._configuration,a,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,a,{writable:!1,configurable:!1}));Kt.debug("configuration parameters after validation:");for(const a in this._configuration)if(Object.prototype.hasOwnProperty.call(Rd.settings,a))switch(a){case"uri":case"registrar_server":Kt.debug(`- ${a}: ${this._configuration[a]}`);break;case"password":case"ha1":case"authorization_jwt":Kt.debug(`- ${a}: NOT SHOWN`);break;default:Kt.debug(`- ${a}: ${JSON.stringify(this._configuration[a])}`)}}};function aA(o){this.emit("connecting",o)}function oA(o){this._status!==Dn.STATUS_USER_CLOSED&&(this._status=Dn.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function lA(o){const n=["nict","ict","nist","ist"];for(const r of n)for(const a in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],a)&&this._transactions[r][a].onTransportError();this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==Dn.STATUS_USER_CLOSED&&(this._status=Dn.STATUS_NOT_READY,this._error=Dn.NETWORK_ERROR)}function uA(o){const n=o.transport;let r=o.message;if(r=sA.parseMessage(r,this),!!r&&!(this._status===Dn.STATUS_USER_CLOSED&&r instanceof Id.IncomingRequest)&&iA(r,this,n)){if(r instanceof Id.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Id.IncomingResponse){let a;switch(r.method){case kn.INVITE:a=this._transactions.ict[r.via_branch],a&&a.receiveResponse(r);break;case kn.ACK:break;default:a=this._transactions.nict[r.via_branch],a&&a.receiveResponse(r);break}}}}const cA=Qt(ff);for(var Nn=[],$d=0;$d<256;++$d)Nn.push(($d+256).toString(16).slice(1));function dA(o,n=0){return(Nn[o[n+0]]+Nn[o[n+1]]+Nn[o[n+2]]+Nn[o[n+3]]+"-"+Nn[o[n+4]]+Nn[o[n+5]]+"-"+Nn[o[n+6]]+Nn[o[n+7]]+"-"+Nn[o[n+8]]+Nn[o[n+9]]+"-"+Nn[o[n+10]]+Nn[o[n+11]]+Nn[o[n+12]]+Nn[o[n+13]]+Nn[o[n+14]]+Nn[o[n+15]]).toLowerCase()}var Uu,hA=new Uint8Array(16);function pA(){if(!Uu&&(Uu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Uu))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Uu(hA)}var _A=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const mf={randomUUID:_A};function gf(o,n,r){if(mf.randomUUID&&!n&&!o)return mf.randomUUID();o=o||{};var a=o.random||(o.rng||pA)();if(a[6]=a[6]&15|64,a[8]=a[8]&63|128,n){r=r||0;for(var c=0;c<16;++c)n[r+c]=a[c];return n}return dA(a)}var kt=$n();const qs=Qt(kt),xd=new wu("Dialog"),_i={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class Pu{static get C(){return _i}constructor(n,r,a,c=_i.STATUS_CONFIRMED){if(this._owner=n,this._ua=n._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,r instanceof On.IncomingResponse&&(c=r.status_code<200?_i.STATUS_EARLY:_i.STATUS_CONFIRMED),a==="UAS"){this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=c,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri;let e=r.getHeaders("to")[0].split(";")[0];e=e.match(/<([^>]*)>/)[1],this._remote_target=e,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(a==="UAC"){this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=c,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri;let e=r.getHeaders("to")[0].split(";")[0];e=e.match(/<([^>]*)>/)[1],this._remote_target=e,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),xd.debug(`new ${a} dialog created with status ${this._state===_i.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(n){this._local_seqnum=n}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(n){this._uac_pending_reply=n}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===_i.STATUS_TERMINATED}update(n,r){this._state=_i.STATUS_CONFIRMED,xd.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),r==="UAC"&&(this._route_set=n.getHeaders("record-route").reverse())}terminate(){xd.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=_i.STATUS_TERMINATED}sendRequest(n,r={}){const a=qs.cloneArray(r.extraHeaders),c=qs.cloneObject(r.eventHandlers),e=r.body||null,_=this._createRequest(n,a,e);return c.onAuthenticated=()=>{this._local_seqnum+=1},new KE(this,_,c).send(),_}receiveRequest(n){this._checkInDialogRequest(n)&&(n.method===oe.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:n.method===oe.INVITE&&(this._ack_seqnum=n.cseq),this._owner.receiveRequest(n))}_createRequest(n,r,a){r=qs.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const c=n===oe.CANCEL||n===oe.ACK?this._local_seqnum:this._local_seqnum+=1;return new On.OutgoingRequest(n,this._remote_target,this._ua,{cseq:c,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},r,a)}_checkInDialogRequest(n){if(!this._remote_seqnum)this._remote_seqnum=n.cseq;else if(n.cseq<this._remote_seqnum)if(n.method===oe.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===oe.INVITE||n.method===oe.UPDATE&&n.body){if(this._uac_pending_reply===!0)n.reply(491);else if(this._uas_pending_reply===!0){const r=(Math.random()*10|0)+1;return n.reply(500,null,[`Retry-After:${r}`]),!1}else{this._uas_pending_reply=!0;const r=()=>{(n.server_transaction.state===Ir.C.STATUS_ACCEPTED||n.server_transaction.state===Ir.C.STATUS_COMPLETED||n.server_transaction.state===Ir.C.STATUS_TERMINATED)&&(n.server_transaction.removeListener("stateChanged",r),this._uas_pending_reply=!1)};n.server_transaction.on("stateChanged",r)}n.hasHeader("contact")&&n.server_transaction.on("stateChanged",()=>{n.server_transaction.state===Ir.C.STATUS_ACCEPTED&&(this._remote_target=n.parseHeader("contact").uri)})}else n.method===oe.NOTIFY&&n.hasHeader("contact")&&n.server_transaction.on("stateChanged",()=>{n.server_transaction.state===Ir.C.STATUS_COMPLETED&&(this._remote_target=n.parseHeader("contact").uri)});return!0}}class fA{constructor(n,r){rs(this,"plugin",null),rs(this,"rtcpPeer",null),rs(this,"handleId",0),rs(this,"info",null),rs(this,"joinResult",null),rs(this,"state",{}),rs(this,"stream",null),rs(this,"loaded",!1),rs(this,"aTracks",[]),rs(this,"vTracks",[]),this.info=n,this.plugin=r,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(n){var r;this.state={...this.state,...n||{}},(r=this.plugin)==null||r.session.emit("member:update",this.memberInfo)}updateMemberStateFromMessage(n){var r,a,c,e;const _=(a=(r=n?.plugindata)==null?void 0:r.data)==null?void 0:a.newStatePublisher,g=((e=(c=n?.plugindata)==null?void 0:c.data)==null?void 0:e.publisher_state).find(d=>d.id===_);this.updateMemberState(g?.state)}hangup(){this.rtcpPeer&&(this.rtcpPeer.close(),this.rtcpPeer=null),this.stream&&this.stream.getTracks().forEach(n=>{n.stop()})}}class Fr{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(n){return Fr.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind===n):[]}static async getMicrophoneList(){return(await Fr.getDevices("audioinput")).map((n,r)=>({...n,deviceId:n.deviceId,label:n.label||`microphone ${r+1}`,kind:n.kind,groupId:n.groupId}))}static async getSpeakerList(){return(await Fr.getDevices("audiooutput")).map((n,r)=>({...n,deviceId:n.deviceId,label:n.label||`speaker ${r+1}`,kind:n.kind,groupId:n.groupId}))}static async getCameraList(){return(await Fr.getDevices("videoinput")).map((n,r)=>({...n,deviceId:n.deviceId,label:n.label||`camera ${r+1}`,kind:n.kind,groupId:n.groupId}))}static stopStreamTracks(n){n&&n.getTracks().forEach(r=>{r.stop()})}static async getMediaFromInputs({videoInput:n,audioInput:r}){let a,c;n==="default"?a=!0:n&&n!=="default"&&(a={deviceId:{exact:n}}),r==="default"?c=!0:r&&r!=="default"&&(c={deviceId:{exact:r}});const e={audio:c,video:a};return Fr.getUserMedia(e)}static async getUserMedia(n){return await navigator.mediaDevices.getUserMedia(n)}static async changeAudioOutput(n,r){if(!(!n||!r))if(typeof n.sinkId<"u")try{await n.setSinkId(r)}catch(a){let c=a;a.name==="SecurityError"&&(c=`You need to use HTTPS for selecting audio output device: ${a}`),console.error(c)}else console.warn("Browser does not support output device selection.")}static toggleAudioMute(n){const r=n.getAudioTracks();if(r.length!==0)return r.forEach(a=>{a.enabled=!a.enabled}),r[0].enabled}static toggleVideoMute(n){const r=n.getVideoTracks();if(r.length!==0)return r.forEach(a=>{a.enabled=!a.enabled}),r[0].enabled}static async getStream(n={video:!0,audio:!0}){try{const r=await navigator.mediaDevices.getUserMedia(n);let a=r.getTracks();return n.video?a=r.getVideoTracks():n.audio&&(a=r.getAudioTracks()),a.length===0?{stream:r,track:null}:{stream:r,track:a[0]}}catch(r){return console.warn(r),{stream:null,track:null}}}}var mA=Ms();const ba=Qt(mA),ir={LEAVE:"Leave",DETACH:"Detach",AUDIO_CHANGE:"AudioChange",VIDEO_CHANGE:"VideoChange",STATE:"State",ICE:"Ice",CONFIGURE:"Configure",TRICKLE:"Trickle",SUBSCRIBER:"Subscriber",PUBLISHER:"Publisher"},we=new wu("JanusSession"),gA="/opt/recordings/",Ie={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},Lu=["audio","video"];class qu extends Tn.EventEmitter{static get C(){return Ie}constructor(n){we.debug("new"),super(),this._id=null,this._ua=n,this._status=Ie.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:oe.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 Ie}get causes(){return oe.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(n){this._data=n}get status(){return this._status}isInProgress(){switch(this._status){case Ie.STATUS_NULL:case Ie.STATUS_INVITE_SENT:case Ie.STATUS_1XX_RECEIVED:case Ie.STATUS_INVITE_RECEIVED:case Ie.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case Ie.STATUS_ANSWERED:case Ie.STATUS_WAITING_FOR_ACK:case Ie.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case Ie.STATUS_CANCELED:case Ie.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(n){return`PTYPE: ${n}`}generateOpaqueId(){return`videoroomtest-${gf().replace(/-/g,"").slice(0,12)}`}connect(n,r,a={},c){we.debug("connect()"),this.display_name=r;const e=n,_=kt.cloneObject(a.eventHandlers),g=kt.cloneArray(a.extraHeaders),d=kt.cloneObject(a.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={...d};const A=a.mediaStream||null,S=kt.cloneObject(a.pcConfig,{iceServers:[]}),R=a.rtcConstraints||null,N=a.rtcOfferConstraints||null;if(this._rtcOfferConstraints=N,this._rtcAnswerConstraints=a.rtcAnswerConstraints||null,this._data=a.data||this._data,n===void 0)throw new TypeError("Not enough arguments");if(this._status!==Ie.STATUS_NULL)throw new di.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new di.NotSupportedError("WebRTC not supported");if(n=this._ua.normalizeTarget(n),this.room_id=n.user,this.target=n,!n)throw new TypeError(`Invalid target: ${e}`);this._sessionTimers.enabled&&kt.isDecimal(a.sessionTimersExpires)&&(a.sessionTimersExpires>=oe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=a.sessionTimersExpires:this._sessionTimers.defaultExpires=oe.SESSION_EXPIRES);for(const G in _)Object.prototype.hasOwnProperty.call(_,G)&&this.on(G,_[G]);this._from_tag=kt.newTag();const H=a.anonymous||!1,W={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:H,outbound:!0}),H?(W.from_display_name="Anonymous",W.from_uri=new ba("sip","anonymous","anonymous.invalid"),g.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),g.push("Privacy: id")):a.fromUserName&&(W.from_uri=new ba("sip",a.fromUserName,this._ua.configuration.uri.host),g.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),a.fromDisplayName&&(W.from_display_name=a.fromDisplayName),g.push(`Contact: ${this._contact}`),g.push("Content-Type: application/json"),this._sessionTimers.enabled&&g.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new On.InitialOutgoingInviteRequest(n,this._ua,W,g),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(S,R),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,c&&c(this),this._newJanusSession("local",this._request),this._sendInitialRequest(d,N,A)}_overrideSenderTracks(n,r){n.getTracks().forEach(a=>{r.getSenders().forEach(async c=>{c.track.kind===a.kind&&(a.kind==="audio"&&!this.isAudioOn&&(a.enabled=!1),a.kind==="video"&&!this.isVideoOn&&(a.enabled=!1),await c.replaceTrack(a))})})}init_incoming(n,r){we.debug("init_incoming()");let a;const c=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&c!=="application/sdp"){n.reply(415);return}if(this._status=Ie.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(a=n.getHeader("expires")*1e3),n.to_tag=kt.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=Ie.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),this._failed("local",null,oe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===Ie.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),this._failed("system",null,oe.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),this._newJanusSession("remote",n),this._status!==Ie.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(n={}){we.debug("answer()");const r=this._request,a=kt.cloneArray(n.extraHeaders),c=kt.cloneObject(n.mediaConstraints),e=n.mediaStream||null,_=kt.cloneObject(n.pcConfig,{iceServers:[]}),g=n.rtcConstraints||null,d=n.rtcAnswerConstraints||null,A=kt.cloneObject(n.rtcOfferConstraints);let S,R=!1,N=!1,H=!1,W=!1;if(this._rtcAnswerConstraints=d,this._rtcOfferConstraints=n.rtcOfferConstraints||null,this._data=n.data||this._data,this._direction!=="incoming")throw new di.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==Ie.STATUS_WAITING_FOR_ANSWER)throw new di.InvalidStateError(this._status);if(this._sessionTimers.enabled&&kt.isDecimal(n.sessionTimersExpires)&&(n.sessionTimersExpires>=oe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=n.sessionTimersExpires:this._sessionTimers.defaultExpires=oe.SESSION_EXPIRES),this._status=Ie.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),a.unshift(`Contact: ${this._contact}`);const G=r.parseSDP();Array.isArray(G.media)||(G.media=[G.media]);for(const K of G.media)K.type==="audio"&&(R=!0,(!K.direction||K.direction==="sendrecv")&&(H=!0)),K.type==="video"&&(N=!0,(!K.direction||K.direction==="sendrecv")&&(W=!0));if(e&&c.audio===!1){S=e.getAudioTracks();for(const K of S)e.removeTrack(K)}if(e&&c.video===!1){S=e.getVideoTracks();for(const K of S)e.removeTrack(K)}!e&&c.audio===void 0&&(c.audio=H),!e&&c.video===void 0&&(c.video=W),!e&&!R&&!A.offerToReceiveAudio&&(c.audio=!1),!e&&!N&&!A.offerToReceiveVideo&&(c.video=!1),this._createRTCConnection(_,g),Promise.resolve().then(()=>{if(e)return e;if(c.audio||c.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(K=>{throw this._status===Ie.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,oe.causes.USER_DENIED_MEDIA_ACCESS),we.warn('emit "getusermediafailed" [error:%o]',K),this.emit("getusermediafailed",K),new Error("getUserMedia() failed"))})}).then(K=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=K,K&&K.getTracks().forEach(ae=>{this._connection.addTrack(ae,K)})}).then(()=>{if(this._late_sdp)return;const K={originator:"remote",type:"offer",sdp:r.body};we.debug('emit "sdp"'),this.emit("sdp",K);const ae=new RTCSessionDescription({type:"offer",sdp:K.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(ae)).catch(ee=>{throw r.reply(488),this._failed("system",null,oe.causes.WEBRTC_ERROR),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',ee),this.emit("peerconnection:setremotedescriptionfailed",ee),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",d).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(K=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,a),r.reply(200,null,a,K,()=>{this._status=Ie.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,K),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,oe.causes.CONNECTION_ERROR)})}).catch(K=>{this._status!==Ie.STATUS_TERMINATED&&we.warn(K)})}terminate(n={}){we.debug("terminate()");const r=n.cause||oe.causes.BYE,a=kt.cloneArray(n.extraHeaders),c=n.body;let e,_=n.status_code,g=n.reason_phrase;if(this._status===Ie.STATUS_TERMINATED)throw new di.InvalidStateError(this._status);switch(this._status){case Ie.STATUS_NULL:case Ie.STATUS_INVITE_SENT:case Ie.STATUS_1XX_RECEIVED:if(we.debug("canceling session"),_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);_&&(g=g||oe.REASON_PHRASE[_]||"",e=`SIP ;cause=${_} ;text="${g}"`),this._status===Ie.STATUS_NULL||this._status===Ie.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===Ie.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=Ie.STATUS_CANCELED,this._failed("local",null,oe.causes.CANCELED);break;case Ie.STATUS_WAITING_FOR_ANSWER:case Ie.STATUS_ANSWERED:if(we.debug("rejecting session"),_=_||480,_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);this._request.reply(_,g,a,c),this._failed("local",null,oe.causes.REJECTED);break;case Ie.STATUS_WAITING_FOR_ACK:case Ie.STATUS_CONFIRMED:if(we.debug("terminating session"),g=n.reason_phrase||oe.REASON_PHRASE[_]||"",_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);if(_&&a.push(`Reason: SIP ;cause=${_}; text="${g}"`),this._status===Ie.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ir.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:A})=>{A===oe.ACK&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ir.C.STATUS_TERMINATED&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate(),this.closeSession())}),this._ended("local",null,r),this._dialog=d,this._ua.newDialog(d)}else{const d={janus:"leave"},A=["Content-Type: application/json",this.getPTypeHeader(ir.LEAVE)];this.sendRequest(oe.BYE,{extraHeaders:A,body:JSON.stringify(d)}),this.closeSession(),this._ended("local",null,r)}}}configureMedia(n){this.isAudioOn=n.audio,this.isVideoOn=n.video}enableAudio(n){const r={janus:"message",body:{audio:n},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(ir.AUDIO_CHANGE)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{c.status_code===200&&(this._ua.emit("changeAudioState",n),this.sendStateMessage({audio:n}))}}})}startAudio(){Fr.toggleAudioMute(this.stream),this._toggleMuteAudio(!1),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Fr.toggleAudioMute(this.stream),this._toggleMuteAudio(!0),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(n){const r={janus:"message",body:{video:n},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(ir.VIDEO_CHANGE)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{c.status_code===200&&(this._ua.emit("changeVideoState",n),this.sendStateMessage({video:n}))}}})}startVideo(){Fr.toggleVideoMute(this.stream),this._toggleMuteVideo(!1),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Fr.toggleVideoMute(this.stream),this._toggleMuteVideo(!0),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(n){const r={janus:"message",body:{request:"state",data:n},handle_id:this.handle_id,session_id:this.session_id},a=["Content-Type: application/json",this.getPTypeHeader(ir.STATE)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r)})}sendInfo(n,r,a={}){if(we.debug("sendInfo()"),this._status!==Ie.STATUS_CONFIRMED&&this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_1XX_RECEIVED)throw new di.InvalidStateError(this._status);new pd(this).send(n,r,a)}mute(n={audio:!0,video:!1}){we.debug("mute()");let r=!1,a=!1;this._audioMuted===!1&&n.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&n.video&&(a=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||a===!0)&&this._onmute({audio:r,video:a})}unmute(n={audio:!0,video:!0}){we.debug("unmute()");let r=!1,a=!1;this._audioMuted===!0&&n.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&n.video&&(a=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||a===!0)&&this._onunmute({audio:r,video:a})}hold(n={},r){if(we.debug("hold()"),this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:n.extraHeaders}),!0}unhold(n={},r){if(we.debug("unhold()"),this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const a={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:a,extraHeaders:n.extraHeaders}),!0}renegotiate(n={},r){we.debug("renegotiate()");const a=n.rtcOfferConstraints||null;if(this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const c={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:oe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),n.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:c,rtcOfferConstraints:a,extraHeaders:n.extraHeaders}):this._sendReinvite({eventHandlers:c,rtcOfferConstraints:a,extraHeaders:n.extraHeaders}),!0}refer(n,r){we.debug("refer()");const a=n;if(this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED)return!1;if(n=this._ua.normalizeTarget(n),!n)throw new TypeError(`Invalid target: ${a}`);const c=new pC(this);c.sendRefer(n,r);const e=c.id;return this._referSubscribers[e]=c,c.on("requestFailed",()=>{delete this._referSubscribers[e]}),c.on("accepted",()=>{delete this._referSubscribers[e]}),c.on("failed",()=>{delete this._referSubscribers[e]}),c}sendRequest(n,r){return we.debug("sendRequest()"),this._dialog.sendRequest(n,r)}receiveNotify(n){we.debug("receiveRequest()")}receiveRequest(n){if(we.debug("receiveRequest()"),n.method===oe.CANCEL)(this._status===Ie.STATUS_WAITING_FOR_ANSWER||this._status===Ie.STATUS_ANSWERED)&&(this._status=Ie.STATUS_CANCELED,this._request.reply(487),this._failed("remote",n,oe.causes.CANCELED));else switch(n.method){case oe.ACK:if(this._status!==Ie.STATUS_WAITING_FOR_ACK)return;if(this._status=Ie.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:oe.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};we.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(c=>{this.terminate({cause:oe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})}else this._is_confirmed||this._confirmed("remote",n);break;case oe.BYE:this._status===Ie.STATUS_CONFIRMED||this._status===Ie.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,oe.causes.BYE)):this._status===Ie.STATUS_INVITE_RECEIVED||this._status===Ie.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,oe.causes.BYE)):n.reply(403,"Wrong Status");break;case oe.INVITE:this._status===Ie.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case oe.INFO:if(this._status===Ie.STATUS_1XX_RECEIVED||this._status===Ie.STATUS_WAITING_FOR_ANSWER||this._status===Ie.STATUS_ANSWERED||this._status===Ie.STATUS_WAITING_FOR_ACK||this._status===Ie.STATUS_CONFIRMED){const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new nC(this).init_incoming(n):r!==void 0?new pd(this).init_incoming(n):n.reply(415)}else n.reply(403,"Wrong Status");break;case oe.UPDATE:this._status===Ie.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case oe.REFER:this._status===Ie.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case oe.NOTIFY:this._status===Ie.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){we.warn("onTransportError()"),this._status!==Ie.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.CONNECTION_ERROR,cause:oe.causes.CONNECTION_ERROR})}onRequestTimeout(){we.warn("onRequestTimeout()"),this._status!==Ie.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:oe.causes.REQUEST_TIMEOUT,cause:oe.causes.REQUEST_TIMEOUT})}onDialogError(){we.warn("onDialogError()"),this._status!==Ie.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.DIALOG_ERROR,cause:oe.causes.DIALOG_ERROR})}newDTMF(n){we.debug("newDTMF()"),this.emit("newDTMF",n)}newInfo(n){we.debug("newInfo()"),this.emit("newInfo",n)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(we.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(we.debug("_isReadyToReOffer() | session not established yet"),!1):(we.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(we.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(we.debug("close() | closing local MediaStream"),kt.closeMediaStream(this._localMediaStream)),this._status!==Ie.STATUS_TERMINATED){if(this._status=Ie.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){we.warn("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(n,r){let a=el.T1;function c(){this._status===Ie.STATUS_WAITING_FOR_ACK&&(n.reply(200,null,[`Contact: ${this._contact}`],r),a<el.T2&&(a=a*2,a>el.T2&&(a=el.T2)),this._timers.invite2xxTimer=setTimeout(c.bind(this),a))}this._timers.invite2xxTimer=setTimeout(c.bind(this),a)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===Ie.STATUS_WAITING_FOR_ACK&&(we.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(oe.BYE),this._ended("remote",null,oe.causes.NO_ACK))},el.TIMER_H)}_createRTCConnection(n,r){this.stunServers,this._connection=new RTCPeerConnection(n,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:oe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:oe.causes.RTP_TIMEOUT})});let a;const c=e=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||e.candidate&&(this._candidates.push(e.candidate),clearTimeout(a),a=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=c,we.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(n,r){if(we.debug("createLocalDescription()"),n!=="offer"&&n!=="answer")throw new Error(`createLocalDescription() | invalid type "${n}"`);const a=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>n==="offer"?a.createOffer(r).catch(c=>(we.warn('emit "peerconnection:createofferfailed" [error:%o]',c),this.emit("peerconnection:createofferfailed",c),Promise.reject(c))):a.createAnswer(r).catch(c=>(we.warn('emit "peerconnection:createanswerfailed" [error:%o]',c),this.emit("peerconnection:createanswerfailed",c),Promise.reject(c)))).then(c=>(this.jsepOffer=c,a.setLocalDescription(c).catch(e=>(this._rtcReady=!0,we.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',e),this.emit("peerconnection:setlocaldescriptionfailed",e),Promise.reject(e))))).then(()=>{const c=r&&r.iceRestart;if(a.iceGatheringState==="complete"&&!c||a.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const e={originator:"local",type:n,sdp:a.localDescription.sdp};return we.debug('emit "sdp"'),this.emit("sdp",e),Promise.resolve(e.sdp)}return new Promise(e=>{let _=!1,g,d;this._iceReady=!1;const A=()=>{a.removeEventListener("icecandidate",g),a.removeEventListener("icegatheringstatechange",d),_=!0,this._rtcReady=!0,this._iceReady=!0;const S={originator:"local",type:n,sdp:a.localDescription.sdp};we.debug('emit "sdp"'),this.emit("sdp",S),e(S.sdp)};a.addEventListener("icecandidate",g=S=>{const R=S.candidate;R?this.emit("icecandidate",{candidate:R,ready:A}):_||A()}),a.addEventListener("icegatheringstatechange",d=()=>{a.iceGatheringState==="complete"&&!_&&A()})})})}_createDialog(n,r,a){const c=r==="UAS"?n.to_tag:n.from_tag,e=r==="UAS"?n.from_tag:n.to_tag,_=n.call_id+c+e;let g=this._earlyDialogs[_];if(a)return g?!0:(g=new Pu(this,n,r,Pu.C.STATUS_EARLY),g.error?(we.debug(g.error),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[_]=g,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,g)return g.update(n,r),this._dialog=g,delete this._earlyDialogs[_],!0;const d=new Pu(this,n,r);return d.error?(we.debug(d.error),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_receiveReinvite(n){we.debug("receiveReinvite()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,a={request:n,callback:void 0,reject:e.bind(this)};let c=!1;function e(g={}){c=!0;const d=g.status_code||403,A=g.reason_phrase||"",S=kt.cloneArray(g.extraHeaders);if(this._status!==Ie.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);n.reply(d,A,S)}if(this.emit("reinvite",a),c)return;if(this._late_sdp=!1,!n.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(g=>{_.call(this,g)}).catch(()=>{n.reply(500)});return}if(r!=="application/sdp"){we.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(g=>{this._status!==Ie.STATUS_TERMINATED&&_.call(this,g)}).catch(g=>{we.warn(g)});function _(g){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,d),this._late_sdp&&(g=this._mangleOffer(g)),n.reply(200,null,d,g,()=>{this._status=Ie.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(n,g),this._setACKTimer()}),typeof a.callback=="function"&&a.callback()}}_receiveUpdate(n){we.debug("receiveUpdate()");const r=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0,a={request:n,callback:void 0,reject:e.bind(this)};let c=!1;function e(g={}){c=!0;const d=g.status_code||403,A=g.reason_phrase||"",S=kt.cloneArray(g.extraHeaders);if(this._status!==Ie.STATUS_CONFIRMED)return!1;if(d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);n.reply(d,A,S)}if(this.emit("update",a),c)return;if(!n.body){_.call(this,null);return}if(r!=="application/sdp"){we.debug("invalid Content-Type"),n.reply(415);return}this._processInDialogSdpOffer(n).then(g=>{this._status!==Ie.STATUS_TERMINATED&&_.call(this,g)}).catch(g=>{we.warn(g)});function _(g){const d=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(n,d),n.reply(200,null,d,g),typeof a.callback=="function"&&a.callback()}}_processInDialogSdpOffer(n){we.debug("_processInDialogSdpOffer()");const r=n.parseSDP();let a=!1;for(const _ of r.media){if(Lu.indexOf(_.type)===-1)continue;const g=_.direction||r.direction||"sendrecv";if(g==="sendonly"||g==="inactive")a=!0;else{a=!1;break}}const c={originator:"remote",type:"offer",sdp:n.body};we.debug('emit "sdp"'),this.emit("sdp",c);const e=new RTCSessionDescription({type:"offer",sdp:c.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(e).catch(_=>{throw n.reply(488),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',_),this.emit("peerconnection:setremotedescriptionfailed",_),_})}).then(()=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&a===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&a===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(_=>{throw n.reply(500),we.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',_),_})}).catch(_=>{we.warn("_processInDialogSdpOffer() failed [error: %o]",_)}),this._connectionPromiseQueue}_receiveRefer(n){if(we.debug("receiveRefer()"),!n.refer_to){we.debug("no Refer-To header field present in REFER"),n.reply(400);return}if(n.refer_to.uri.scheme!==oe.SIP){we.debug("Refer-To header field points to a non-SIP URI scheme"),n.reply(416);return}n.reply(202);const r=new uC(this,n.cseq);we.debug('emit "refer"'),this.emit("refer",{request:n,accept:(e,_)=>{a.call(this,e,_)},reject:()=>{c.call(this)}});function a(e,_={}){if(e=typeof e=="function"?e:null,this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED)return!1;const g=new qu(this._ua);if(g.on("progress",({response:d})=>{r.notify(d.status_code,d.reason_phrase)}),g.on("accepted",({response:d})=>{r.notify(d.status_code,d.reason_phrase)}),g.on("_failed",({message:d,cause:A})=>{d?r.notify(d.status_code,d.reason_phrase):r.notify(487,A)}),n.refer_to.uri.hasHeader("replaces")){const d=decodeURIComponent(n.refer_to.uri.getHeader("replaces"));_.extraHeaders=kt.cloneArray(_.extraHeaders),_.extraHeaders.push(`Replaces: ${d}`)}g.connect(n.refer_to.uri.toAor(),_,e)}function c(){r.notify(603)}}_receiveNotify(n){switch(we.debug("receiveNotify()"),n.event||n.reply(400),n.event.event){case"refer":{let r,a;if(n.event.params&&n.event.params.id)r=n.event.params.id,a=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)a=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{n.reply(400,"Missing event id parameter");return}if(!a){n.reply(481,"Subscription does not exist");return}a.receiveNotify(n),n.reply(200);break}default:n.reply(489)}}_receiveReplaces(n){we.debug("receiveReplaces()");function r(c){if(this._status!==Ie.STATUS_WAITING_FOR_ACK&&this._status!==Ie.STATUS_CONFIRMED)return!1;const e=new qu(this._ua);e.on("confirmed",()=>{this.terminate()}),e.init_incoming(n,c)}function a(){we.debug("Replaced INVITE rejected by the user"),n.reply(486)}this.emit("replaces",{request:n,accept:c=>{r.call(this,c)},reject:()=>{a.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(n,r,a){this.ackSent=!1,this.publisherSubscribeSent=!1;const c=new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});Promise.resolve().then(()=>{if(a)return a;if(n.audio||n.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(e=>{throw this._status===Ie.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,oe.causes.USER_DENIED_MEDIA_ACCESS),we.warn('emit "getusermediafailed" [error:%o]',e),this.emit("getusermediafailed",e),e)})}).then(e=>{if(this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=e,e&&e.getTracks().forEach(_=>{this._connection.addTrack(_,e)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(_=>{throw this._failed("local",null,oe.causes.WEBRTC_ERROR),_})}).then(e=>{if(this._is_canceled||this._status===Ie.STATUS_TERMINATED)throw new Error("terminated");const _={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},g=JSON.stringify(_);this._request.body=g,this._status=Ie.STATUS_INVITE_SENT,we.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),c.send()}).catch(e=>{this._status!==Ie.STATUS_TERMINATED&&we.warn(e)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async changeMediaConstraints(n){this.mediaConstraints={...n},await this.processPlugins(),this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}async loadStream(){const n={};this.isAudioOn?this.mediaConstraints.audio?n.audio=this.mediaConstraints.audio:n.audio=!0:n.audio=!1,this.isVideoOn?this.mediaConstraints.video?n.video=this.mediaConstraints.video:n.video=!0:n.video=!1;let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch{try{n.video=!1,r=await navigator.mediaDevices.getUserMedia(n)}catch{n.audio=!1,n.video=!1,r=await navigator.mediaDevices.getUserMedia(n)}}return r}addTracks(n){this._connection.getSenders().forEach(r=>{this._connection.removeTrack(r)}),n.forEach(r=>{this._connection.addTrack(r)})}getRecordFileName(){return gA+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let n=0;n<this.iceCandidates.length;n++)await this._connection.addIceCandidate(this.iceCandidates[n]);this.iceCandidates=[]}async _sendConfigureMessage(n){const r=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handle_id,session_id:this.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...n},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...r]},c=["Content-Type: application/json",this.getPTypeHeader(ir.ICE)];this.sendRequest(oe.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{this.isConfigureSent=!0;const _=e.data.split(`\r
|
|
135
|
+
`),g=_[_.length-1],d=JSON.parse(g);await this._connection.setRemoteDescription(d.jsep),this._candidates=[]}}})}_sendMemberStartMessage(n,r){const a={janus:"message",body:{request:"start",room:this.room_id},handle_id:n.handleId,session_id:this.session_id,jsep:r},c=["Content-Type: application/json",this.getPTypeHeader(ir.CONFIGURE)];this.sendRequest(oe.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{e.status_code===200&&await n.rtcpPeer.setLocalDescription(r)}}})}_sendTrickleMessage(n){const r={trickles:[...n.map(c=>({janus:"trickle",candidate:c,handle_id:this.handle_id,session_id:this.session_id}))]},a=[this.getPTypeHeader(ir.TRICKLE)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{}}})}async _answerAttachedStream(n,r){let a=null;const c=async d=>{if(!n.rtcpPeer||n.loaded)return;{n.loaded=!0;const H={audio:!0,video:!0};await new Promise(W=>{setTimeout(W,100)}),a=await n.rtcpPeer.createAnswer(H),this._sendMemberStartMessage(n,a)}const A=d.streams[0].getAudioTracks(),S=d.streams[0].getVideoTracks(),R=[];A[0]&&R.push(A[0]),S[0]&&R.push(S[0]);const N=new MediaStream(R);n.stream=N,this._ua.emit("memberJoin",n.memberInfo)};let e,_=[];const g=d=>{n.rtcpPeer.signalingState!=="stable"&&n.rtcpPeer.signalingState!=="have-local-offer"||(_.push(d.candidate||null),clearTimeout(e),e=setTimeout(()=>{this._sendTrickleMessage(_)},500))};n.rtcpPeer=new RTCPeerConnection,n.rtcpPeer.ontrack=c,n.rtcpPeer.onicecandidate=g,n.rtcpPeer.sender=r.sender,await n.rtcpPeer.setRemoteDescription(r.jsep)}_sendJoinMemberRequest(n){const r={janus:"message",body:{request:"join",room:this.room_id,feed:n.info.id,ptype:"subscriber"},handle_id:n.handleId,session_id:this.session_id},a=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(oe.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{var e,_;if(c.status_code===200){const g=JSON.parse(c.body);(_=(e=g?.plugindata)==null?void 0:e.data)!=null&&_.id&&await this._answerAttachedStream(n,g)}}}})}_attachMember(n){const r={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},a=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async c=>{if(c.status_code===200){const e=JSON.parse(c.body).data.id;n.handleId=e,this._sendJoinMemberRequest(n)}}}})}_detachMember(n){const r={janus:"detach",handle_id:n.handleId,session_id:this.session_id},a=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(oe.INFO,{extraHeaders:a,body:JSON.stringify(r)}),Fr.stopStreamTracks(n.memberInfo.stream),this._ua.emit("memberHangup",n.memberInfo)}receivePublishers(n){var r,a,c,e,_,g,d,A;const S={...this.memberList};(a=(r=n?.plugindata)==null?void 0:r.data)==null||a.publishers.forEach(R=>{delete S[R.id],!this.memberList[R.id]&&!this.myFeedList.includes(R.id)&&R.clientID!==this.client_id&&(this.memberList[R.id]=new fA(R,this),this._attachMember(this.memberList[R.id]))}),((e=(c=n?.plugindata)==null?void 0:c.data)==null?void 0:e.videoroom)==="synced"&&Object.keys(S).forEach(R=>{S[R].hangup(),delete this.memberList[R]}),this.publishers=(g=(_=n?.plugindata)==null?void 0:_.data)==null?void 0:g.publishers,this.private_id=(A=(d=n?.plugindata)==null?void 0:d.data)==null?void 0:A.private_id}receiveUnpublished(n){const r=this.memberList[n];r&&(r.hangup(),this._detachMember(r),delete this.memberList[n])}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 n=this._ua.processStreamPlugins;let r=await this.loadStream();for(const a of n)r=await a.process(r);this.stream.getTracks().forEach(a=>{this.stream.removeTrack(a),a.stop()}),r.getTracks().forEach(a=>{this.stream.addTrack(a)})}async resyncPlugins(n){const r=this._ua.processStreamPlugins.filter(a=>a.type===n);for(const a of r)a.running&&a.terminate();if(n==="video"){let a=await this.loadStream();for(const c of r)c.running&&(a=await c.start(a));this.stream.getTracks().forEach(c=>{this.stream.removeTrack(c),c.stop()}),a.getTracks().forEach(c=>{this.stream.addTrack(c)}),this._overrideSenderTracks(this.stream,this._connection),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}else{const a=this._ua.newStreamPlugins.find(_=>_.type===n);let c=a.getStream().clone();for(const _ of r)_.running&&(c=await _.start(c));const e=a.getConnection();this._overrideSenderTracks(c,e),this._ua.emit("changePluginStream",{type:n,stream:c})}}stopProcessPlugins(n){const r=this._ua.processStreamPlugins.filter(a=>a.type===n);for(const a of r)a.running&&a.kill()}_receiveInviteResponse(n){if(we.debug("receiveInviteResponse()"),this._dialog&&n.status_code>=200&&n.status_code<=299&&!this.ackSent)if(this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.ackSent=!0,this.sendRequest(oe.ACK);return}else{const r=new Pu(this,n,"UAC");if(r.error!==void 0){we.debug(r.error);return}this.sendRequest(oe.ACK),this.sendRequest(oe.BYE);return}if(this.ackSent&&!this.publisherSubscribeSent){const r=JSON.parse(n.body);this.setupMediaStream().then(()=>{this.session_id=r.session_id,this.handle_id=r.data.id,this.client_id=gf();const a={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},c=[this.getPTypeHeader(ir.PUBLISHER)];this.sendRequest(oe.SUBSCRIBE,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{var _,g,d,A;if(e.status_code===200){if(this.subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((g=(_=S.plugindata)==null?void 0:_.data)==null?void 0:g.videoroom)==="joined"&&this.myFeedList.push(S.plugindata.data.id),(A=(d=S.plugindata)==null?void 0:d.data)!=null&&A.publishers&&this.receivePublishers(S)}catch(S){console.error(S)}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){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==Ie.STATUS_INVITE_SENT&&this._status!==Ie.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(n.status_code):this._status=Ie.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){we.debug("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=Ie.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};we.debug('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",n)).catch(c=>{we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(this._status=Ie.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,oe.causes.MISSING_SDP),this._failed("remote",n,oe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;break}default:{const r=kt.sipErrorCause(n.status_code);this._failed("remote",n,r)}}}_sendReinvite(n={}){we.debug("sendReinvite()");const r=kt.cloneArray(n.extraHeaders),a=kt.cloneObject(n.eventHandlers),c=n.rtcOfferConstraints||this._rtcOfferConstraints||null;let e=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",c)).then(d=>{d=this._mangleOffer(d);const A={originator:"local",type:"offer",sdp:d};we.debug('emit "sdp"'),this.emit("sdp",A),this.sendRequest(oe.INVITE,{extraHeaders:r,body:d,eventHandlers:{onSuccessResponse:S=>{_.call(this,S),e=!0},onErrorResponse:S=>{g.call(this,S)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{g()});function _(d){if(this._status===Ie.STATUS_TERMINATED||(this.sendRequest(oe.ACK),e))return;if(this._handleSessionTimersInIncomingResponse(d),d.body){if(!d.hasHeader("Content-Type")||d.getHeader("Content-Type").toLowerCase()!=="application/sdp"){g.call(this);return}}else{g.call(this);return}const A={originator:"remote",type:"answer",sdp:d.body};we.debug('emit "sdp"'),this.emit("sdp",A);const S=new RTCSessionDescription({type:"answer",sdp:A.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(S)).then(()=>{a.succeeded&&a.succeeded(d)}).catch(R=>{g.call(this),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),this.emit("peerconnection:setremotedescriptionfailed",R)})}function g(d){a.failed&&a.failed(d)}}_sendUpdate(n={}){we.debug("sendUpdate()");const r=kt.cloneArray(n.extraHeaders),a=kt.cloneObject(n.eventHandlers),c=n.rtcOfferConstraints||this._rtcOfferConstraints||null,e=n.sdpOffer||!1;let _=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),e?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",c)).then(A=>{A=this._mangleOffer(A);const S={originator:"local",type:"offer",sdp:A};we.debug('emit "sdp"'),this.emit("sdp",S),this.sendRequest(oe.UPDATE,{extraHeaders:r,body:A,eventHandlers:{onSuccessResponse:R=>{g.call(this,R),_=!0},onErrorResponse:R=>{d.call(this,R)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{d.call(this)})):this.sendRequest(oe.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:A=>{g.call(this,A)},onErrorResponse:A=>{d.call(this,A)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function g(A){if(this._status!==Ie.STATUS_TERMINATED&&!_)if(this._handleSessionTimersInIncomingResponse(A),e){if(A.body){if(!A.hasHeader("Content-Type")||A.getHeader("Content-Type").toLowerCase()!=="application/sdp"){d.call(this);return}}else{d.call(this);return}const S={originator:"remote",type:"answer",sdp:A.body};we.debug('emit "sdp"'),this.emit("sdp",S);const R=new RTCSessionDescription({type:"answer",sdp:S.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(R)).then(()=>{a.succeeded&&a.succeeded(A)}).catch(N=>{d.call(this),we.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',N),this.emit("peerconnection:setremotedescriptionfailed",N)})}else a.succeeded&&a.succeeded(A)}function d(A){a.failed&&a.failed(A)}}_acceptAndTerminate(n,r,a){we.debug("acceptAndTerminate()");const c=[];r&&(a=a||oe.REASON_PHRASE[r]||"",c.push(`Reason: SIP ;cause=${r}; text="${a}"`)),(this._dialog||this._createDialog(n,"UAC"))&&(this.sendRequest(oe.ACK),this.sendRequest(oe.BYE,{extraHeaders:c})),this._status=Ie.STATUS_TERMINATED}_mangleOffer(n){if(!this._localHold&&!this._remoteHold)return n;if(n=nr.parse(n),this._localHold&&!this._remoteHold){we.debug("mangleOffer() | me on hold, mangling offer");for(const r of n.media)Lu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){we.debug("mangleOffer() | both on hold, mangling offer");for(const r of n.media)Lu.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){we.debug("mangleOffer() | remote on hold, mangling offer");for(const r of n.media)Lu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return nr.write(n)}_setLocalMediaStatus(){let n=!0,r=!0;(this._localHold||this._remoteHold)&&(n=!1,r=!1),this._audioMuted&&(n=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!n),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(n,r){if(!this._sessionTimers.enabled)return;let a;n.session_expires&&n.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,a=n.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,a="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${a}`),this._sessionTimers.refresher=a==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const n=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==Ie.STATUS_TERMINATED&&this._isReadyToReOffer()&&(we.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===oe.UPDATE?this._sendUpdate():this._sendReinvite())},n*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==Ie.STATUS_TERMINATED&&(we.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:oe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},n*1100)}_toggleMuteAudio(n){const r=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="audio");for(const a of r)a.track.enabled=!n}_toggleMuteVideo(n){const r=this._connection.getSenders().filter(a=>a.track&&a.track.kind==="video");for(const a of r)a.track.enabled=!n}_newJanusSession(n,r){we.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:n,session:this,request:r})}_connecting(n){we.debug("session connecting"),we.debug('emit "connecting"'),this.emit("connecting",{request:n})}_progress(n,r){we.debug("session progress"),we.debug('emit "progress"'),this.emit("progress",{originator:n,response:r||null})}_accepted(n,r){we.debug("session accepted"),this._start_time=new Date,we.debug('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){we.debug("session confirmed"),this._is_confirmed=!0,we.debug('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,a){we.debug("session ended"),this._end_time=new Date,this._close(),we.debug('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:a})}_failed(n,r,a){we.debug("session failed"),we.debug('emit "_failed"'),this.emit("_failed",{originator:n,message:r||null,cause:a}),this._close(),we.debug('emit "failed"'),this.emit("failed",{originator:n,message:r||null,cause:a})}_onhold(n){we.debug("session onhold"),this._setLocalMediaStatus(),we.debug('emit "hold"'),this.emit("hold",{originator:n})}_onunhold(n){we.debug("session onunhold"),this._setLocalMediaStatus(),we.debug('emit "unhold"'),this.emit("unhold",{originator:n})}_onmute({audio:n,video:r}){we.debug("session onmute"),this._setLocalMediaStatus(),we.debug('emit "muted"'),this.emit("muted",{audio:n,video:r})}_onunmute({audio:n,video:r}){we.debug("session onunmute"),this._setLocalMediaStatus(),we.debug('emit "unmuted"'),this.emit("unmuted",{audio:n,video:r})}}class ro{constructor(n){if(this.headers={},n.length>0){let r=!1;const a=n.split(`\r
|
|
136
136
|
`),c=a.shift().split(/\s/);this.protocol=c[0],this.ident=c[1],this.code=c.length>3?parseInt(c[2]):0,this.method=c.length>3?c[3]:c[2],this.body="";for(const e of a){if(e==`-------${this.ident}$`)break;if(e===""){r=!0;continue}if(e&&r)this.body+=`${e}\r
|
|
137
|
-
`;else{const
|
|
137
|
+
`;else{const _=e.split(": ");this.addHeader(_[0],_[1].trim())}}}else this.ident=kt.createRandomToken(12),this.protocol="MSRP"}addHeader(n,r){this.headers[n]=r}getHeader(n){return this.headers[n]}toString(){let n=`${this.protocol} ${this.ident} ${this.code} ${this.method}`.replaceAll(/null\s|undefined\s/ig,"")+`\r
|
|
138
138
|
`;for(const r in this.headers)n+=`${r}: ${this.headers[r]}\r
|
|
139
139
|
`;return this.body&&(n+=`\r
|
|
140
140
|
${this.body}\r
|
|
@@ -153,14 +153,14 @@ t=0 0
|
|
|
153
153
|
m=message 2856 TCP/TLS/MSRP *
|
|
154
154
|
a=accept-types:text/plain text/html
|
|
155
155
|
a=path:${n.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 sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:c=>{this.onTransportError(),console.log(c)},onAuthenticated:c=>{this._request=c},onReceiveResponse:c=>{this._receiveInviteResponse(c),c.status_code===200&&(c.parseSDP(!0),this._status=dt.STATUS_CONFIRMED,this.target_addr=c.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=dt.STATUS_INVITE_SENT}terminate(n={}){const r=n.cause||oe.causes.BYE,a=kt.cloneArray(n.extraHeaders),c=n.body;let e,f=n.status_code,g=n.reason_phrase;if(this._status===dt.STATUS_TERMINATED)throw new di.InvalidStateError(this._status);switch(this.status="terminated",this._status){case dt.STATUS_NULL:case dt.STATUS_INVITE_SENT:case dt.STATUS_1XX_RECEIVED:if(f&&(f<200||f>=700))throw new TypeError(`Invalid status_code: ${f}`);f&&(g=g||oe.REASON_PHRASE[f]||"",e=`SIP ;cause=${f} ;text="${g}"`),this._status===dt.STATUS_NULL||this._status===dt.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===dt.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=dt.STATUS_CANCELED,this._failed("local",null,oe.causes.CANCELED);break;case dt.STATUS_WAITING_FOR_ANSWER:case dt.STATUS_ANSWERED:if(f=f||480,f<300||f>=700)throw new TypeError(`Invalid status_code: ${f}`);this._request.reply(f,g,a,c),this._failed("local",null,oe.causes.REJECTED);break;case dt.STATUS_WAITING_FOR_ACK:case dt.STATUS_CONFIRMED:if(g=n.reason_phrase||oe.REASON_PHRASE[f]||"",f&&(f<200||f>=700))throw new TypeError(`Invalid status_code: ${f}`);if(f&&a.push(`Reason: SIP ;cause=${f}; text="${g}"`),this._status===dt.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ir.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:A})=>{A===oe.ACK&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ir.C.STATUS_TERMINATED&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate())}),this._ended("local",null,r),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),this._ended("local",null,r)}}sendRequest(n,r){return this._dialog.sendRequest(n,r)}authenticate(n){this.status="auth";let r=new ro("");r.method="AUTH",r.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),r.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),n&&r.addHeader("Authorization",n.toString());let a=r.toString(),c=[];for(var e=0;e<a.length;e++)c.push(a.charCodeAt(e).toString(16));this._connection.send(r.toString())}onmessage(n){const r=new ro(n.data);if(this.status==="auth"&&r.code===401){const a=this.parseAuth(r.getHeader("WWW-Authenticate")),c=new $E(this.credentials);c.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},a,kt.createRandomToken(12)),this.authenticate(c)}this.status==="auth"&&r.code===200&&this._direction==="outgoing"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.inviteParty(r)):this.status==="auth"&&r.code===200&&this._direction==="incoming"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.acceptParty(r),this.emit("confirmed")):r.method==="SEND"&&(this._sendOk(r),this._sendReport(r),r.direction="incoming",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)),r.code===480&&this._close()}onclose(){console.log("close")}onopen(){const n=new RTCPeerConnection({iceServers:[]});n.createDataChannel(""),n.createOffer().then(n.setLocalDescription.bind(n)),n.onicecandidate=r=>{if(!r||!r.candidate||!r.candidate.candidate)return;const a=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,c=r.candidate.candidate.match(a);this.my_ip=c&&c[1],n.onicecandidate=()=>{},this.authenticate(null)}}onerror(n){console.log(n)}_receiveInviteResponse(n){if(console.log("resp0000000000000",n),this._dialog&&n.status_code>=200&&n.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.sendRequest(oe.ACK);return}else{const r=new Ru(this,n,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(oe.ACK),this.sendRequest(oe.BYE);return}if(this._is_canceled){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==dt.STATUS_INVITE_SENT&&this._status!==dt.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(n.status_code):this._status=dt.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){console.log("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=dt.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",n)).catch(c=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("maybe here???"),this._status=dt.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,oe.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",n,oe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r),new RTCSessionDescription({type:"answer",sdp:r.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(n,500,a.toString()),console.log("failed 4"),this._failed("local",n,oe.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(oe.ACK),this._confirmed("local",null)});break}default:{const r=kt.sipErrorCause(n.status_code);console.log("failed 5"),this._failed("remote",n,r)}}}sendMSRP(n){const r=new ro("");let a="";this.my_addr[1]&&(a=this.my_addr[1]),this.target_addr[1]&&(a+=" "+this.target_addr[1]),this.target_addr[0]&&(a+=" "+this.target_addr[0]),r.method="SEND",r.addHeader("To-Path",a),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",kt.createRandomToken(10)),r.addHeader("Byte-Range","1-25/25"),r.addHeader("Content-Type","text/plain"),r.addHeader("Success-Report","yes"),r.addHeader("Failure-Report","yes"),r.body=n;let c=r.toString();console.log(c);let e=[];for(var f=0;f<c.length;f++)e.push(c.charCodeAt(f).toString(16));console.log(e),this._connection.send(r.toString()),r.direction="outgoing",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(n){let r=n.ident,a=n.getHeader("Message-ID"),c=new ro("");c.method="200 OK",c.addHeader("To-Path",`${this.my_addr[1]}`),c.addHeader("From-Path",`${this.my_addr[0]}`),c.addHeader("Message-ID",a),c.ident=r;let e=c.toString();console.log(e);let f=[];for(var g=0;g<e.length;g++)f.push(e.charCodeAt(g).toString(16));console.log(f),this._connection.send(c.toString())}_sendReport(n){let r=n.ident,a=n.getHeader("Message-ID"),c=new ro("");c.method="REPORT",c.addHeader("To-Path",`${n.getHeader("From-Path")}`),c.addHeader("From-Path",`${this.my_addr[0]}`),c.addHeader("Message-ID",a),c.addHeader("Byte-Range","1-25/25"),c.addHeader("Status","000 200 OK"),c.ident=r;let e=c.toString();console.log(e);let f=[];for(var g=0;g<e.length;g++)f.push(e.charCodeAt(g).toString(16));console.log(f),this._connection.send(c.toString())}parseAuth(n){const r={},a=n.replace("Digest","").split(",");for(const c of a){const e=c.trim().split("=");r[e[0]]=e[1].match('^"(.+)"$')[1]}return r}init_incoming(n,r){let a;const c=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&c!=="application/sdp"){n.reply(415);return}if(this._status=dt.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(a=n.getHeader("expires")*1e3),n.to_tag=kt.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=dt.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),console.log("failed 6"),this._failed("local",null,oe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===dt.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),console.log("failed 7"),this._failed("system",null,oe.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),n.parseSDP(!0),this.target_addr=n.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",n),this._status!==dt.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(n,r,a){this.emit("_failed",{originator:n,message:r||null,cause:a}),this._close(),this.emit("failed",{originator:n,message:r||null,cause:a})}_close(){if(console.log("CLOSE SESSION"),this._status!==dt.STATUS_TERMINATED){if(this._status=dt.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){console.log("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyMSRPSession(this)}}_createDialog(n,r,a){const c=r==="UAS"?n.to_tag:n.from_tag,e=r==="UAS"?n.from_tag:n.to_tag,f=n.call_id+c+e;let g=this._earlyDialogs[f];if(a)return g?!0:(g=new Ru(this,n,r,Ru.C.STATUS_EARLY),g.error?(console.log("failed 8"),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[f]=g,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,g)return g.update(n,r),this._dialog=g,delete this._earlyDialogs[f],!0;const d=new Ru(this,n,r);return d.error?(console.log("failed 9"),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_newMSRPSession(n,r){this._ua.newMSRPSession(this,{originator:n,session:this,request:r})}_progress(n,r){this.emit("progress",{originator:n,response:r||null})}isEnded(){switch(this._status){case dt.STATUS_CANCELED:case dt.STATUS_TERMINATED:return!0;default:return!1}}_accepted(n,r){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,a){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:a})}_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 n=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(r){console.error("Failed to send keep-alive:",r)}this._sessionTimers.running=!1,this._runKeepAliveTimer()},n*1e3*.5)}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runKeepAliveTimer()}receiveRequest(n){if(console.log("receiveRequest()"),n.method===oe.CANCEL)(this._status===dt.STATUS_WAITING_FOR_ANSWER||this._status===dt.STATUS_ANSWERED)&&(this._status=dt.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",n,oe.causes.CANCELED));else switch(n.method){case oe.ACK:if(this._status!==dt.STATUS_WAITING_FOR_ACK)return;if(this._status=dt.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:oe.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(c=>{this.terminate({cause:oe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})}else this._is_confirmed||this._confirmed("remote",n);break;case oe.BYE:this._status===dt.STATUS_CONFIRMED||this._status===dt.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,oe.causes.BYE)):this._status===dt.STATUS_INVITE_RECEIVED||this._status===dt.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,oe.causes.BYE)):n.reply(403,"Wrong Status");break;case oe.INVITE:this._status===dt.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case oe.INFO:this._status===dt.STATUS_1XX_RECEIVED||this._status===dt.STATUS_WAITING_FOR_ANSWER||this._status===dt.STATUS_ANSWERED||this._status===dt.STATUS_WAITING_FOR_ACK||this._status===dt.STATUS_CONFIRMED?(n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new pd(this).init_incoming(n):n.reply(415):n.reply(403,"Wrong Status");break;case oe.UPDATE:this._status===dt.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case oe.REFER:this._status===dt.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case oe.NOTIFY:this._status===dt.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.CONNECTION_ERROR,cause:oe.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:oe.causes.REQUEST_TIMEOUT,cause:oe.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.DIALOG_ERROR,cause:oe.causes.DIALOG_ERROR})}}var yA=Hr();const kd=Qt(yA),Hu=new wu("Parser"),vA=(o,n)=>{let r,a,c=o.indexOf(`\r
|
|
157
|
-
`);if(c===-1){Hu.warn("parseMessage() | no CRLF found, not a SIP message");return}const e=o.substring(0,c);let
|
|
158
|
-
`,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function bA(o,n,r,a){let c;const e=n.indexOf(":",r),f=n.substring(r,e).trim(),g=n.substring(e+1,a).trim();switch(f.toLowerCase()){case"via":case"v":o.addHeader("via",g),o.getHeaders("via").length===1?(c=o.parseHeader("Via"),c&&(o.via=c,o.via_branch=c.branch)):c=0;break;case"from":case"f":o.setHeader("from",g),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",g),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=kd.parse(g,"Record_Route"),c===-1)c=void 0;else for(const d of c)o.addHeader("record-route",g.substring(d.possition,d.offset)),o.headers["Record-Route"][o.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":o.setHeader("call-id",g),c=o.parseHeader("call-id"),c&&(o.call_id=g);break;case"contact":case"m":if(c=kd.parse(g,"Contact"),c===-1)c=void 0;else for(const d of c)o.addHeader("contact",g.substring(d.possition,d.offset)),o.headers.Contact[o.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":o.setHeader("content-length",g),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",g),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",g),c=o.parseHeader("cseq"),c&&(o.cseq=c.value),o instanceof Za.IncomingResponse&&(o.method=c.method);break;case"max-forwards":o.setHeader("max-forwards",g),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",g),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",g),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",g),c=o.parseHeader("session-expires"),c&&(o.session_expires=c.expires,o.session_expires_refresher=c.refresher);break;case"refer-to":case"r":o.setHeader("refer-to",g),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",g),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",g),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(f,g),c=0}return c===void 0?{error:`error parsing header "${f}"`}:!0}const wA={parseMessage:vA},_l=new wu("Registrator"),zu=10;class SA{constructor(n,r){this._reg_id=1,this._ua=n,this._transport=r,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=qs.createRandomToken(22),this._cseq=0,this._to_uri=n.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const c=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=c}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(n){Array.isArray(n)||(n=[]),this._extraHeaders=n.slice()}setExtraContactParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){_l.debug("Register request in progress...");return}const n=this._extraHeaders.slice();n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),n.push(`Expires: ${this._expires}`);const r=new On.OutgoingRequest(oe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n),a=new sl(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,oe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,oe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{if(c.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):{if(this._registering=!1,!c.hasHeader("Contact")){_l.debug("no Contact header in response to REGISTER, response ignored");break}const e=c.headers.Contact.reduce((A,S)=>A.concat(S.parsed),[]);let f=e.find(A=>this._sipInstance===A.getParam("+sip.instance")&&this._reg_id===parseInt(A.getParam("reg-id")));if(f||(f=e.find(A=>A.uri.user===this._ua.contact.uri.user)),!f){_l.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let g=f.getParam("expires");!g&&c.hasHeader("expires")&&(g=c.getHeader("expires")),g||(g=this._expires),g=Number(g),g<zu&&(g=zu);const d=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):g*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),f.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=f.getParam("temp-gruu").replace(/"/g,"")),f.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=f.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:c}));break}case/^423$/.test(c.status_code):{c.hasHeader("min-expires")?(this._expires=Number(c.getHeader("min-expires")),this._expires<zu&&(this._expires=zu),this.register()):(_l.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(c,oe.causes.SIP_FAILURE_CODE));break}default:{const e=qs.sipErrorCause(c.status_code);this._registrationFailure(c,e)}}}});this._registering=!0,a.send()}unregister(n={}){if(!this._registered){_l.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();n.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),r.push("Expires: 0");const a=new On.OutgoingRequest(oe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new sl(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,oe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,oe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{switch(!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):this._unregistered(c);break;default:{const e=qs.sipErrorCause(c.status_code);this._unregistered(c,e)}}}}).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(n,r){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:r}))}_unregistered(n,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:r||null})}}const un=console,fi={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},EA=cA;class CA extends EA{constructor(n){super(n),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 SA(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(n,r){return super.call(n,r)}joinVideoCall(n,r,a){un.debug("call()");const c=new qu(this);return c.configureMedia({audio:!0,video:!0}),c.connect(n,r,a),c}startScreenShare(){un.debug("startScreenShare()");for(const n in this._janus_sessions)this._janus_sessions[n].connectScreenShare()}changeMediaConstraints(n){for(const r in this._janus_sessions)this._janus_sessions[r].changeMediaConstraints(n)}startBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].connectBlur()}stopBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].stopBlur()}_loadConfig(n){try{pl.load(this._configuration,n)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=qs.newUUID());let r;typeof window<"u"&&typeof window.document<"u"?r=window?.navigator.userAgent:typeof self<"u"&&self.navigator&&(r=self.navigator.userAgent),r+=" "+bt.USER_AGENT,this._configuration.user_agent=n.overrideUserAgent&&typeof n.overrideUserAgent=="function"?n.overrideUserAgent(r):r,n.onTransportCallback&&typeof n.onTransportCallback=="function"&&(this.onTransportCallback=n.onTransportCallback),this._configuration.jssip_id=qs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new UC(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=AA.bind(this),this._transport.onconnect=IA.bind(this),this._transport.ondisconnect=RA.bind(this),this._transport.ondata=$A.bind(this)}catch(e){throw un.warn(e),new di.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 e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ba("sip",qs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){const f=e.anonymous||null,g=e.outbound||null;let d="<";return f?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),g&&(f?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",d}};const c=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(c.indexOf(e)!==-1?Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}));un.debug("configuration parameters after validation:");for(const e in this._configuration)if(Object.prototype.hasOwnProperty.call(pl.settings,e))switch(e){case"uri":case"registrar_server":un.debug(`- ${e}: ${this._configuration[e]}`);break;case"password":case"ha1":case"authorization_jwt":un.debug(`- ${e}: NOT SHOWN`);break;default:un.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}newMSRPSession(n,r){n.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.newStreamPlugins.forEach(a=>{a.setSession(n)}),this.processStreamPlugins.forEach(a=>{a.setSession(n)}),this.emit("newJanusSession",r)}kill(){}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(n){var r,a,c,e;const f=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){un.debug("Request-URI does not point to us"),n.method!==bt.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===bt.SIPS){n.reply_sl(416);return}if(Ir.checkTransaction(this,n))return;if(f===bt.INVITE?new Ir.InviteServerTransaction(this,this._transport,n):f!==bt.ACK&&f!==bt.CANCEL&&new Ir.NonInviteServerTransaction(this,this._transport,n),f===bt.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const A=Date.now(),S=this.lastOptionsTimestamp>A-35e3,R=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>A;S&&R&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){n.reply(200);return}new b_.Options(this).init_incoming(n)}else if(f===bt.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new b_.Message(this).init_incoming(n)}else if(f===bt.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let g,d;if(n.to_tag)if(g=this._findDialog(n.call_id,n.from_tag,n.to_tag),g)g.receiveRequest(n);else if(f===bt.NOTIFY)if(d=this._findSession(n),d)d.receiveRequest(n);else{if(n.body)try{const A=JSON.parse(n.body)||{};(a=(r=A.plugindata)==null?void 0:r.data)!=null&&a.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(A),(e=(c=A.plugindata)==null?void 0:c.data)!=null&&e.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(A.plugindata.data.unpublished)}catch(A){console.error(A)}n.reply(200)}else f!==bt.ACK&&n.reply(481);else switch(f){case bt.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const A=n.replaces;g=this._findDialog(A.call_id,A.from_tag,A.to_tag),g?(d=g.owner,d.isEnded()?n.reply(603):d.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(d=new Od(this),d.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(d=new TC(this),d.init_incoming(n));else un.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case bt.BYE:n.reply(481);break;case bt.CANCEL:d=this._findSession(n),d?d.receiveRequest(n):un.debug("received CANCEL request for a non existent session");break;case bt.ACK:break;case bt.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){un.debug("startMSRP()",r);const a=new Od(this);return a.connect(n),a}startJanus(n,r){un.debug("startJanus()",r);const a=new Od(this);return a.connect(n),a}terminateMSRPSessions(n){un.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){un.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}enableJanusAudio(n){un.debug("enableJanusAudio()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startAudio():this._janus_sessions[r].stopAudio())}enableJanusVideo(n){un.debug("enableJanusVideo()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startVideo():this._janus_sessions[r].stopVideo())}terminateAllSessions(){for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){un.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch(r){console.error(r)}}}stop(n=!0){if(un.debug("stop()"),this._dynConfiguration={},this._status===fi.STATUS_USER_CLOSED){un.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;n&&this.terminateAllSessions();for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){un.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){un.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(c){console.error(c)}this._status=fi.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&&r===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function AA(o){this.emit("connecting",o)}function IA(o){this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function RA(o){const n=["nict","ict","nist","ist"];for(const r of n)for(const a in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],a)&&this._transactions[r][a].onTransportError();this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_NOT_READY,this._error=fi.NETWORK_ERROR)}function $A(o){const n=o.transport;let r=o.message;const a=r;if(r=wA.parseMessage(r,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(r,a),!!r&&!(this._status===fi.STATUS_USER_CLOSED&&r instanceof Za.IncomingRequest)&&JC(r,this,n)){if(r instanceof Za.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Za.IncomingResponse){let c;switch(r.method){case bt.INVITE:c=this._transactions.ict[r.via_branch],c&&c.receiveResponse(r);break;case bt.ACK:break;default:c=this._transactions.nict[r.via_branch],c&&c.receiveResponse(r);break}}}}const xA=["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"],OA=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function yf(o){const n={};return xA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n.localHold=o._localHold,n}function vf(o){const n={};return OA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n}async function Dd(o,n,r){const a=o.createMediaStreamSource(n),c=o.createMediaStreamDestination(),e=o.createGain();return a.connect(e),e.connect(c),e.gain.value=r,c.stream}function kA(o,n,r,a){if(Tf())return;const c=document.createElement("audio");c.id=n._id,c.className="audioTag",c.srcObject=o,c.setSinkId(r),c.volume=a,c.play(),n.audioTag=c}function DA(o){if(o&&typeof o.log=="function"&&typeof o.warn=="function"&&typeof o.error=="function")return!0}function Tf(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const NA=mn,MA=Hr(),Jn=new NA("WebSocketInterface");var UA=class{constructor(o){Jn.debug('new() [url:"%s"]',o),this._url=o,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=MA.parse(o,"absoluteURI");if(n===-1)throw Jn.warn(`invalid WebSocket URI: ${o}`),new TypeError(`Invalid argument: ${o}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Jn.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${o}`);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(o){this._via_transport=o.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Jn.debug("connect()"),this.isConnected()){Jn.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Jn.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Jn.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(o){this._onError(o)}}disconnect(){Jn.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(o){return Jn.debug("send()"),this.isConnected()?(this._ws.send(o),!0):(Jn.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(){Jn.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:o,code:n,reason:r}){Jn.debug(`WebSocket ${this._url} closed`),o===!1&&Jn.debug("WebSocket abrupt disconnection"),this.ondisconnect(!o,n,r)}_onMessage({data:o}){Jn.debug("received WebSocket message"),this.ondata(o)}_onError(o){Jn.warn(`WebSocket ${this._url} error: `,o)}};const Nd=Pl,PA=bt,LA=Ls,qA=$n(),HA=ff,zA=Ms(),FA=ed(),BA=Hr(),VA=UA;Wa("JsSIP")("version %s",Nd.version);var jA={C:PA,Exceptions:LA,Utils:qA,UA:HA,URI:zA,NameAddrHeader:FA,WebSocketInterface:VA,Grammar:BA,debug:Wa,get name(){return Nd.title},get version(){return Nd.version}};const GA=Qt(jA);function Md(o){return o<10?`0${o}`:`${o}`}function WA(o){let n=o.hours||0,r=o.minutes||0,a=o.seconds||0;a++,a===60&&(a=0,r++,r===60&&(r=0,n++));const c=`${Md(n)}:${Md(r)}:${Md(a)}`;return{seconds:a,minutes:r,hours:n,formatted:c}}function KA(o){let n=0;for(let r=0;r<o.length;r++)n+=o[r]*o[r];return Math.sqrt(n/o.length)}async function YA(o,n,r=150){const a=n.createMediaStreamSource(o),c=n.createDelay();c.delayTime.value=r/1e3;const e=n.createGain();e.gain.value=0;const f=n.createMediaStreamDestination();return a.connect(c).connect(e).connect(f),{stream:f.stream,setSpeaking:g=>{e.gain.value=g?1:0}}}var Mn={};Mn.forEach=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)if(c in o){const e=Promise.resolve(o[c]).then(f=>n.call(r||globalThis,f,c,o));a.push(e)}await Promise.all(a)},Mn.forEachSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)a in o&&await n.call(r||globalThis,await o[a],a,o)},Mn.map=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=Promise.resolve(o[c]).then(e=>n.call(r||globalThis,e,c,o)));return Promise.all(a)},Mn.mapSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=await n.call(r||globalThis,await o[c],c,o));return a},Mn.find=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a();let e=1;for(let f=0;f<o.length;f++){const g=d=>{d?a(o[f]):e===o.length&&a(),e++};Promise.resolve(o[f]).then(d=>n.call(r||globalThis,d,f,o)).then(g).catch(c)}}),Mn.findSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return o[a]},Mn.findIndex=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(-1);let e=1;for(let f=0;f<o.length;f++){const g=d=>{d?a(f):e===o.length&&a(-1),e++};Promise.resolve(o[f]).then(d=>n.call(r||globalThis,d,f,o)).then(g).catch(c)}}),Mn.findIndexSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return a},Mn.some=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!1);let e=1;for(let f=0;f<o.length;f++){if(!(f in o)){e++;continue}const g=d=>{d?a(!0):e===o.length&&a(!1),e++};Promise.resolve(o[f]).then(d=>n.call(r||globalThis,d,f,o)).then(g).catch(c)}}),Mn.someSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&await n.call(r||globalThis,await o[a],a,o))return!0;return!1},Mn.every=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!0);let e=1;for(let f=0;f<o.length;f++){if(!(f in o)){e++;continue}const g=d=>{d?e===o.length&&a(!0):a(!1),e++};Promise.resolve(o[f]).then(d=>n.call(r||globalThis,d,f,o)).then(g).catch(c)}}),Mn.everySeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&!await n.call(r||globalThis,await o[a],a,o))return!1;return!0},Mn.filter=(o,n,r)=>new Promise(async(a,c)=>{const e=[];for(let g=0;g<o.length;g++)g in o&&(e[g]=Promise.resolve(o[g]).then(d=>n.call(r||globalThis,d,g,o)).catch(c));const f=[];for(let g=0;g<e.length;g++)await e[g]&&f.push(await o[g]);a(f)}),Mn.filterSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&await n.call(r||globalThis,await o[c],c,o)&&a.push(await o[c]);return a},Mn.reduce=async(o,n,r)=>{if(o.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let a,c;for(r!==void 0?(c=r,a=0):(c=o[0],a=1),a;a<o.length;a++)a in o&&(c=await n(await c,await o[a],a,o));return c};var bf={};(function(o){const n=Mn;Object.keys(n).forEach(r=>{const a=r.charAt(0).toUpperCase()+r.slice(1);o[`async${a}`]=async function(...c){return n[r](this,...c)}})})(bf);var XA=Object.assign(Mn,{instanceMethods:bf});const Br={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},JA={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 QA={exports:{}};(function(o){var n=function(r){var a=Object.prototype,c=a.hasOwnProperty,e=Object.defineProperty||function(Ae,fe,se){Ae[fe]=se.value},f,g=typeof Symbol=="function"?Symbol:{},d=g.iterator||"@@iterator",A=g.asyncIterator||"@@asyncIterator",S=g.toStringTag||"@@toStringTag";function R(Ae,fe,se){return Object.defineProperty(Ae,fe,{value:se,enumerable:!0,configurable:!0,writable:!0}),Ae[fe]}try{R({},"")}catch{R=function(Ae,fe,se){return Ae[fe]=se}}function N(Ae,fe,se,st){var We=fe&&fe.prototype instanceof De?fe:De,ht=Object.create(We.prototype),It=new Se(st||[]);return e(ht,"_invoke",{value:ue(Ae,se,It)}),ht}r.wrap=N;function H(Ae,fe,se){try{return{type:"normal",arg:Ae.call(fe,se)}}catch(st){return{type:"throw",arg:st}}}var W="suspendedStart",G="suspendedYield",K="executing",ae="completed",ee={};function De(){}function X(){}function re(){}var be={};R(be,d,function(){return this});var Ne=Object.getPrototypeOf,Q=Ne&&Ne(Ne($e([])));Q&&Q!==a&&c.call(Q,d)&&(be=Q);var ce=re.prototype=De.prototype=Object.create(be);X.prototype=re,e(ce,"constructor",{value:re,configurable:!0}),e(re,"constructor",{value:X,configurable:!0}),X.displayName=R(re,S,"GeneratorFunction");function me(Ae){["next","throw","return"].forEach(function(fe){R(Ae,fe,function(se){return this._invoke(fe,se)})})}r.isGeneratorFunction=function(Ae){var fe=typeof Ae=="function"&&Ae.constructor;return fe?fe===X||(fe.displayName||fe.name)==="GeneratorFunction":!1},r.mark=function(Ae){return Object.setPrototypeOf?Object.setPrototypeOf(Ae,re):(Ae.__proto__=re,R(Ae,S,"GeneratorFunction")),Ae.prototype=Object.create(ce),Ae},r.awrap=function(Ae){return{__await:Ae}};function _e(Ae,fe){function se(ht,It,qe,Ue){var wt=H(Ae[ht],Ae,It);if(wt.type==="throw")Ue(wt.arg);else{var Yt=wt.arg,Xe=Yt.value;return Xe&&typeof Xe=="object"&&c.call(Xe,"__await")?fe.resolve(Xe.__await).then(function(Je){se("next",Je,qe,Ue)},function(Je){se("throw",Je,qe,Ue)}):fe.resolve(Xe).then(function(Je){Yt.value=Je,qe(Yt)},function(Je){return se("throw",Je,qe,Ue)})}}var st;function We(ht,It){function qe(){return new fe(function(Ue,wt){se(ht,It,Ue,wt)})}return st=st?st.then(qe,qe):qe()}e(this,"_invoke",{value:We})}me(_e.prototype),R(_e.prototype,A,function(){return this}),r.AsyncIterator=_e,r.async=function(Ae,fe,se,st,We){We===void 0&&(We=Promise);var ht=new _e(N(Ae,fe,se,st),We);return r.isGeneratorFunction(fe)?ht:ht.next().then(function(It){return It.done?It.value:ht.next()})};function ue(Ae,fe,se){var st=W;return function(We,ht){if(st===K)throw new Error("Generator is already running");if(st===ae){if(We==="throw")throw ht;return zt()}for(se.method=We,se.arg=ht;;){var It=se.delegate;if(It){var qe=ye(It,se);if(qe){if(qe===ee)continue;return qe}}if(se.method==="next")se.sent=se._sent=se.arg;else if(se.method==="throw"){if(st===W)throw st=ae,se.arg;se.dispatchException(se.arg)}else se.method==="return"&&se.abrupt("return",se.arg);st=K;var Ue=H(Ae,fe,se);if(Ue.type==="normal"){if(st=se.done?ae:G,Ue.arg===ee)continue;return{value:Ue.arg,done:se.done}}else Ue.type==="throw"&&(st=ae,se.method="throw",se.arg=Ue.arg)}}}function ye(Ae,fe){var se=fe.method,st=Ae.iterator[se];if(st===f)return fe.delegate=null,se==="throw"&&Ae.iterator.return&&(fe.method="return",fe.arg=f,ye(Ae,fe),fe.method==="throw")||se!=="return"&&(fe.method="throw",fe.arg=new TypeError("The iterator does not provide a '"+se+"' method")),ee;var We=H(st,Ae.iterator,fe.arg);if(We.type==="throw")return fe.method="throw",fe.arg=We.arg,fe.delegate=null,ee;var ht=We.arg;if(!ht)return fe.method="throw",fe.arg=new TypeError("iterator result is not an object"),fe.delegate=null,ee;if(ht.done)fe[Ae.resultName]=ht.value,fe.next=Ae.nextLoc,fe.method!=="return"&&(fe.method="next",fe.arg=f);else return ht;return fe.delegate=null,ee}me(ce),R(ce,S,"Generator"),R(ce,d,function(){return this}),R(ce,"toString",function(){return"[object Generator]"});function Re(Ae){var fe={tryLoc:Ae[0]};1 in Ae&&(fe.catchLoc=Ae[1]),2 in Ae&&(fe.finallyLoc=Ae[2],fe.afterLoc=Ae[3]),this.tryEntries.push(fe)}function J(Ae){var fe=Ae.completion||{};fe.type="normal",delete fe.arg,Ae.completion=fe}function Se(Ae){this.tryEntries=[{tryLoc:"root"}],Ae.forEach(Re,this),this.reset(!0)}r.keys=function(Ae){var fe=Object(Ae),se=[];for(var st in fe)se.push(st);return se.reverse(),function We(){for(;se.length;){var ht=se.pop();if(ht in fe)return We.value=ht,We.done=!1,We}return We.done=!0,We}};function $e(Ae){if(Ae){var fe=Ae[d];if(fe)return fe.call(Ae);if(typeof Ae.next=="function")return Ae;if(!isNaN(Ae.length)){var se=-1,st=function We(){for(;++se<Ae.length;)if(c.call(Ae,se))return We.value=Ae[se],We.done=!1,We;return We.value=f,We.done=!0,We};return st.next=st}}return{next:zt}}r.values=$e;function zt(){return{value:f,done:!0}}return Se.prototype={constructor:Se,reset:function(Ae){if(this.prev=0,this.next=0,this.sent=this._sent=f,this.done=!1,this.delegate=null,this.method="next",this.arg=f,this.tryEntries.forEach(J),!Ae)for(var fe in this)fe.charAt(0)==="t"&&c.call(this,fe)&&!isNaN(+fe.slice(1))&&(this[fe]=f)},stop:function(){this.done=!0;var Ae=this.tryEntries[0],fe=Ae.completion;if(fe.type==="throw")throw fe.arg;return this.rval},dispatchException:function(Ae){if(this.done)throw Ae;var fe=this;function se(Ue,wt){return ht.type="throw",ht.arg=Ae,fe.next=Ue,wt&&(fe.method="next",fe.arg=f),!!wt}for(var st=this.tryEntries.length-1;st>=0;--st){var We=this.tryEntries[st],ht=We.completion;if(We.tryLoc==="root")return se("end");if(We.tryLoc<=this.prev){var It=c.call(We,"catchLoc"),qe=c.call(We,"finallyLoc");if(It&&qe){if(this.prev<We.catchLoc)return se(We.catchLoc,!0);if(this.prev<We.finallyLoc)return se(We.finallyLoc)}else if(It){if(this.prev<We.catchLoc)return se(We.catchLoc,!0)}else if(qe){if(this.prev<We.finallyLoc)return se(We.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Ae,fe){for(var se=this.tryEntries.length-1;se>=0;--se){var st=this.tryEntries[se];if(st.tryLoc<=this.prev&&c.call(st,"finallyLoc")&&this.prev<st.finallyLoc){var We=st;break}}We&&(Ae==="break"||Ae==="continue")&&We.tryLoc<=fe&&fe<=We.finallyLoc&&(We=null);var ht=We?We.completion:{};return ht.type=Ae,ht.arg=fe,We?(this.method="next",this.next=We.finallyLoc,ee):this.complete(ht)},complete:function(Ae,fe){if(Ae.type==="throw")throw Ae.arg;return Ae.type==="break"||Ae.type==="continue"?this.next=Ae.arg:Ae.type==="return"?(this.rval=this.arg=Ae.arg,this.method="return",this.next="end"):Ae.type==="normal"&&fe&&(this.next=fe),ee},finish:function(Ae){for(var fe=this.tryEntries.length-1;fe>=0;--fe){var se=this.tryEntries[fe];if(se.finallyLoc===Ae)return this.complete(se.completion,se.afterLoc),J(se),ee}},catch:function(Ae){for(var fe=this.tryEntries.length-1;fe>=0;--fe){var se=this.tryEntries[fe];if(se.tryLoc===Ae){var st=se.completion;if(st.type==="throw"){var We=st.arg;J(se)}return We}}throw new Error("illegal catch attempt")},delegateYield:function(Ae,fe,se){return this.delegate={iterator:$e(Ae),resultName:fe,nextLoc:se},this.method==="next"&&(this.arg=f),ee}},r}(o.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(QA);var wf={exports:{}};(function(o){(function(n,r){o.exports?o.exports=r():n.log=r()})(Sb,function(){var n=function(){},r="undefined",a=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),c=["trace","debug","info","warn","error"];function e(G,K){var ae=G[K];if(typeof ae.bind=="function")return ae.bind(G);try{return Function.prototype.bind.call(ae,G)}catch{return function(){return Function.prototype.apply.apply(ae,[G,arguments])}}}function f(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function g(G){return G==="debug"&&(G="log"),typeof console===r?!1:G==="trace"&&a?f:console[G]!==void 0?e(console,G):console.log!==void 0?e(console,"log"):n}function d(G,K){for(var ae=0;ae<c.length;ae++){var ee=c[ae];this[ee]=ae<G?n:this.methodFactory(ee,G,K)}this.log=this.debug}function A(G,K,ae){return function(){typeof console!==r&&(d.call(this,K,ae),this[G].apply(this,arguments))}}function S(G,K,ae){return g(G)||A.apply(this,arguments)}function R(G,K,ae){var ee=this,De;K=K??"WARN";var X="loglevel";typeof G=="string"?X+=":"+G:typeof G=="symbol"&&(X=void 0);function re(ce){var me=(c[ce]||"silent").toUpperCase();if(!(typeof window===r||!X)){try{window.localStorage[X]=me;return}catch{}try{window.document.cookie=encodeURIComponent(X)+"="+me+";"}catch{}}}function be(){var ce;if(!(typeof window===r||!X)){try{ce=window.localStorage[X]}catch{}if(typeof ce===r)try{var me=window.document.cookie,_e=me.indexOf(encodeURIComponent(X)+"=");_e!==-1&&(ce=/^([^;]+)/.exec(me.slice(_e))[1])}catch{}return ee.levels[ce]===void 0&&(ce=void 0),ce}}function Ne(){if(!(typeof window===r||!X)){try{window.localStorage.removeItem(X);return}catch{}try{window.document.cookie=encodeURIComponent(X)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}ee.name=G,ee.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},ee.methodFactory=ae||S,ee.getLevel=function(){return De},ee.setLevel=function(ce,me){if(typeof ce=="string"&&ee.levels[ce.toUpperCase()]!==void 0&&(ce=ee.levels[ce.toUpperCase()]),typeof ce=="number"&&ce>=0&&ce<=ee.levels.SILENT){if(De=ce,me!==!1&&re(ce),d.call(ee,ce,G),typeof console===r&&ce<ee.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+ce},ee.setDefaultLevel=function(ce){K=ce,be()||ee.setLevel(ce,!1)},ee.resetLevel=function(){ee.setLevel(K,!1),Ne()},ee.enableAll=function(ce){ee.setLevel(ee.levels.TRACE,ce)},ee.disableAll=function(ce){ee.setLevel(ee.levels.SILENT,ce)};var Q=be();Q==null&&(Q=K),ee.setLevel(Q,!1)}var N=new R,H={};N.getLogger=function(G){if(typeof G!="symbol"&&typeof G!="string"||G==="")throw new TypeError("You must supply a name when creating a logger.");var K=H[G];return K||(K=H[G]=new R(G,N.getLevel(),N.methodFactory)),K};var W=typeof window!==r?window.log:void 0;return N.noConflict=function(){return typeof window!==r&&window.log===N&&(window.log=W),N},N.getLoggers=function(){return H},N.default=N,N})})(wf);var Vn=wf.exports;const Hs=()=>`${new Date().toISOString()} | metrics`,zs=(o,n,r)=>`${o} | ${n} | ${r}`;Vn.setDefaultLevel(Vn.levels.TRACE);const ZA=o=>{Vn.info(zs(Hs(),"log ",`set log level to ${o?"verbose":"info"}`)),Vn.setLevel(o?Vn.levels.TRACE:Vn.levels.INFO)},e1=o=>{const n=[...Object.keys(Vn.levels)];n.includes(o)?(Vn.info(zs(Hs(),"log ",`update log level to ${o.toLowerCase()}`)),Vn.setLevel(o)):Vn.warn(zs(Hs(),"log ","Incorrect log level please choose one of "),n)},Rt=(o,n,r)=>{r?Vn.debug(zs(Hs(),o,n),r):Vn.debug(zs(Hs(),o,n))},Ud=(o,n)=>{Vn.info(zs(Hs(),o,n))},wa=(o,n)=>{Vn.info(zs(Hs(),o,n))},Fu=(o,n)=>{Vn.warn(zs(Hs(),o,n))},so=(o,n)=>{Vn.error(zs(Hs(),o,n))};function t1(o){return Math.floor(Math.random()*o).toString()}function Sf(o,n){let r=n;return o.forEach(a=>{r=r.replace(a,"")}),r}function n1(o,n){let r="";for(let a=0;a<n;a+=1)r+=o[t1(o.length)];return r}function r1({length:o=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:a=[],excludeSymbols:c=[]}={}){let e="abcdefghijklmnopqrstuvwxyz",f="0123456789",g=[],d=[],A=[];return n&&(c.length&&(e=Sf(c,e)),d=e.split("")),r&&(c.length&&(f=Sf(c,f)),A=f.split("")),g=[...d,...A,...a],n1(g,o)}var s1=r1;const fl=Qt(s1),i1=()=>"WebRTCMetrics",a1=()=>"5.0.3",Ht={INBOUND:"inbound",OUTBOUND:"outbound"},Fs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ml={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},o1=()=>({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:[]}),Ef={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:Ht.INBOUND},Cf={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:Ht.OUTBOUND},Af={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:Ht.INBOUND},If={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:Ht.OUTBOUND},l1=o=>{const n={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(o){const r={...o,audio:{},video:{},data:{...o.data},network:{...o.network},experimental:{...o.experimental}};return Object.keys(o.audio).forEach(a=>{r.audio[a]={...o.audio[a]}}),Object.keys(o.video).forEach(a=>{r.video[a]={...o.video[a]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},u1={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${fl()}`,cid:`c-${fl()}`,uid:`u-${fl()}`,record:!1,ticket:!0},Vr={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"},ge={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"},ie={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},gl={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Pd={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Me={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Ld="config ",c1=(o,n={},r)=>{const a={...r,...n};return n.pname||Fu(Ld,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||Fu(Ld,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||Fu(Ld,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),a.pc=o,a},d1=(o={})=>{const n={...u1,...o};return n.name=i1(),n.version=a1(),n},yl=(o,n,r,a=!1,c)=>{let e=o.map(f=>{if(!r)return f[n];if(!c)return f[n][r];const g=f[n][c];return g?g[r]:null});return e=e.filter(f=>a?Number.isFinite(f)&&f>0:Number.isFinite(f)),e.length===0?[]:e},mi=o=>o.reduce((n,r)=>n+r,0)/o.length,h1=()=>`probe-${fl()}`,p1=()=>`coltr-${fl()}`,Rf=o=>new Promise(n=>setTimeout(n,o)),qd=(o,n,r)=>{n?o.call(n,r):o(r)},Zt=(o,n,r,a)=>{const c=yl(o,n,r,!0,a);if(c.length===0)return null;const e=c.reduce((f,g)=>f+g,0)/c.length;return e===0?null:c.map(f=>Math.abs(e-f)).reduce((f,g)=>f+g,0)/c.length*100/e},nn=(o,n,r,a=!1,c)=>{const e=yl(o,n,r,a,c);return e.length===0?null:e.reduce((f,g)=>f+g,0)/e.length},Sa=(o,n,r)=>yl(o,n,r).reduce((a,c)=>a+c,0),en=(o,n,r,a)=>{const c=yl(o,n,r,!0,a);return c.length===0?null:Math.min(...c)},tn=(o,n,r,a)=>{const c=yl(o,n,r,!1,a);return c.length===0?null:Math.max(...c)},Un=(o,n,r,a)=>{const c=o.slice().pop();if(!c)return null;if(!r)return c[n];if(!a)return c[n][r];const e=c[n][a];return e?e[r]:null},_1=o=>o.slice().pop(),wn=(o,n,r)=>{if(!n)return null;const a={};let c=n[ie.AUDIO][o];c||(c=r===Ht.INBOUND?{...Ef}:{...Cf}),a[ie.AUDIO]=c;let e=n[ie.VIDEO][o];return e||(e=r===Ht.INBOUND?{...Af}:{...If}),a[ie.VIDEO]=e,a},vl="exporter ",f1="2.0",$f=(o,n,r)=>{if(!o||o.length===0)return 0;const a=o[o.length-1];if(!a)return 0;const c=a[n][r];if(c){const e=c.total_rtt_ms_out,f=c.total_rtt_measure_out;return!f||!e?nn(o,n,"delta_rtt_ms_out",!1,r):Number(e/f)}return null},m1=(o,n)=>{if(!o||o.length===0)return 0;const r=o[o.length-1];if(!r)return 0;const a=r[n].total_rtt_connectivity_ms,c=r[n].total_rtt_connectivity_measure;return!c||!a?nn(o,n,"delta_rtt_connectivity_ms"):Number(a/c)},g1=o=>Un(o,"network","local_candidate_type")!=="relay"?`direct/${Un(o,"network","local_candidate_protocol")}`:`turn/${Un(o,"network","local_candidate_relay_protocol")}`,y1=o=>{const n=Un(o,"network","remote_candidate_type"),r=Un(o,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class v1{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ud(vl,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){Ud(vl,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Rt(vl,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){Ud(vl,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Rt(vl,"ticket() - generate ticket");const n=Un(this._reports,"audio","total_packets_lost_in"),r=Un(this._reports,"audio","total_packets_in"),a=Un(this._reports,"video","total_packets_lost_in"),c=Un(this._reports,"video","total_packets_in"),e={},f=_1(this._reports);return f&&(Object.keys(f[ie.AUDIO]).forEach(g=>{const d=f[ie.AUDIO][g];if(e[d.ssrc]={type:ie.AUDIO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_kbs_in",g),max:tn(this._reports,ie.AUDIO,"delta_kbs_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_KBytes_in",g),max:tn(this._reports,ie.AUDIO,"delta_KBytes_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_in",!1,g),min:en(this._reports,ie.AUDIO,"mos_emodel_in",g),max:tn(this._reports,ie.AUDIO,"mos_emodel_in",g),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_in",g)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_in",!1,g),min:en(this._reports,ie.AUDIO,"mos_in",g),max:tn(this._reports,ie.AUDIO,"mos_in",g),volatility:Zt(this._reports,ie.AUDIO,"mos_in",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_in",g),W=Un(this._reports,ie.AUDIO,"total_packets_in",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].mos=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G}else{const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_kbs_out",g),max:tn(this._reports,ie.AUDIO,"delta_kbs_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_KBytes_out",g),max:tn(this._reports,ie.AUDIO,"delta_KBytes_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},N={avg:$f(this._reports,ie.AUDIO,g),min:en(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),max:tn(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_out",g),W=Un(this._reports,ie.AUDIO,"total_packets_out",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},K={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_out",!1,g),min:en(this._reports,ie.AUDIO,"mos_emodel_out",g),max:tn(this._reports,ie.AUDIO,"mos_emodel_out",g),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_out",g)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_out",!1,g),min:en(this._reports,ie.AUDIO,"mos_out",g),max:tn(this._reports,ie.AUDIO,"mos_out",g),volatility:Zt(this._reports,ie.AUDIO,"mos_out",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[g].jitter=A,e[g].rtt=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G,e[g].mos=K}}),Object.keys(f[ie.VIDEO]).forEach(g=>{const d=f[ie.VIDEO][g];if(e[g]={type:ie.VIDEO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_kbs_in",g),max:tn(this._reports,ie.VIDEO,"delta_kbs_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_KBytes_in",g),max:tn(this._reports,ie.VIDEO,"delta_KBytes_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N=Un(this._reports,ie.VIDEO,"total_packets_lost_in",g),H=Un(this._reports,ie.VIDEO,"total_packets_in",g),W={lost:N,avg:Math.round((N/(N+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].traffic=R,e[g].bitrate=S,e[g].loss=W}else{const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_kbs_out",g),max:tn(this._reports,ie.VIDEO,"delta_kbs_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_KBytes_out",g),max:tn(this._reports,ie.VIDEO,"delta_KBytes_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={avg:$f(this._reports,ie.VIDEO,g),min:en(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),max:tn(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.VIDEO,"total_packets_lost_out",g),W=Un(this._reports,ie.VIDEO,"total_packets_out",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].rtt=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G}})),{version:f1,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:e,data:{rtt:{avg:m1(this._reports,"data"),min:en(this._reports,"data","delta_rtt_connectivity_ms"),max:tn(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Zt(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+r)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+c)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:nn(this._reports,"data","delta_kbs_in"),min:en(this._reports,"data","delta_kbs_in"),max:tn(this._reports,"data","delta_kbs_in"),volatility:Zt(this._reports,"data","delta_kbs_in")},out:{avg:nn(this._reports,"data","delta_kbs_out"),min:en(this._reports,"data","delta_kbs_out"),max:tn(this._reports,"data","delta_kbs_out"),volatility:Zt(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:nn(this._reports,"data","delta_KBytes_in"),min:en(this._reports,"data","delta_KBytes_in"),max:tn(this._reports,"data","delta_KBytes_in"),volatility:Zt(this._reports,"data","delta_KBytes_in")},out:{avg:nn(this._reports,"data","delta_KBytes_out"),min:en(this._reports,"data","delta_KBytes_out"),max:tn(this._reports,"data","delta_KBytes_out"),volatility:Zt(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:g1(this._reports),remoteConnection:y1(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const gi="extractor ",xf=(o,n,r,a)=>{let c=!1;const e=a[n].total_rtt_ms_out,f=a[n].total_rtt_measure_out,g=r?r[n].total_rtt_ms_out:0,d=r?r[n].total_rtt_measure_out:0,A={rtt:null,totalRTT:e,totalRTTMeasurements:f};if(o[ge.TIMESTAMP]===a[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ge.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(c=!0,Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===f))return A;const S=1e3*Number(o[ge.ROUND_TRIP_TIME]);let R=e+S,N=f+1;return c&&(R=1e3*Number(o[ge.TOTAL_ROUND_TRIP_TIME])-g,N=Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:S,totalRTT:R,totalRTTMeasurements:N}},T1=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[n].total_rtt_connectivity_ms,totalRTTMeasurements:a[n].total_rtt_connectivity_measure};const c=1e3*Number(o[ge.CURRENT_ROUND_TRIP_TIME]);let e=a[n].total_rtt_connectivity_ms+c,f=a[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ROUND_TRIP_TIME)&&(e=1e3*Number(o[ge.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(o,ge.RESPONSES_RECEIVED)&&(f=Number(o[ge.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:c,totalRTT:e,totalRTTMeasurements:f}},Bu=(o,n,r)=>o[ge.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ge.JITTER)?null:1e3*(Number(o[ge.JITTER])||0),b1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(o,ge.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[ie.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[ie.VIDEO].total_frames_decoded_in,total_decode_time:n[ie.VIDEO].total_time_decoded_in};const r=o[ge.FRAMES_DECODED],a=o[ge.TOTAL_DECODE_TIME],c=a-n[ie.VIDEO].total_time_decoded_in,e=r-n[ie.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:e>0?c*1e3/e:0,frames_decoded:r,total_decode_time:a}},w1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[ie.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[ie.VIDEO].total_frames_encoded_out,total_encode_time:n[ie.VIDEO].total_time_encoded_out};const r=o[ge.FRAMES_ENCODED],a=o[ge.TOTAL_ENCODE_TIME],c=a-n[ie.VIDEO].total_time_encoded_out,e=r-n[ie.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:e>0&&c?c*1e3/e:0,frames_encoded:r,total_encode_time:a}},Of=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(o,ge.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const c=Number(o[ge.PACKETS_SENT])||0-(a?a[n].total_packets_out:0),e=c-r[n].total_packets_out,f=Number(o[ge.BYTES_SENT])/1024-(a?a[n].total_KBytes_out:0),g=f-r[n].total_KBytes_out,d=o[ge.TIMESTAMP]||Date.now(),A=a?a.timestamp:null;let S=r.timestamp;!S&&A&&(S=A);const R=S?d-S:0,N=R>0?g*.008*1024/R*1e3:0;return{packetsSent:c,deltaPacketsSent:e,KBytesSent:f,deltaKBytesSent:g,kbsSent:N}},kf=(o,n,r,a)=>{let c=r[n].total_packets_lost_out,e=0,f=0;return Object.prototype.hasOwnProperty.call(o,ge.PACKETS_LOST)&&(c=Number(o[ge.PACKETS_LOST])||0-(a?a[n].total_packets_lost_out:0),e=c-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(o,ge.FRACTION_LOST)&&(f=Number(100*o[ge.FRACTION_LOST])),{packetsLost:c,deltaPacketsLost:e,fractionLost:f}},Df=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(o,ge.BYTES_RECEIVED))return{percent_packets_lost:r[n].percent_packets_lost_in,packetsReceived:r[n].total_packets_in,packetsLost:r[n].total_packets_lost_in,bytesReceived:r[n].total_KBytes_in};const c=Number(o[ge.PACKETS_RECEIVED])||0-(a?a[n].total_packets_in:0),e=Number(o[ge.PACKETS_LOST])||0-(a?a[n].total_packets_lost_in:0),f=e-r[n].total_packets_lost_in,g=c-r[n].total_packets_in,d=c!==r[n].total_packets_in?f*100/(f+g):0,A=Number(o[ge.BYTES_RECEIVED])/1024-(a?a[n].total_KBytes_in:0),S=A-r[n].total_KBytes_in,R=o[ge.TIMESTAMP]||Date.now(),N=a?a.timestamp:null;let H=r.timestamp;!H&&N&&(H=N);const W=H?R-H:0,G=W>0?S*.008*1024/W*1e3:0;return{percentPacketsLost:d,packetsReceived:c,deltaPacketsReceived:g,packetsLost:e,deltaPacketsLost:f,KBytesReceived:A,deltaKBytesReceived:S,kbsReceived:G}},S1=o=>o[ge.CANDIDATE_TYPE]!=="relay"?"":o[ge.RELAY_PROTOCOL]||"",E1=o=>{if(!Object.prototype.hasOwnProperty.call(o,ge.NETWORK_TYPE))return gl.WIFI;switch(o[ge.NETWORK_TYPE]){case Pd.ETHERNET:return gl.ETHERNET;case Pd.CELLULAR_4G:return gl.CELLULAR_4G;case Pd.WIFI:return gl.WIFI;default:return gl.CELLULAR}},Nf=o=>!Object.prototype.hasOwnProperty.call(o,ge.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(o,ge.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:o[ge.FRAME_WIDTH]||null,height:o[ge.FRAME_HEIGHT]||null,framerate:o[ge.FRAMES_PER_SECOND]},C1=o=>{const n=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_REASON)?o[ge.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_RESOLUTION_CHANGES)?o[ge.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_DURATIONS)?o[ge.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(c=>{a[c]>1e3&&(a[c]=Number(a[c]/1e3))}),{reason:n,durations:a,resolutionChanges:r}},A1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PLI)||!Object.prototype.hasOwnProperty.call(o,ge.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(o[ge.PLI]||0)-(r?r[ie.VIDEO].total_pli_sent_in:0),c=(o[ge.NACK]||0)-(r?r[ie.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ie.VIDEO].total_pli_sent_in,deltaNackCount:c-n[ie.VIDEO].total_nack_sent_in}},I1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PLI)||!Object.prototype.hasOwnProperty.call(o,ge.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(o[ge.PLI]||0)-(r?r[ie.VIDEO].total_pli_received_out:0),c=(o[ge.NACK]||0)-(r?r[ie.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ie.VIDEO].total_pli_received_out,deltaNackCount:c-n[ie.VIDEO].total_nack_received_out}},R1=o=>({channels:o[ge.CHANNELS]||null,clock_rate:o[ge.CLOCK_RATE]||null,mime_type:o[ge.MIME_TYPE]||null,sdp_fmtp_line:o[ge.SDP_FMTP_LINE]||null}),$1=o=>({clock_rate:o[ge.CLOCK_RATE]||null,mime_type:o[ge.MIME_TYPE]||null}),x1=(o,n,r)=>{const a=(o[ge.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),c=(o[ge.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),e=o[ge.TIMESTAMP]||Date.now(),f=a-n.data.total_KBytes_in,g=c-n.data.total_KBytes_out,d=r?r.timestamp:null;let A=n.timestamp;!A&&d&&(A=d);const S=A?e-A:0,R=S>0?f*.008*1024/S*1e3:0,N=S>0?g*.008*1024/S*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:c,delta_KBytes_received:f,delta_KBytes_sent:g,kbs_speed_received:R,kbs_speed_sent:N}},O1=o=>{const n=o[ge.AVAILABLE_INCOMING_BITRATE]/1024||0,r=o[ge.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},k1=(o,n,r,a)=>{if(!o)return[];switch(o[ge.TYPE]){case Vr.CANDIDATE_PAIR:let c=!1;if(o[ge.NOMINATED]&&o[ge.STATE]===ie.SUCCEEDED&&(c=!0,Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o),ge.SELECTED in o&&!o[ge.SELECTED]&&(c=!1)),c){const f=o[ge.LOCAL_CANDIDATE_ID],g=o[ge.REMOTE_CANDIDATE_ID],d=x1(o,n,a),A=O1(o),S=T1(o,"data",a,n);return[{type:Me.NETWORK,value:{local_candidate_id:f}},{type:Me.NETWORK,value:{remote_candidate_id:g}},{type:Me.DATA,value:{total_KBytes_in:d.total_KBytes_received}},{type:Me.DATA,value:{total_KBytes_out:d.total_KBytes_sent}},{type:Me.DATA,value:{delta_KBytes_in:d.delta_KBytes_received}},{type:Me.DATA,value:{delta_KBytes_out:d.delta_KBytes_sent}},{type:Me.DATA,value:{delta_kbs_in:d.kbs_speed_received}},{type:Me.DATA,value:{delta_kbs_out:d.kbs_speed_sent}},{type:Me.DATA,value:{delta_kbs_bandwidth_in:A.kbs_incoming_bandwidth}},{type:Me.DATA,value:{delta_kbs_bandwidth_out:A.kbs_outgoing_bandwidth}},{type:Me.DATA,value:{delta_rtt_connectivity_ms:S.rtt}},{type:Me.DATA,value:{total_rtt_connectivity_ms:S.totalRTT}},{type:Me.DATA,value:{total_rtt_connectivity_measure:S.totalRTTMeasurements}}]}break;case Vr.LOCAL_CANDIDATE:if(o[ge.ID]===n.network.local_candidate_id)return[{type:Me.NETWORK,value:{infrastructure:E1(o)}},{type:Me.NETWORK,value:{local_candidate_type:o[ge.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{local_candidate_protocol:o[ge.PROTOCOL]||""}},{type:Me.NETWORK,value:{local_candidate_relay_protocol:S1(o)}}];break;case Vr.REMOTE_CANDIDATE:if(o[ge.ID]===n.network.remote_candidate_id)return[{type:Me.NETWORK,value:{remote_candidate_type:o[ge.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{remote_candidate_protocol:o[ge.PROTOCOL]||""}}];break;case Vr.INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const f=o[ge.SSRC],g=wn(f,n,Ht.INBOUND);g&&(g.timestamp=n.timestamp);const d=wn(f,a,Ht.INBOUND);if(d&&(d.timestamp=a.timestamp),o[ge.MEDIA_TYPE]===ie.AUDIO){const A=Df(o,ie.AUDIO,g,d),S=Bu(o,ie.AUDIO,g),R=o[ge.CODEC_ID]||"";return[{ssrc:f,type:Me.AUDIO,value:{codec_id_in:R}},{ssrc:f,type:Me.AUDIO,value:{total_packets_in:A.packetsReceived}},{ssrc:f,type:Me.AUDIO,value:{delta_packets_in:A.deltaPacketsReceived}},{ssrc:f,type:Me.AUDIO,value:{total_packets_lost_in:A.packetsLost}},{ssrc:f,type:Me.AUDIO,value:{delta_packets_lost_in:A.deltaPacketsLost}},{ssrc:f,type:Me.AUDIO,value:{percent_packets_lost_in:A.percentPacketsLost}},{ssrc:f,type:Me.AUDIO,value:{total_KBytes_in:A.KBytesReceived}},{ssrc:f,type:Me.AUDIO,value:{delta_KBytes_in:A.deltaKBytesReceived}},{ssrc:f,type:Me.AUDIO,value:{delta_kbs_in:A.kbsReceived}},{ssrc:f,type:Me.AUDIO,value:{delta_jitter_ms_in:S}}]}if(o[ge.MEDIA_TYPE]===ie.VIDEO){const A=b1(o,g),S=Df(o,ie.VIDEO,g,d),R=Bu(o,ie.VIDEO,g),N=o[ge.DECODER_IMPLEMENTATION]||null,H=o[ge.CODEC_ID]||null,W=Nf(o),G=A1(o,g,d);return[{ssrc:f,type:Me.VIDEO,value:{codec_id_in:H}},{ssrc:f,type:Me.VIDEO,value:{total_packets_in:S.packetsReceived}},{ssrc:f,type:Me.VIDEO,value:{delta_packets_in:S.deltaPacketsReceived}},{ssrc:f,type:Me.VIDEO,value:{total_packets_lost_in:S.packetsLost}},{ssrc:f,type:Me.VIDEO,value:{delta_packets_lost_in:S.deltaPacketsLost}},{ssrc:f,type:Me.VIDEO,value:{percent_packets_lost_in:S.percentPacketsLost}},{ssrc:f,type:Me.VIDEO,value:{total_KBytes_in:S.KBytesReceived}},{ssrc:f,type:Me.VIDEO,value:{delta_KBytes_in:S.deltaKBytesReceived}},{ssrc:f,type:Me.VIDEO,value:{delta_kbs_in:S.kbsReceived}},{ssrc:f,type:Me.VIDEO,value:{delta_jitter_ms_in:R}},{ssrc:f,type:Me.VIDEO,value:{decoder_in:N}},{ssrc:f,type:Me.VIDEO,value:{delta_ms_decode_frame_in:A.delta_ms_decode_frame}},{ssrc:f,type:Me.VIDEO,value:{total_frames_decoded_in:A.frames_decoded}},{ssrc:f,type:Me.VIDEO,value:{total_time_decoded_in:A.total_decode_time}},{ssrc:f,type:Me.VIDEO,value:{total_nack_sent_in:G.nackCount}},{ssrc:f,type:Me.VIDEO,value:{delta_nack_sent_in:G.deltaNackCount}},{ssrc:f,type:Me.VIDEO,value:{total_pli_sent_in:G.pliCount}},{ssrc:f,type:Me.VIDEO,value:{delta_pli_sent_in:G.deltaPliCount}},{ssrc:f,type:Me.VIDEO,value:{size_in:W}}]}break}case Vr.OUTBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const f=o[ge.SSRC],g=wn(f,n,Ht.OUTBOUND);g&&(g.timestamp=n.timestamp);const d=wn(f,a,Ht.OUTBOUND);if(d&&(d.timestamp=a.timestamp),o[ge.MEDIA_TYPE]===ie.AUDIO){const A=o[ge.CODEC_ID]||null,S=Of(o,ie.AUDIO,g,d);return[{ssrc:f,type:Me.AUDIO,value:{codec_id_out:A}},{ssrc:f,type:Me.AUDIO,value:{total_packets_out:S.packetsSent}},{ssrc:f,type:Me.AUDIO,value:{delta_packets_out:S.deltaPacketsSent}},{ssrc:f,type:Me.AUDIO,value:{total_KBytes_out:S.KBytesSent}},{ssrc:f,type:Me.AUDIO,value:{delta_KBytes_out:S.deltaKBytesSent}},{ssrc:f,type:Me.AUDIO,value:{delta_kbs_out:S.kbsSent}}]}if(o[ge.MEDIA_TYPE]===ie.VIDEO){const A=o[ge.ENCODER_IMPLEMENTATION]||null,S=o[ge.CODEC_ID]||null,R=w1(o,g),N=Nf(o),H=C1(o),W=I1(o,g,d),G=Of(o,ie.VIDEO,g,d);return[{ssrc:f,type:Me.VIDEO,value:{codec_id_out:S}},{ssrc:f,type:Me.VIDEO,value:{total_packets_out:G.packetsSent}},{ssrc:f,type:Me.VIDEO,value:{delta_packets_out:G.deltaPacketsSent}},{ssrc:f,type:Me.VIDEO,value:{total_KBytes_out:G.KBytesSent}},{ssrc:f,type:Me.VIDEO,value:{delta_KBytes_out:G.deltaKBytesSent}},{ssrc:f,type:Me.VIDEO,value:{delta_kbs_out:G.kbsSent}},{ssrc:f,type:Me.VIDEO,value:{encoder_out:A}},{ssrc:f,type:Me.VIDEO,value:{delta_ms_encode_frame_out:R.delta_ms_encode_frame}},{ssrc:f,type:Me.VIDEO,value:{total_frames_encoded_out:R.frames_encoded}},{ssrc:f,type:Me.VIDEO,value:{total_time_encoded_out:R.total_encode_time}},{ssrc:f,type:Me.VIDEO,value:{total_nack_received_out:W.nackCount}},{ssrc:f,type:Me.VIDEO,value:{delta_nack_received_out:W.deltaNackCount}},{ssrc:f,type:Me.VIDEO,value:{total_pli_received_out:W.pliCount}},{ssrc:f,type:Me.VIDEO,value:{delta_pli_received_out:W.deltaPliCount}},{ssrc:f,type:Me.VIDEO,value:{size_out:N}},{ssrc:f,type:Me.VIDEO,value:{limitation_out:H}}]}break}case Vr.MEDIA_SOURCE:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);break}case Vr.TRACK:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);break}case Vr.CODEC:const e=[];return Object.keys(n[ie.AUDIO]).forEach(f=>{const g=n[ie.AUDIO][f];if(g.codec_id_in===o[ge.ID]||g.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=R1(o);o[ge.ID]===g.codec_id_in?e.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_in:d}}):e.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_out:d}})}}),Object.keys(n[ie.VIDEO]).forEach(f=>{const g=n[ie.VIDEO][f];if(g.codec_id_in===o[ge.ID]||g.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=$1(o);o[ge.ID]===g.codec_id_in?e.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_in:d}}):e.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_out:d}})}}),e;case Vr.REMOTE_INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const f=o[ge.SSRC],g=wn(f,n,Ht.OUTBOUND),d=wn(f,a,Ht.OUTBOUND);if(o[ge.KIND]===ie.AUDIO){const A=xf(o,ie.AUDIO,d,g),S=Bu(o,ie.AUDIO,g),R=kf(o,ie.AUDIO,g,d);return[{ssrc:f,type:Me.AUDIO,value:{delta_rtt_ms_out:A.rtt}},{ssrc:f,type:Me.AUDIO,value:{total_rtt_ms_out:A.totalRTT}},{ssrc:f,type:Me.AUDIO,value:{total_rtt_measure_out:A.totalRTTMeasurements}},{ssrc:f,type:Me.AUDIO,value:{delta_jitter_ms_out:S}},{ssrc:f,type:Me.AUDIO,value:{timestamp_out:o[ge.TIMESTAMP]}},{ssrc:f,type:Me.AUDIO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:f,type:Me.AUDIO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:f,type:Me.AUDIO,value:{percent_packets_lost_out:R.fractionLost}}]}if(o[ge.KIND]===ie.VIDEO){const A=xf(o,ie.VIDEO,d,g),S=Bu(o,ie.VIDEO,g),R=kf(o,ie.VIDEO,g,d);return[{ssrc:f,type:Me.VIDEO,value:{delta_rtt_ms_out:A.rtt}},{ssrc:f,type:Me.VIDEO,value:{total_rtt_ms_out:A.totalRTT}},{ssrc:f,type:Me.VIDEO,value:{total_rtt_measure_out:A.totalRTTMeasurements}},{ssrc:f,type:Me.VIDEO,value:{delta_jitter_ms_out:S}},{ssrc:f,type:Me.VIDEO,value:{timestamp_out:o[ge.TIMESTAMP]}},{ssrc:f,type:Me.VIDEO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:f,type:Me.VIDEO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:f,type:Me.VIDEO,value:{percent_packets_lost_out:R.fractionLost}}]}break}}return[]},Vu=o=>o<0?1:o>100?4.5:1+.035*o+7/1e6*o*(o-60)*(100-o),D1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.INBOUND),f=wn(c,r,Ht.INBOUND),g=wn(c,a,Ht.INBOUND),d=[],A=[],S=e[n].percent_packets_lost_in,R=e[n].delta_jitter_ms_in,N=f&&f[n].delta_jitter_ms_in||null,H=g&&g[n].delta_jitter_ms_in||null,W=o.data.delta_rtt_connectivity_ms,G=r&&r.data.delta_rtt_connectivity_ms||null,K=a&&a.data.delta_rtt_connectivity_ms||null;W&&d.push(W),G&&d.push(G),K&&d.push(K),R&&A.push(R),r&&N&&A.push(N),a&&H&&A.push(H);const ae=d.length>0?mi(d):100,ee=A.length>0?mi(A):10,De=93.2-S,X=.18*De*De-27.9*De+1126.62,re=(ae+ee)/2,be=re-177.3<0?0:1,Ne=.024*re+.11*(re-177.3)*be,Q=X-Ne;return Vu(Q)},N1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.OUTBOUND),f=wn(c,r,Ht.OUTBOUND),g=wn(c,a,Ht.OUTBOUND),d=[],A=[],S=e[n].percent_packets_lost_out,R=e[n].delta_rtt_ms_out,N=f&&f[n].delta_rtt_ms_out||null,H=g&&g[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=f&&f[n].delta_jitter_ms_out||null,K=g&&g[n].delta_jitter_ms_out||null,ae=o.data.delta_rtt_connectivity_ms,ee=r&&r.data.delta_rtt_connectivity_ms||null,De=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):ae&&d.push(ae),N?d.push(N):ee&&d.push(ee),H?d.push(H):De&&d.push(De),W&&A.push(W),r&&G&&A.push(G),a&&K&&A.push(K);const X=d.length>0?mi(d):100,re=A.length>0?mi(A):10,be=93.2-S,Ne=.18*be*be-27.9*be+1126.62,Q=(X+re)/2,ce=Q-177.3<0?0:1,me=.024*Q+.11*(Q-177.3)*ce,_e=Ne-me;return Vu(_e)},M1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.INBOUND),f=wn(c,r,Ht.INBOUND),g=wn(c,a,Ht.INBOUND),d=[],A=[],S=e[n].percent_packets_lost_in/100,R=e[n].delta_jitter_ms_in,N=f&&f[n].delta_jitter_ms_in||null,H=g&&g[n].delta_jitter_ms_in||null,W=o.data.delta_rtt_connectivity_ms,G=r&&r.data.delta_rtt_connectivity_ms||null,K=a&&a.data.delta_rtt_connectivity_ms||null;W&&d.push(W),G&&d.push(G),K&&d.push(K),R&&A.push(R),f&&N&&A.push(N),g&&H&&A.push(H);const ae=d.length>0?mi(d):100,ee=A.length>0?mi(A):10,De=0,X=19.8,re=29.7,be=30,Ne=(ae+ee)/2+be,Q=Ne-177.3<0?0:1,ce=.024*Ne+.11*(Ne-177.3)*Q,me=93.2-(De+X*Math.log(1+re*S)+ce);return Vu(me)},U1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.OUTBOUND),f=wn(c,r,Ht.OUTBOUND),g=wn(c,a,Ht.OUTBOUND),d=[],A=[],S=e[n].percent_packets_lost_out/100,R=e[n].delta_rtt_ms_out,N=f&&f[n].delta_rtt_ms_out||null,H=g&&g[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=f&&f[n].delta_jitter_ms_out||null,K=g&&g[n].delta_jitter_ms_out||null,ae=o.data.delta_rtt_connectivity_ms,ee=r&&r.data.delta_rtt_connectivity_ms||null,De=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):ae&&d.push(ae),N?d.push(N):ee&&d.push(ee),H?d.push(H):De&&d.push(De),W&&A.push(W),f&&G&&A.push(G),g&&K&&A.push(K);const X=d.length>0?mi(d):100,re=A.length>0?mi(A):10,be=0,Ne=19.8,Q=29.7,ce=30,me=(X+re)/2+ce,_e=me-177.3<0?0:1,ue=.024*me+.11*(me-177.3)*_e,ye=93.2-(be+Ne*Math.log(1+Q*S)+ue);return Vu(ye)};class P1{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=p1(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new v1(n),this._state=Fs.IDLE,this.registerToPCEvents(),wa(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,a,c){const e=(d,A)=>d===ie.AUDIO?A===Vr.INBOUND_RTP?{...Ef}:{...Cf}:A===Vr.INBOUND_RTP?{...Af}:{...If},f=l1(r);f.pname=this._config.pname,f.call_id=this._config.cid,f.user_id=this._config.uid,f.count=r?r.count+1:1;let g=null;return n.forEach(d=>{!g&&d.timestamp&&(g=d.timestamp),k1(d,f,f.pname,c).forEach(A=>{if(A.value&&A.type)if(A.ssrc){let S=f[A.type][A.ssrc];S||(S=e(A.type,d.type),S.ssrc=A.ssrc,f[A.type][A.ssrc]=S),Object.keys(A.value).forEach(R=>{S[R]=A.value[R]})}else Object.keys(A.value).forEach(S=>{f[A.type][S]=A.value[S]})})}),f.timestamp=g,Object.keys(f[ie.AUDIO]).forEach(d=>{const A=f[ie.AUDIO][d];A.direction===Ht.INBOUND?(A.mos_emodel_in=D1(f,ie.AUDIO,r,a,A.ssrc),A.mos_in=M1(f,ie.AUDIO,r,a,A.ssrc)):(A.mos_emodel_out=N1(f,ie.AUDIO,r,a,A.ssrc),A.mos_out=U1(f,ie.AUDIO,r,a,A.ssrc))}),f}async takeReferenceStats(){return new Promise((n,r)=>{const a=Date.now();setTimeout(async()=>{try{const c=Date.now()-a,e=Date.now(),f=await this._config.pc.getStats(),g=this.analyze(f,null,null,null),d=Date.now();g.experimental.time_to_measure_ms=d-e,g.experimental.time_to_wait_ms=c,this._exporter.saveReferenceReport(g),Rt(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(c){r(c)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Fs.RUNNING||!this._config.pc)return Rt(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),a=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),c=Date.now();return a.experimental.time_to_measure_ms=c-n,this._exporter.addReport(a),Rt(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(n){return so(this._moduleName,`got error ${n}`),null}}async start(){Rt(this._moduleName,"starting"),this.state=Fs.RUNNING,this._startedTime=this._exporter.start(),Rt(this._moduleName,"started")}async mute(){this.state=Fs.MUTED,Rt(this._moduleName,"muted")}async unmute(){this.state=Fs.RUNNING,Rt(this._moduleName,"unmuted")}async stop(n){if(Rt(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Fs.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Rt(this._moduleName,"stopped")}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(this._moduleName,`registered callback '${n}'`)):so(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&qd(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&qd(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Rt(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,a,c){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:a,description:c})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{so(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const a=n.iceConnectionState;a===ml.CONNECTED||a===ml.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.DISCONNECTED||a===ml.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const a=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},n.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=n.getReceivers();if(r&&r.length>0){const a=r[0],{transport:c}=a;if(c){const{iceTransport:e}=c;e&&(e.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class L1{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||h1(),this._moduleName=this._id,wa(this._moduleName,"probe created"),this._config=n,this._collector=new P1(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):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(n){this._collector.state=n}addCustomEvent(n,r,a,c=new Date().toJSON()){this._collector.addCustomEvent(c,r,n,a)}get isRunning(){return this._collector.state===Fs.RUNNING}get isIdle(){return this._collector.state===Fs.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Fu(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const jn="engine ";class q1{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},wa(jn,`configured for probing every ${this._config.refreshEvery}ms`),wa(jn,`configured for starting after ${this._config.startAfter}ms`),wa(jn,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Rt(jn,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,r){if(!n)throw new Error("undefined peer connection");const a=c1(n,r,this._config),c=new L1(a);return this._probes.push(c),Rt(jn,`${this._probes.length} probes registered`),c}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===Fs.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(e=>e.start())},r=async()=>Promise.all(this._probes.map(e=>e.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,c=async()=>{const e=o1(),f=this._probes.filter(g=>g.isRunning);for(const g of f){const d=await g.collectStats();d&&e.probes.push(d),Rt(jn,`got probe ${g.id}`),await Rf(0)}return e.delta_time_to_measure_probes_ms=Sa(e.probes,"experimental","time_to_measure_ms"),e.delta_KBytes_in=Sa(e.probes,"data","delta_KBytes_in"),e.delta_KBytes_out=Sa(e.probes,"data","delta_KBytes_out"),e.delta_kbs_in=Sa(e.probes,"data","delta_kbs_in"),e.delta_kbs_out=Sa(e.probes,"data","delta_kbs_out"),e.total_time_decoded_in=Sa(e.probes,"video","total_time_decoded_in"),e.total_time_encoded_out=Sa(e.probes,"video","total_time_encoded_out"),e};for(Rt(jn,"starting to collect"),n(),Rt(jn,"generating reference reports..."),await r(),Rt(jn,"reference reports generated"),this._startedTime=Date.now();a();)if(Rt(jn,`wait ${this._config.refreshEvery}ms before collecting`),await Rf(this._config.refreshEvery),a()){Rt(jn,"collecting...");const e=Date.now(),f=await c(),g=Date.now();f.delta_time_consumed_to_measure_ms=g-e,this.fireOnReports(f),Rt(jn,"collected")}Rt(jn,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=a=>{this._probes.forEach(c=>{c.stop(a)})};wa(jn,"stop collecting"),r(n)}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(jn,`registered callback '${n}'`)):so(jn,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&qd(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const H1="interface ";class z1{constructor(n){this._config=d1(n),wa(H1,`welcome to ${this._config.name} version ${this._config.version}`),ZA(this._config.verbose||!1),this._engine=new q1(this._config)}setupLogLevel(n){e1(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,r){return this._engine.addNewProbe(n,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function F1(o,n){return Object.keys(o).filter(r=>n.includes(r)).reduce((r,a)=>{const c=a;return{...r,[c]:o[c]}},{})}const B1=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],V1={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class j1{constructor(n){this.intervals={},this.analysers={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}async start(n,r,a){r&&r.getTracks().length&&await this.beginCalculation(n,r,a)}stop(n){this.clearVolumeInterval(n),this.analysers[n]&&typeof this.analysers[n].disconnect=="function"&&(this.analysers[n].disconnect(),delete this.analysers[n])}clearVolumeInterval(n){this.intervals[n]&&(clearInterval(this.intervals[n]),delete this.intervals[n])}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{this.stop(n)}),this.intervals={},this.analysers={}}async beginCalculation(n,r,a){this.clearVolumeInterval(a);const c=n.createAnalyser(),e=n.createMediaStreamSource(r);c.smoothingTimeConstant=.8,c.fftSize=1024,e.connect(c),this.analysers[a]=c,this.intervals[a]=setInterval(()=>{const f=new Uint8Array(c.frequencyBinCount);c.getByteFrequencyData(f);let g=0;const d=f.length;for(let S=0;S<d;S++)g+=f[S];const A=g/d;this.onChangeFunction(a,A)},this.emitInterval)}}class G1{constructor(){this.resumePromise=null,this.context=new AudioContext}async getContext(){return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{throw this.resumePromise=null,n})),await this.resumePromise),this.context}}const ju={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},W1=0;class K1{constructor(n){var r;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.managedAudioContext=new G1,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new j1({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices(),this.processVADConfiguration(((r=this.context.options.configuration)==null?void 0:r.noiseReductionOptions)||{}),this.setupVADInstance()}setVADConfiguration(n){if(!this.MicVAD)throw new Error("VAD module is not provided in the initial configuration");const r=Object.keys(n);for(const a of r)this.noiseReduction[a]=n[a];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,r;const a=(r=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:r.vadModule;a&&a.MicVAD?(this.MicVAD=a.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(n){this.noiseReduction={mode:n.mode||"disabled",checkEveryMs:n.checkEveryMs||500,noiseCheckInterval:n.noiseCheckInterval||2e3,noiseThreshold:n.noiseThreshold||.004,vadConfig:n.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}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(n=>!n.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return Tf()?{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(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(ju.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(ju.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),c=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(c),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}),a.getTracks().forEach(e=>e.stop())}catch(a){console.error(a)}}async cleanupConferenceNodes(n){const r=this.conferenceNodes[n];if(!r)return;let a=0;r.sources.forEach((f,g)=>{try{f.disconnect(),a++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting source ${g}:`,d)}});let c=0;r.destinations.forEach((f,g)=>{try{f.disconnect(),c++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${g}:`,d)}});let e=0;r.gains.forEach((f,g)=>{try{f.disconnect(),e++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${g}:`,d)}}),delete this.conferenceNodes[n]}setCallTime(n){const r={...n};delete r.callId,this.callTime={...this.callTime,[n.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const r={...this.callTime};delete r[n],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,r){this.timeIntervals={...this.timeIntervals,[n]:r}}removeTimeInterval(n){const r={...this.timeIntervals};r[n]&&(clearInterval(r[n]),delete r[n],this.timeIntervals={...r})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,r){this.context.emit("changeCallVolume",{callId:n,volume:r})}getNoiseReductionMode(){return this.noiseReduction.mode}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9*#]+$/g.test(r))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[n].sendDTMF(r)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const r=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:a}){const c=this.extendedCalls[n];if(!c)return;c._automaticHold=a??!1;const e=new Promise((f,g)=>{const d=setTimeout(()=>{g(new Error("Hold operation timeout"))},5e3),A=()=>{clearTimeout(d),c.putOnHoldTimestamp=r?Date.now():void 0,f()},S=R=>{clearTimeout(d),g(R)};try{r?(this.stopSessionVad(c._id),c.hold({},A)):c.unhold({},A)}catch(R){S(R)}});try{await e,this.updateCall(c);const f=Object.values(this.extendedCalls).filter(g=>g.roomId===c.roomId&&(r?n!==g._id:!0));f.length>1&&await this.doConference(f)}catch(f){throw console.error("Hold operation failed:",f),f}}holdCall(n,r=!1){return this.processHold({callId:n,automatic:r,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===W1).forEach(n=>this.terminateCall(n._id))}answerCall(n){const r=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",a=>{this.triggerAddStream(a,r)})}async moveCall(n,r){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:r}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=yf(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const r={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...r}},this.context.emit("updateRoom",{room:r,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const r=/answer-after=0/,a=n.request.getHeader("Call-Info");return a&&r.test(a)}addCall(n,r=!0){this.activeCalls={...this.activeCalls,[n._id]:yf(n)},this.extendedCalls[n._id]=n,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const r={...this.callStatus[n.callId]};n.isMoving!==void 0&&(r.isMoving=n.isMoving),n.isTransferring!==void 0&&(r.isTransferring=n.isTransferring),n.isMerging!==void 0&&(r.isMerging=n.isMerging),n.isTransferred!==void 0&&(r.isTransferred=n.isTransferred),this.callStatus={...this.callStatus,[n.callId]:{...r}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const r={...this.callStatus};delete r[n],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}async setupActiveStream(){const n=await Dd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n)}async getActiveStream(){const n=await Dd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:a})=>a===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async a=>{await this.setupActiveStream();const c=this.activeStream;a.connection.getSenders()[0].replaceTrack(c.getTracks()[0]),this.updateCall(a)}):await this.doConference(r)}async setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:c})=>c===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const a=r.filter(c=>c.roomId===this.currentActiveRoomId);a.length===1?r.forEach(c=>{var e;(e=c.audioTag)==null||e.setSinkId(n),this.updateCall(c)}):await this.doConference(a)}removeRoom(n){const r={...this.activeRooms},a={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}startNoiseMonitor({sessionId:n,stream:r,onNoiseDetected:a,onNoiseStop:c}){const e=new AudioContext,f=e.createMediaStreamSource(r.clone()),g=e.createAnalyser();g.fftSize=1024;const d=new Float32Array(g.fftSize);f.connect(g);const A=[];this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),this.vadIntervals[n]=null),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),this.vadMrsIntervals[n]=null),this.vadMrsIntervals[n]=setInterval(()=>{g.getFloatTimeDomainData(d);const S=KA(d);A.push(S);const R=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);A.length>R&&A.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[n]=setInterval(()=>{if(A.length===0)return;const S=A.reduce((H,W)=>H+W,0)/A.length,R=this.vadSessionsState[n],N=S>this.noiseReduction.noiseThreshold;R.isSpeaking||(N&&R.currentMode==="clean"?(R.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!0}),a()):!N&&R.currentMode==="noisy"&&(R.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!1}),c()))},this.noiseReduction.noiseCheckInterval)}async processVAD(n,r){const a=r.clone();this.stopSessionVad(n._id),this.vadSessionsState[n._id]={currentMode:"clean",isSpeaking:!1};const c=await this.managedAudioContext.getContext(),e=await YA(a,c,150);let f=!1;const g=await this.MicVAD.new({getStream:()=>new Promise(d=>d(a)),...V1,...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:()=>{if(!f){if(f=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){n.connection.getSenders()[0]&&n.connection.getSenders()[0].replaceTrack(e.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:n._id,stream:a,onNoiseDetected:async()=>{var d;console.log("Replace track with Vad Controlled"),await((d=n.connection.getSenders()[0])==null?void 0:d.replaceTrack(e.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const d=n.connection.getSenders()[0];d&&d.track&&d.transport&&d.transport.state!=="closed"&&d.transport.state!=="failed"&&(console.log("Replace track with Original"),await d.replaceTrack(a.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var d;console.log("🎤 Speech started"),e.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((d=n.connection.getSenders()[0])==null||d.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!0},onSpeechEnd:()=>{var d;console.log("🛑 Speech end"),e.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((d=n.connection.getSenders()[0])==null||d.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!1}});this.vadSessions[n._id]&&(this.vadSessions[n._id].pause(),delete this.vadSessions[n._id]),this.vadSessions[n._id]=g,g.start()}stopSessionVad(n){this.vadSessions[n]&&(this.vadSessions[n].pause(),delete this.vadSessions[n]),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]),this.vadSessionsState[n]&&delete this.vadSessionsState[n]}async roomReconfigure(n){var r;if(n===void 0)return;const a=Object.values(this.extendedCalls).filter(e=>e.roomId===n),c=this.currentActiveRoomId===n;if(a.forEach((e,f)=>{if(e.audioTag){e.connection.getReceivers().forEach(d=>{d.track.enabled=!e.localMuted}),c&&this.muteReconfigure(e);const g=!c;e.audioTag.muted=g,this.updateCall(e)}}),a.length===0){this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n),this.deleteRoomIfEmpty(n);return}if(a.length===1&&!c){const e=a[0];e.isOnHold().local||await this.holdCall(e._id,!0),this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}if(a.length===1&&c){const e=a[0];e.isOnHold().local&&e._automaticHold&&await this.unholdCall(e._id);const f=(((r=e.connection)==null?void 0:r.getSenders())||[])[0];if(e.connection&&f)try{await this.setupActiveStream();const g=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(a[0],g);const d=g.getTracks();await f.replaceTrack(d[0]),this.muteReconfigure(e)}catch(g){console.error(g)}this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}a.length>1&&await this.doConference(a)}async doConference(n){if(n.length===0)return;const r=n[0].roomId,a=this.currentActiveRoomId===r;if(n.find(g=>g.roomId!==r))return;const c=await this.managedAudioContext.getContext();if(c.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${c.state}`);return}await this.cleanupConferenceNodes(r),this.conferenceNodes[r]={sources:new Map,destinations:new Map,gains:new Map};const e=this.conferenceNodes[r],f=new Map;n.forEach((g,d)=>{g&&g.connection&&g.connection.getReceivers().forEach((A,S)=>{var R,N,H;A.track.enabled=!g.localMuted;const W=(R=A.track)==null?void 0:R.id;(N=A.track)==null||N.readyState,(H=A.track)==null||H.kind;const G=`${g._id}-${W}`;A.track&&A.track.readyState==="live"&&f.set(G,A.track)})}),await this.setupActiveStream(),await XA.forEach(n,async(g,d)=>{if(!g||!g.connection)return;const A=c.createMediaStreamDestination();e.destinations.set(g._id,A);let S=0;if(f.forEach((H,W)=>{if(!W.startsWith(g._id))try{const G=c.createMediaStreamSource(new MediaStream([H])),K=c.createGain(),ae=`${g._id}-${W}`;G.connect(K),K.connect(A),e.sources.set(ae,G),e.gains.set(ae,K),S++}catch(G){console.error(G)}}),a&&this.activeStreamValue)try{const H=this.activeStream,W=c.createMediaStreamSource(H),G=c.createGain(),K=`${g._id}-local`;W.connect(G),G.connect(A),e.sources.set(K,W),e.gains.set(K,G)}catch(H){console.error(H)}else a&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${g._id}`);const R=g.connection.getSenders()[0],N=A.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(g,A.stream),R&&N[0])try{await R.replaceTrack(N[0]),this.muteReconfigure(g)}catch(H){console.error(H)}})}processCallerMute(n,r){const a=this.extendedCalls[n];a&&a.connection.getReceivers().length&&(a.localMuted=r,a.connection.getReceivers().forEach(c=>{c.track.enabled=!r}),this.updateCall(a))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status===4?r.terminate({status_code:603,reason_phrase:"Decline"}):r._status!==8&&r.terminate()}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[n];if(!a._is_confirmed&&!a._is_canceled){const c=`sip:${r}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${c}`]});return}this.updateCallStatus({callId:n,isTransferring:!0,isTransferred:!1}),a.refer(`sip:${r}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(a)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(e=>e.roomId===n);if(r.length!==2)return;const a=r[0],c=r[1];!a||!c||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:c._id,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a))}mergeCallByIds(n,r){const a=Object.values(this.extendedCalls).find(e=>e._id===n),c=Object.values(this.extendedCalls).find(e=>e._id===r);if(!a||!c)throw new Error("Call ID is not provided");this.updateCallStatus({callId:n,isMerging:!0}),this.updateCallStatus({callId:r,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a)}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}setCallWaiting(n){this.isCallWaitingEnabled=n,this.context.emit("changeIsCallWaiting",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const a=setInterval(()=>{const c={...this.callTime[n]},e=WA(c);this.setCallTime({callId:n,...e})},1e3);this.setTimeInterval(n,a)}async setActiveRoom(n){const r=this.currentActiveRoomId;n!==r&&(this.currentActiveRoomId=n,await this.roomReconfigure(r),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var r,a;const c=n.session;if(this.getActiveCalls[c.id]!==void 0)return;const e=this.getNewRoomId(),f={started:new Date,incomingInProgress:!1,roomId:e};if(c.direction==="incoming")this.context.logger.log("New incoming call from",(a=(r=c._remote_identity)==null?void 0:r._uri)==null?void 0:a._user),f.incomingInProgress=!0,this.context.subscribe(Br.CALL_CONFIRMED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.startCallTimer(c.id))}),this.context.subscribe(Br.CALL_FAILED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.deleteRoomIfEmpty(e))});else if(c.direction==="outgoing"){const S=R=>{R.response&&R.response.status_code===JA.SESSION_PROGRESS&&(this.startCallTimer(c.id),c.off("progress",S))};c.on("progress",S),c.once("confirmed",()=>{this.startCallTimer(c.id)})}const g=c,d=this.hasAutoAnswerHeaders(n),A=g.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);g.roomId=e,g.localMuted=!1,g.autoAnswer=A,A?this.addCall(g,!1):this.addCall(g),this.addCallStatus(c.id),this.addRoom(f),A&&this.answerCall(g._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const a={...this.extendedCalls};delete a[n],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];if(!r)return;this.stopVUMeter("origin"),this.stopVUMeter(n._id);const a=r.roomId;this.removeCall(n._id),this.roomReconfigure(a).then(()=>{}).catch(c=>{console.error("Error reconfiguring room after call removal:",c)})}shouldTerminateNewSession(n){if(n.session.direction==="outgoing")return!1;const r=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||r}async newRTCSessionCallback(n){const r=n.session;if(this.shouldTerminateNewSession(n)){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Br.NEW_CALL,session:r,event:n}),r.on("ended",a=>{var c,e,f;this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(e=(c=r._remote_identity)==null?void 0:c._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Br.CALL_ENDED,session:r,event:a}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id);const g=this.getActiveCalls[r.id];g&&this.activeCallListRemove(g),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(f=this.initialStreamValue)==null||f.getTracks().forEach(d=>d.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("progress",a=>{var c,e;this.context.logger.log("Session in progress for",(e=(c=r._remote_identity)==null?void 0:c._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Br.CALL_PROGRESS,session:r,event:a})}),r.on("failed",a=>{var c,e,f;this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(e=(c=r._remote_identity)==null?void 0:c._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Br.CALL_FAILED,session:r,event:a}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const g=this.getActiveCalls[r.id];g&&this.activeCallListRemove(g),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(f=this.initialStreamValue)==null||f.getTracks().forEach(d=>d.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("confirmed",a=>{var c,e;this.context.logger.log("Session confirmed for",(e=(c=r._remote_identity)==null?void 0:c._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Br.CALL_CONFIRMED,session:r,event:a}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(n),r.direction==="outgoing"){const a=this.getActiveCalls[r.id].roomId;await this.setActiveRoom(a)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=n,this.updateCall(r))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(ju.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(ju.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const r={...n};delete r.callId,this.callMetrics={...this.callMetrics,[n.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const r={...this.callMetrics};delete r[n],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const r=new z1(this.metricConfig),a=r.createProbe(n.connection,{cid:n._id}),c=[];let e;a.onreport=f=>{Object.entries(f.audio).forEach(([A,S])=>{S.direction==="inbound"&&!c.includes(A)&&(c.push(A),e=A)});const g=f.audio[e];if(!g)return;const d=F1(g,B1);d.callId=n._id,this.setCallMetrics(d)},this.context.subscribe(Br.CALL_ENDED,f=>{f._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}async setupVUMeter(n,r){await this.VUMeter.start(await this.managedAudioContext.getContext(),n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){try{const n=Date.now(),r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((a,c)=>{a.stop()}),this.initialStreamValue=null),this.initialStreamValue=r}catch(n){throw n}}async triggerAddStream(n,r){const a=this.muteWhenJoin||this.isMuted;this.setIsMuted(a),this.initialStreamValue||await this.setupStream();const c=await this.managedAudioContext.getContext(),e=await Dd(c,this.initialStreamValue,this.microphoneInputLevel*2),f=this.isMuted||this.muteWhenJoin;e.getTracks().forEach(A=>{A.enabled=!f}),await this.setActiveStream(e),await r.connection.getSenders()[0].replaceTrack(e.getTracks()[0]);const g=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(A=>A.audioTag&&A.audioTag.id===r._id)&&kA(g,r,this.selectedOutputDevice,this.speakerVolume);const d=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!d),await this.setupVUMeter(g,r._id),this.getCallQuality(r),this.updateCall(r),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r,e)}initCall(n,r,a=!1){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const c=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=c.id,r&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:c.id,roomId:this.currentActiveRoomId}),a)){const e=Object.values(this.extendedCalls).filter(f=>f.roomId===this.currentActiveRoomId&&f._id!==c.id);for(const f of e)this.holdCall(f._id,!0)}c.connection.addEventListener("track",e=>{this.triggerAddStream(e,c)})}async processRoomChange({callId:n,roomId:r}){const a=this.extendedCalls[n];if(!a)return;const c=a.roomId;a.roomId=r,this.updateCall(a),await this.roomReconfigure(c),await this.roomReconfigure(r)}}class Y1{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n,r){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,r,this.sipOptions)}stop(n={}){this.context.terminateJanusSessions(n)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(n){this.context.changeMediaConstraints(n)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class X1{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const r=this.extendedMessages[n];this.updateMSRPSession(r)}updateMSRPSession(n){this.activeMessages[n._id]=vf(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:vf(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const a=this.msrpHistory[r.id]||[];a.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...a]},this.context.emit("newMSRPMessage",{message:n,session:r})}messageTerminate(n){const r=this.extendedMessages[n];r._status!==8&&r.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const r=n;this.addMMSRPSession(r)}triggerMSRPListener({listenerType:n,session:r,event:a}){const c=this.context.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const a={...this.extendedMessages};delete a[n],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){n.session._id||(n.session._id=n.request.call_id+n.request.from._parameters.tag);const r=n.session;r.on("ended",a=>{this.triggerMSRPListener({listenerType:Br.CALL_ENDED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("failed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_FAILED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_CONFIRMED,session:r,event:a}),this.updateMSRPSession(r)}),r.on("newMessage",a=>{this.addMSRPMessage(a,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,a){if(n.length===0)return console.error("Target must be a valid string");const c=this.context.startMSRP(n,a);c.on("active",()=>{this.addMessageSession(c),c.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const a=this.extendedMessages[n];if(!a)throw new Error(`MSRP session with id ${n} doesn't exist!`);a.sendMSRP(r)}}const Gu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Mf{constructor(n){this.opensips=null,this.session=null,this.name=null,this.name=n}setOpensips(n){this.opensips=n}setSession(n){this.session=n}kill(){this.opensips.kill(this.name)}}class J1 extends Mf{constructor(n,r){super(n),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=r}connect(n={}){this.opaqueId=this.session.generateOpaqueId();const r=kt.cloneArray(n.extraHeaders),a={from_tag:this.session._from_tag};n.fromUserName&&(a.from_uri=new ba("sip",n.fromUserName,this.session._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(a.from_display_name=n.fromDisplayName),r.push(`Contact: ${this.session._contact}`),r.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&r.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new On.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,r),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 n;this._connection.onicecandidate=r=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||r.candidate&&(this._candidates.push(r.candidate),clearTimeout(n),n=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(n){n.forEach(r=>{this._connection.addTrack(r)})}async _sendInitialRequest(){const n=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const r={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(r),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},c=JSON.stringify(a);this._request.body=c,n.send()}_receiveInviteResponse(n){if(this._publisherSubscribeSent||!n.body)return;const r=JSON.parse(n.body);this.handleId=r.data.id;const a={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},c=[this.session.getPTypeHeader(ir.PUBLISHER)];this.session.sendRequest(oe.SUBSCRIBE,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{var f,g,d,A;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((g=(f=S.plugindata)==null?void 0:f.data)==null?void 0:g.videoroom)==="joined"&&this.session.myFeedList.push(S.plugindata.data.id),(A=(d=S.plugindata)==null?void 0:d.data)!=null&&A.publishers&&this.session.receivePublishers(S)}catch(S){console.error(S)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(n){const r=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handleId,session_id:this.session.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...n},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...r]},c=["Content-Type: application/json",this.session.getPTypeHeader(ir.ICE)];this.session.sendRequest(oe.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{this._configureSent=!0;const f=e.data.split(`\r
|
|
159
|
-
`),g=f[f.length-1],d=JSON.parse(g);await this._connection.setRemoteDescription(d.jsep),this._candidates=[]}}})}_sendDetach(){const n={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},r=[this.session.getPTypeHeader(ir.DETACH)];this.session.sendRequest(oe.INFO,{extraHeaders:r,body:JSON.stringify(n)}),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 n=this._connection.getSenders();n.forEach(r=>{const a=r.track;a&&a.stop()}),n.forEach(r=>{this._connection.removeTrack(r)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Q1 extends Mf{constructor(n,r,a={}){super(n),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=r}start(n){return n}stop(){throw new Error("stop method is not implemented")}async process(n){if(this.immediate){const r=await this.start(n);return this.running=!0,r}return n}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 Z1 extends CA{constructor(n,r){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const a={...n.configuration,sockets:n.socketInterfaces.map(c=>new GA.WebSocketInterface(c))};super(a),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=[],n.pnExtraHeaders&&Object.keys(n.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(n.pnExtraHeaders),this.options=n,this.modules=n.modules,n.configuration.reconnectionAttemptsLimit&&(this.reconnectionAttemptsLimit=n.configuration.reconnectionAttemptsLimit),r&&DA(r)&&(this.logger=r)}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(Gu.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(n,r){return super.on(n,r)}off(n,r){return super.off(n,r)}emit(n,r){return super.emit(n,r)}get sipDomain(){return this.options.sipDomain}use(n){if(this.newStreamPlugins.find(r=>r.name===n.name)||this.processStreamPlugins.find(r=>r.name===n.name))throw new Error(`Plugin with name ${n.name} already exists`);if(n instanceof J1)n.setOpensips(this),this.newStreamPlugins.push(n);else if(n instanceof Q1)n.setOpensips(this),this.processStreamPlugins.push(n);else throw new Error("Wrong plugin instance")}getPlugin(n){return this.newStreamPlugins.find(r=>r.name===n)||this.processStreamPlugins.find(r=>r.name===n)}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(Gu.AUDIO)&&(this.audio=new K1(this)),this.modules.includes(Gu.MSRP)&&(this.msrp=new X1(this)),this.modules.includes(Gu.VIDEO)&&(this.video=new Y1(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(n,r){const a=!this.listenersList[n]||!this.listenersList[n].length?[r]:[...this.listenersList[n],r];this.listenersList={...this.listenersList,[n]:a}}removeIListener(n){const r={...this.listenersList};delete r[n],this.listenersList={...r}}triggerListener({listenerType:n,session:r,event:a}){const c=this.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}setConnected(n){this.connected=n,this.emit("connection",n)}setReconnecting(n){this.isReconnecting=n,this.emit("reconnecting",n)}}var Gn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function eI(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var Hd={},Tl={};Object.defineProperty(Tl,"__esModule",{value:!0}),Tl.baseAssetPath=void 0;const Uf=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let Pf="/";Uf&&(Pf=Uf.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),Tl.baseAssetPath=Pf;var io={};Object.defineProperty(io,"__esModule",{value:!0}),io.defaultModelFetcher=void 0;const tI=o=>fetch(o).then(n=>n.arrayBuffer());io.defaultModelFetcher=tI;var us={},ao={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.log=o.LOG_PREFIX=void 0,o.LOG_PREFIX="[VAD]";const n=["error","debug","warn"];function r(c){return(...e)=>{console[c](o.LOG_PREFIX,...e)}}const a=n.reduce((c,e)=>(c[e]=r(e),c),{});o.log=a})(ao);var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.Message=void 0;var Lf;(function(o){o.AudioFrame="AUDIO_FRAME",o.SpeechStart="SPEECH_START",o.VADMisfire="VAD_MISFIRE",o.SpeechEnd="SPEECH_END",o.SpeechStop="SPEECH_STOP",o.SpeechRealStart="SPEECH_REAL_START",o.FrameProcessed="FRAME_PROCESSED"})(Lf||(Ea.Message=Lf={})),Object.defineProperty(us,"__esModule",{value:!0}),us.FrameProcessor=us.validateOptions=us.defaultFrameProcessorOptions=void 0;const bl=ao,Ca=Ea;us.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function nI(o){(o.positiveSpeechThreshold<0||o.positiveSpeechThreshold>1)&&bl.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(o.negativeSpeechThreshold<0||o.negativeSpeechThreshold>o.positiveSpeechThreshold)&&bl.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),o.preSpeechPadMs<0&&bl.log.error("preSpeechPadMs should be positive"),o.redemptionMs<0&&bl.log.error("redemptionMs should be positive"),o.minSpeechMs<0&&bl.log.error("minSpeechMs should be positive")}us.validateOptions=nI;const qf=o=>{const n=o.reduce((a,c)=>(a.push(a.at(-1)+c.length),a),[0]),r=new Float32Array(n.at(-1));return o.forEach((a,c)=>{const e=n[c];r.set(a,e)}),r};class rI{constructor(n,r,a,c){this.modelProcessFunc=n,this.modelResetFunc=r,this.options=a,this.msPerFrame=c,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=e=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(e):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=e=>{const f=this.audioBuffer;this.audioBuffer=[];const g=this.speaking;if(this.reset(),g)if(f.reduce((A,S)=>S.isSpeech?A+1:A,0)>=this.minSpeechFrames){const A=qf(f.map(S=>S.frame));e({msg:Ca.Message.SpeechEnd,audio:A})}else e({msg:Ca.Message.VADMisfire});return{}},this.process=async(e,f)=>{if(!this.active)return;const g=await this.modelProcessFunc(e),d=g.isSpeech>=this.options.positiveSpeechThreshold;if(f({probs:g,msg:Ca.Message.FrameProcessed,frame:e}),this.audioBuffer.push({frame:e,isSpeech:d}),d&&(this.speechFrameCount++,this.redemptionCounter=0),d&&!this.speaking&&(this.speaking=!0,f({msg:Ca.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,f({msg:Ca.Message.SpeechRealStart})),g.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const A=this.audioBuffer;if(this.audioBuffer=[],A.reduce((R,N)=>N.isSpeech?R+1:R,0)>=this.minSpeechFrames){const R=qf(A.map(N=>N.frame));f({msg:Ca.Message.SpeechEnd,audio:R})}else f({msg:Ca.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[],this.redemptionFrames=Math.floor(a.redemptionMs/this.msPerFrame),this.preSpeechPadFrames=Math.floor(a.preSpeechPadMs/this.msPerFrame),this.minSpeechFrames=Math.floor(a.minSpeechMs/this.msPerFrame),this.reset()}}us.FrameProcessor=rI;var Hf={};function oo(o){throw new Error('Could not dynamically require "'+o+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var zf={exports:{}};/*!
|
|
156
|
+
`),this._newMSRPSession("local",this._request),this._from_tag||(this._from_tag=this._request.from._parameters.tag),this._id=this._request.call_id+this._from_tag,new sl(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:c=>{this.onTransportError(),console.log(c)},onAuthenticated:c=>{this._request=c},onReceiveResponse:c=>{this._receiveInviteResponse(c),c.status_code===200&&(c.parseSDP(!0),this._status=dt.STATUS_CONFIRMED,this.target_addr=c.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=dt.STATUS_INVITE_SENT}terminate(n={}){const r=n.cause||oe.causes.BYE,a=kt.cloneArray(n.extraHeaders),c=n.body;let e,_=n.status_code,g=n.reason_phrase;if(this._status===dt.STATUS_TERMINATED)throw new di.InvalidStateError(this._status);switch(this.status="terminated",this._status){case dt.STATUS_NULL:case dt.STATUS_INVITE_SENT:case dt.STATUS_1XX_RECEIVED:if(_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);_&&(g=g||oe.REASON_PHRASE[_]||"",e=`SIP ;cause=${_} ;text="${g}"`),this._status===dt.STATUS_NULL||this._status===dt.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===dt.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=dt.STATUS_CANCELED,this._failed("local",null,oe.causes.CANCELED);break;case dt.STATUS_WAITING_FOR_ANSWER:case dt.STATUS_ANSWERED:if(_=_||480,_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);this._request.reply(_,g,a,c),this._failed("local",null,oe.causes.REJECTED);break;case dt.STATUS_WAITING_FOR_ACK:case dt.STATUS_CONFIRMED:if(g=n.reason_phrase||oe.REASON_PHRASE[_]||"",_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);if(_&&a.push(`Reason: SIP ;cause=${_}; text="${g}"`),this._status===dt.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Ir.C.STATUS_TERMINATED){const d=this._dialog;this.receiveRequest=({method:A})=>{A===oe.ACK&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Ir.C.STATUS_TERMINATED&&(this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),d.terminate())}),this._ended("local",null,r),this._dialog=d,this._ua.newDialog(d)}else this.sendRequest(oe.BYE,{extraHeaders:a,body:c}),this._ended("local",null,r)}}sendRequest(n,r){return this._dialog.sendRequest(n,r)}authenticate(n){this.status="auth";let r=new ro("");r.method="AUTH",r.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),r.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),n&&r.addHeader("Authorization",n.toString());let a=r.toString(),c=[];for(var e=0;e<a.length;e++)c.push(a.charCodeAt(e).toString(16));this._connection.send(r.toString())}onmessage(n){const r=new ro(n.data);if(this.status==="auth"&&r.code===401){const a=this.parseAuth(r.getHeader("WWW-Authenticate")),c=new $E(this.credentials);c.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},a,kt.createRandomToken(12)),this.authenticate(c)}this.status==="auth"&&r.code===200&&this._direction==="outgoing"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.inviteParty(r)):this.status==="auth"&&r.code===200&&this._direction==="incoming"?(this.my_addr.push(r.getHeader("To-Path")),this.my_addr.push(r.getHeader("Use-Path")),this.status="active",this.acceptParty(r),this.emit("confirmed")):r.method==="SEND"&&(this._sendOk(r),this._sendReport(r),r.direction="incoming",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)),r.code===480&&this._close()}onclose(){console.log("close")}onopen(){const n=new RTCPeerConnection({iceServers:[]});n.createDataChannel(""),n.createOffer().then(n.setLocalDescription.bind(n)),n.onicecandidate=r=>{if(!r||!r.candidate||!r.candidate.candidate)return;const a=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,c=r.candidate.candidate.match(a);this.my_ip=c&&c[1],n.onicecandidate=()=>{},this.authenticate(null)}}onerror(n){console.log(n)}_receiveInviteResponse(n){if(console.log("resp0000000000000",n),this._dialog&&n.status_code>=200&&n.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.sendRequest(oe.ACK);return}else{const r=new Ru(this,n,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(oe.ACK),this.sendRequest(oe.BYE);return}if(this._is_canceled){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==dt.STATUS_INVITE_SENT&&this._status!==dt.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(n.status_code):this._status=dt.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){console.log("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=dt.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>this._progress("remote",n)).catch(c=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("maybe here???"),this._status=dt.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,oe.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",n,oe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r),new RTCSessionDescription({type:"answer",sdp:r.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(n,500,a.toString()),console.log("failed 4"),this._failed("local",n,oe.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(oe.ACK),this._confirmed("local",null)});break}default:{const r=kt.sipErrorCause(n.status_code);console.log("failed 5"),this._failed("remote",n,r)}}}sendMSRP(n){const r=new ro("");let a="";this.my_addr[1]&&(a=this.my_addr[1]),this.target_addr[1]&&(a+=" "+this.target_addr[1]),this.target_addr[0]&&(a+=" "+this.target_addr[0]),r.method="SEND",r.addHeader("To-Path",a),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",kt.createRandomToken(10)),r.addHeader("Byte-Range","1-25/25"),r.addHeader("Content-Type","text/plain"),r.addHeader("Success-Report","yes"),r.addHeader("Failure-Report","yes"),r.body=n;let c=r.toString();console.log(c);let e=[];for(var _=0;_<c.length;_++)e.push(c.charCodeAt(_).toString(16));console.log(e),this._connection.send(r.toString()),r.direction="outgoing",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(n){let r=n.ident,a=n.getHeader("Message-ID"),c=new ro("");c.method="200 OK",c.addHeader("To-Path",`${this.my_addr[1]}`),c.addHeader("From-Path",`${this.my_addr[0]}`),c.addHeader("Message-ID",a),c.ident=r;let e=c.toString();console.log(e);let _=[];for(var g=0;g<e.length;g++)_.push(e.charCodeAt(g).toString(16));console.log(_),this._connection.send(c.toString())}_sendReport(n){let r=n.ident,a=n.getHeader("Message-ID"),c=new ro("");c.method="REPORT",c.addHeader("To-Path",`${n.getHeader("From-Path")}`),c.addHeader("From-Path",`${this.my_addr[0]}`),c.addHeader("Message-ID",a),c.addHeader("Byte-Range","1-25/25"),c.addHeader("Status","000 200 OK"),c.ident=r;let e=c.toString();console.log(e);let _=[];for(var g=0;g<e.length;g++)_.push(e.charCodeAt(g).toString(16));console.log(_),this._connection.send(c.toString())}parseAuth(n){const r={},a=n.replace("Digest","").split(",");for(const c of a){const e=c.trim().split("=");r[e[0]]=e[1].match('^"(.+)"$')[1]}return r}init_incoming(n,r){let a;const c=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&c!=="application/sdp"){n.reply(415);return}if(this._status=dt.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(a=n.getHeader("expires")*1e3),n.to_tag=kt.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=dt.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),console.log("failed 6"),this._failed("local",null,oe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),a&&(this._timers.expiresTimer=setTimeout(()=>{this._status===dt.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),console.log("failed 7"),this._failed("system",null,oe.causes.EXPIRES))},a)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,r&&r(this),n.parseSDP(!0),this.target_addr=n.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",n),this._status!==dt.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(n,r,a){this.emit("_failed",{originator:n,message:r||null,cause:a}),this._close(),this.emit("failed",{originator:n,message:r||null,cause:a})}_close(){if(console.log("CLOSE SESSION"),this._status!==dt.STATUS_TERMINATED){if(this._status=dt.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){console.log("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyMSRPSession(this)}}_createDialog(n,r,a){const c=r==="UAS"?n.to_tag:n.from_tag,e=r==="UAS"?n.from_tag:n.to_tag,_=n.call_id+c+e;let g=this._earlyDialogs[_];if(a)return g?!0:(g=new Ru(this,n,r,Ru.C.STATUS_EARLY),g.error?(console.log("failed 8"),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[_]=g,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,g)return g.update(n,r),this._dialog=g,delete this._earlyDialogs[_],!0;const d=new Ru(this,n,r);return d.error?(console.log("failed 9"),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._dialog=d,!0)}}_newMSRPSession(n,r){this._ua.newMSRPSession(this,{originator:n,session:this,request:r})}_progress(n,r){this.emit("progress",{originator:n,response:r||null})}isEnded(){switch(this._status){case dt.STATUS_CANCELED:case dt.STATUS_TERMINATED:return!0;default:return!1}}_accepted(n,r){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:n,response:r||null})}_confirmed(n,r){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:r||null})}_ended(n,r,a){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:n,message:r||null,cause:a})}_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 n=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(r){console.error("Failed to send keep-alive:",r)}this._sessionTimers.running=!1,this._runKeepAliveTimer()},n*1e3*.5)}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let r;n.session_expires&&n.session_expires>=oe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,r=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runKeepAliveTimer()}receiveRequest(n){if(console.log("receiveRequest()"),n.method===oe.CANCEL)(this._status===dt.STATUS_WAITING_FOR_ANSWER||this._status===dt.STATUS_ANSWERED)&&(this._status=dt.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",n,oe.causes.CANCELED));else switch(n.method){case oe.ACK:if(this._status!==dt.STATUS_WAITING_FOR_ACK)return;if(this._status=dt.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:oe.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",r);const a=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(a)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(c=>{this.terminate({cause:oe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',c),this.emit("peerconnection:setremotedescriptionfailed",c)})}else this._is_confirmed||this._confirmed("remote",n);break;case oe.BYE:this._status===dt.STATUS_CONFIRMED||this._status===dt.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,oe.causes.BYE)):this._status===dt.STATUS_INVITE_RECEIVED||this._status===dt.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,oe.causes.BYE)):n.reply(403,"Wrong Status");break;case oe.INVITE:this._status===dt.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case oe.INFO:this._status===dt.STATUS_1XX_RECEIVED||this._status===dt.STATUS_WAITING_FOR_ANSWER||this._status===dt.STATUS_ANSWERED||this._status===dt.STATUS_WAITING_FOR_ACK||this._status===dt.STATUS_CONFIRMED?(n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new pd(this).init_incoming(n):n.reply(415):n.reply(403,"Wrong Status");break;case oe.UPDATE:this._status===dt.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case oe.REFER:this._status===dt.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case oe.NOTIFY:this._status===dt.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.CONNECTION_ERROR,cause:oe.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:oe.causes.REQUEST_TIMEOUT,cause:oe.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==dt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:oe.causes.DIALOG_ERROR,cause:oe.causes.DIALOG_ERROR})}}var yA=Hr();const kd=Qt(yA),Hu=new wu("Parser"),vA=(o,n)=>{let r,a,c=o.indexOf(`\r
|
|
157
|
+
`);if(c===-1){Hu.warn("parseMessage() | no CRLF found, not a SIP message");return}const e=o.substring(0,c);let _=kd.parse(e,"Request_Response");if(_===-1){Hu.warn(`parseMessage() | error parsing first line of SIP message: "${e}"`);return}else _.status_code?(r=new Za.IncomingResponse,r.status_code=_.status_code,r.reason_phrase=_.reason_phrase):(r=new Za.IncomingRequest(n),r.method=_.method,r.ruri=_.uri);r.data=o;let g=c+2;for(;;){if(c=TA(o,g),c===-2){a=g+2;break}else if(c===-1){Hu.warn("parseMessage() | malformed message");return}if(_=bA(r,o,g,c),_!==!0){Hu.warn("parseMessage() |",_.error);return}g=c+2}if(r.hasHeader("content-length")){const d=r.getHeader("content-length");r.body=o.substr(a,d)}else r.body=o.substring(a);return r};function TA(o,n){let r=n,a=0,c=0;if(o.substring(r,r+2).match(/(^\r\n)/))return-2;for(;a===0;){if(c=o.indexOf(`\r
|
|
158
|
+
`,r),c===-1)return c;!o.substring(c+2,c+4).match(/(^\r\n)/)&&o.charAt(c+2).match(/(^\s+)/)?r=c+2:a=c}return a}function bA(o,n,r,a){let c;const e=n.indexOf(":",r),_=n.substring(r,e).trim(),g=n.substring(e+1,a).trim();switch(_.toLowerCase()){case"via":case"v":o.addHeader("via",g),o.getHeaders("via").length===1?(c=o.parseHeader("Via"),c&&(o.via=c,o.via_branch=c.branch)):c=0;break;case"from":case"f":o.setHeader("from",g),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",g),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=kd.parse(g,"Record_Route"),c===-1)c=void 0;else for(const d of c)o.addHeader("record-route",g.substring(d.possition,d.offset)),o.headers["Record-Route"][o.getHeaders("record-route").length-1].parsed=d.parsed;break;case"call-id":case"i":o.setHeader("call-id",g),c=o.parseHeader("call-id"),c&&(o.call_id=g);break;case"contact":case"m":if(c=kd.parse(g,"Contact"),c===-1)c=void 0;else for(const d of c)o.addHeader("contact",g.substring(d.possition,d.offset)),o.headers.Contact[o.getHeaders("contact").length-1].parsed=d.parsed;break;case"content-length":case"l":o.setHeader("content-length",g),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",g),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",g),c=o.parseHeader("cseq"),c&&(o.cseq=c.value),o instanceof Za.IncomingResponse&&(o.method=c.method);break;case"max-forwards":o.setHeader("max-forwards",g),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",g),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",g),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",g),c=o.parseHeader("session-expires"),c&&(o.session_expires=c.expires,o.session_expires_refresher=c.refresher);break;case"refer-to":case"r":o.setHeader("refer-to",g),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",g),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",g),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(_,g),c=0}return c===void 0?{error:`error parsing header "${_}"`}:!0}const wA={parseMessage:vA},_l=new wu("Registrator"),zu=10;class SA{constructor(n,r){this._reg_id=1,this._ua=n,this._transport=r,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=qs.createRandomToken(22),this._cseq=0,this._to_uri=n.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const a=this._contact.indexOf(">");if(a!==-1){const c=this._contact.slice(0,a)+this._contact.slice(a+1,this._contact.length);this._contact=c}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(n){Array.isArray(n)||(n=[]),this._extraHeaders=n.slice()}setExtraContactParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}setExtraContactUriParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const r in n)if(Object.prototype.hasOwnProperty.call(n,r)){const a=n[r];this._extraContactParams+=`;${r}`,a&&(this._extraContactParams+=`=${a}`)}}register(){if(this._registering){_l.debug("Register request in progress...");return}const n=this._extraHeaders.slice();n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),n.push(`Expires: ${this._expires}`);const r=new On.OutgoingRequest(oe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n),a=new sl(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,oe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,oe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{if(c.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):{if(this._registering=!1,!c.hasHeader("Contact")){_l.debug("no Contact header in response to REGISTER, response ignored");break}const e=c.headers.Contact.reduce((A,S)=>A.concat(S.parsed),[]);let _=e.find(A=>this._sipInstance===A.getParam("+sip.instance")&&this._reg_id===parseInt(A.getParam("reg-id")));if(_||(_=e.find(A=>A.uri.user===this._ua.contact.uri.user)),!_){_l.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let g=_.getParam("expires");!g&&c.hasHeader("expires")&&(g=c.getHeader("expires")),g||(g=this._expires),g=Number(g),g<zu&&(g=zu);const d=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):Math.floor(g*1e3/2);this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},d),_.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=_.getParam("temp-gruu").replace(/"/g,"")),_.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=_.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:c}));break}case/^423$/.test(c.status_code):{c.hasHeader("min-expires")?(this._expires=Number(c.getHeader("min-expires")),this._expires<zu&&(this._expires=zu),this.register()):(_l.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(c,oe.causes.SIP_FAILURE_CODE));break}default:{const e=qs.sipErrorCause(c.status_code);this._registrationFailure(c,e)}}}});this._registering=!0,a.send()}unregister(n={}){if(!this._registered){_l.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();n.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),r.push("Expires: 0");const a=new On.OutgoingRequest(oe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new sl(this._ua,a,{onRequestTimeout:()=>{this._unregistered(null,oe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,oe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:c=>{switch(!0){case/^1[0-9]{2}$/.test(c.status_code):break;case/^2[0-9]{2}$/.test(c.status_code):this._unregistered(c);break;default:{const e=qs.sipErrorCause(c.status_code);this._unregistered(c,e)}}}}).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(n,r){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:r}))}_unregistered(n,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:r||null})}}const un=console,fi={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},EA=cA;class CA extends EA{constructor(n){super(n),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 SA(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(n,r){return super.call(n,r)}joinVideoCall(n,r,a){un.debug("call()");const c=new qu(this);return c.configureMedia({audio:!0,video:!0}),c.connect(n,r,a),c}startScreenShare(){un.debug("startScreenShare()");for(const n in this._janus_sessions)this._janus_sessions[n].connectScreenShare()}changeMediaConstraints(n){for(const r in this._janus_sessions)this._janus_sessions[r].changeMediaConstraints(n)}startBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].connectBlur()}stopBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].stopBlur()}_loadConfig(n){try{pl.load(this._configuration,n)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=qs.newUUID());let r;typeof window<"u"&&typeof window.document<"u"?r=window?.navigator.userAgent:typeof self<"u"&&self.navigator&&(r=self.navigator.userAgent),r+=" "+bt.USER_AGENT,this._configuration.user_agent=n.overrideUserAgent&&typeof n.overrideUserAgent=="function"?n.overrideUserAgent(r):r,n.onTransportCallback&&typeof n.onTransportCallback=="function"&&(this.onTransportCallback=n.onTransportCallback),this._configuration.jssip_id=qs.createRandomToken(5);const a=this._configuration.uri.clone();a.user=null,this._configuration.hostport_params=a.toString().replace(/^sip:/i,"");try{this._transport=new UC(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=AA.bind(this),this._transport.onconnect=IA.bind(this),this._transport.ondisconnect=RA.bind(this),this._transport.ondata=$A.bind(this)}catch(e){throw un.warn(e),new di.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 e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ba("sip",qs.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){const _=e.anonymous||null,g=e.outbound||null;let d="<";return _?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),g&&(_?!this.temp_gruu:!this.pub_gruu)&&(d+=";ob"),d+=">",d}};const c=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(c.indexOf(e)!==-1?Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}));un.debug("configuration parameters after validation:");for(const e in this._configuration)if(Object.prototype.hasOwnProperty.call(pl.settings,e))switch(e){case"uri":case"registrar_server":un.debug(`- ${e}: ${this._configuration[e]}`);break;case"password":case"ha1":case"authorization_jwt":un.debug(`- ${e}: NOT SHOWN`);break;default:un.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}newMSRPSession(n,r){n.on("msgHistoryUpdate",a=>{console.log(a)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",r)}newJanusSession(n,r){this._janus_sessions[n.id]=n,this.newStreamPlugins.forEach(a=>{a.setSession(n)}),this.processStreamPlugins.forEach(a=>{a.setSession(n)}),this.emit("newJanusSession",r)}kill(){}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(n){var r,a,c,e;const _=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){un.debug("Request-URI does not point to us"),n.method!==bt.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===bt.SIPS){n.reply_sl(416);return}if(Ir.checkTransaction(this,n))return;if(_===bt.INVITE?new Ir.InviteServerTransaction(this,this._transport,n):_!==bt.ACK&&_!==bt.CANCEL&&new Ir.NonInviteServerTransaction(this,this._transport,n),_===bt.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const A=Date.now(),S=this.lastOptionsTimestamp>A-35e3,R=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>A;S&&R&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){n.reply(200);return}new b_.Options(this).init_incoming(n)}else if(_===bt.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new b_.Message(this).init_incoming(n)}else if(_===bt.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let g,d;if(n.to_tag)if(g=this._findDialog(n.call_id,n.from_tag,n.to_tag),g)g.receiveRequest(n);else if(_===bt.NOTIFY)if(d=this._findSession(n),d)d.receiveRequest(n);else{if(n.body)try{const A=JSON.parse(n.body)||{};(a=(r=A.plugindata)==null?void 0:r.data)!=null&&a.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(A),(e=(c=A.plugindata)==null?void 0:c.data)!=null&&e.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(A.plugindata.data.unpublished)}catch(A){console.error(A)}n.reply(200)}else _!==bt.ACK&&n.reply(481);else switch(_){case bt.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const A=n.replaces;g=this._findDialog(A.call_id,A.from_tag,A.to_tag),g?(d=g.owner,d.isEnded()?n.reply(603):d.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(d=new Od(this),d.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(d=new TC(this),d.init_incoming(n));else un.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case bt.BYE:n.reply(481);break;case bt.CANCEL:d=this._findSession(n),d?d.receiveRequest(n):un.debug("received CANCEL request for a non existent session");break;case bt.ACK:break;case bt.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,r){un.debug("startMSRP()",r);const a=new Od(this);return a.connect(n),a}startJanus(n,r){un.debug("startJanus()",r);const a=new Od(this);return a.connect(n),a}terminateMSRPSessions(n){un.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(n)}terminateJanusSessions(n){un.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(n)}enableJanusAudio(n){un.debug("enableJanusAudio()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startAudio():this._janus_sessions[r].stopAudio())}enableJanusVideo(n){un.debug("enableJanusVideo()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(n?this._janus_sessions[r].startVideo():this._janus_sessions[r].stopVideo())}terminateAllSessions(){for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){un.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch(r){console.error(r)}}}stop(n=!0){if(un.debug("stop()"),this._dynConfiguration={},this._status===fi.STATUS_USER_CLOSED){un.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;n&&this.terminateAllSessions();for(const a in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,a)){un.debug(`closing session ${a}`);try{this._msrp_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,a)){un.debug(`closing session ${a}`);try{this._janus_sessions[a].terminate()}catch(c){console.error(c)}}for(const a in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,a))try{this._applicants[a].close()}catch(c){console.error(c)}this._status=fi.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&&r===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function AA(o){this.emit("connecting",o)}function IA(o){this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_READY,this._error=null,this.emit("connected",o),this._dynConfiguration.register&&this._registrator.register())}function RA(o){const n=["nict","ict","nist","ist"];for(const r of n)for(const a in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],a)&&this._transactions[r][a].onTransportError();this.emit("disconnected",o),this._registrator.onTransportClosed(),this._status!==fi.STATUS_USER_CLOSED&&(this._status=fi.STATUS_NOT_READY,this._error=fi.NETWORK_ERROR)}function $A(o){const n=o.transport;let r=o.message;const a=r;if(r=wA.parseMessage(r,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(r,a),!!r&&!(this._status===fi.STATUS_USER_CLOSED&&r instanceof Za.IncomingRequest)&&JC(r,this,n)){if(r instanceof Za.IncomingRequest)r.transport=n,this.receiveRequest(r);else if(r instanceof Za.IncomingResponse){let c;switch(r.method){case bt.INVITE:c=this._transactions.ict[r.via_branch],c&&c.receiveResponse(r);break;case bt.ACK:break;default:c=this._transactions.nict[r.via_branch],c&&c.receiveResponse(r);break}}}}const xA=["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"],OA=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function yf(o){const n={};return xA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n.localHold=o._localHold,n}function vf(o){const n={};return OA.forEach(r=>{o[r]!==void 0&&(n[r]=o[r])}),n}async function Dd(o,n,r){const a=o.createMediaStreamSource(n),c=o.createMediaStreamDestination(),e=o.createGain();return a.connect(e),e.connect(c),e.gain.value=r,c.stream}function kA(o,n,r,a){if(Tf())return;const c=document.createElement("audio");c.id=n._id,c.className="audioTag",c.srcObject=o,c.setSinkId(r),c.volume=a,c.play(),n.audioTag=c}function DA(o){if(o&&typeof o.log=="function"&&typeof o.warn=="function"&&typeof o.error=="function")return!0}function Tf(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const NA=mn,MA=Hr(),Jn=new NA("WebSocketInterface");var UA=class{constructor(o){Jn.debug('new() [url:"%s"]',o),this._url=o,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=MA.parse(o,"absoluteURI");if(n===-1)throw Jn.warn(`invalid WebSocket URI: ${o}`),new TypeError(`Invalid argument: ${o}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw Jn.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${o}`);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(o){this._via_transport=o.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Jn.debug("connect()"),this.isConnected()){Jn.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Jn.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Jn.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(o){this._onError(o)}}disconnect(){Jn.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(o){return Jn.debug("send()"),this.isConnected()?(this._ws.send(o),!0):(Jn.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(){Jn.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:o,code:n,reason:r}){Jn.debug(`WebSocket ${this._url} closed`),o===!1&&Jn.debug("WebSocket abrupt disconnection"),this.ondisconnect(!o,n,r)}_onMessage({data:o}){Jn.debug("received WebSocket message"),this.ondata(o)}_onError(o){Jn.warn(`WebSocket ${this._url} error: `,o)}};const Nd=Pl,PA=bt,LA=Ls,qA=$n(),HA=ff,zA=Ms(),FA=ed(),BA=Hr(),VA=UA;Wa("JsSIP")("version %s",Nd.version);var jA={C:PA,Exceptions:LA,Utils:qA,UA:HA,URI:zA,NameAddrHeader:FA,WebSocketInterface:VA,Grammar:BA,debug:Wa,get name(){return Nd.title},get version(){return Nd.version}};const GA=Qt(jA);function Md(o){return o<10?`0${o}`:`${o}`}function WA(o){let n=o.hours||0,r=o.minutes||0,a=o.seconds||0;a++,a===60&&(a=0,r++,r===60&&(r=0,n++));const c=`${Md(n)}:${Md(r)}:${Md(a)}`;return{seconds:a,minutes:r,hours:n,formatted:c}}function KA(o){let n=0;for(let r=0;r<o.length;r++)n+=o[r]*o[r];return Math.sqrt(n/o.length)}async function YA(o,n,r=150){const a=n.createMediaStreamSource(o),c=n.createDelay();c.delayTime.value=r/1e3;const e=n.createGain();e.gain.value=0;const _=n.createMediaStreamDestination();return a.connect(c).connect(e).connect(_),{stream:_.stream,setSpeaking:g=>{e.gain.value=g?1:0}}}var Mn={};Mn.forEach=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)if(c in o){const e=Promise.resolve(o[c]).then(_=>n.call(r||globalThis,_,c,o));a.push(e)}await Promise.all(a)},Mn.forEachSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)a in o&&await n.call(r||globalThis,await o[a],a,o)},Mn.map=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=Promise.resolve(o[c]).then(e=>n.call(r||globalThis,e,c,o)));return Promise.all(a)},Mn.mapSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&(a[c]=await n.call(r||globalThis,await o[c],c,o));return a},Mn.find=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a();let e=1;for(let _=0;_<o.length;_++){const g=d=>{d?a(o[_]):e===o.length&&a(),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.findSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return o[a]},Mn.findIndex=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(-1);let e=1;for(let _=0;_<o.length;_++){const g=d=>{d?a(_):e===o.length&&a(-1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.findIndexSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(await n.call(r||globalThis,await o[a],a,o))return a},Mn.some=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!1);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const g=d=>{d?a(!0):e===o.length&&a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.someSeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&await n.call(r||globalThis,await o[a],a,o))return!0;return!1},Mn.every=(o,n,r)=>new Promise((a,c)=>{if(o.length===0)return a(!0);let e=1;for(let _=0;_<o.length;_++){if(!(_ in o)){e++;continue}const g=d=>{d?e===o.length&&a(!0):a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(g).catch(c)}}),Mn.everySeries=async(o,n,r)=>{for(let a=0;a<o.length;a++)if(a in o&&!await n.call(r||globalThis,await o[a],a,o))return!1;return!0},Mn.filter=(o,n,r)=>new Promise(async(a,c)=>{const e=[];for(let g=0;g<o.length;g++)g in o&&(e[g]=Promise.resolve(o[g]).then(d=>n.call(r||globalThis,d,g,o)).catch(c));const _=[];for(let g=0;g<e.length;g++)await e[g]&&_.push(await o[g]);a(_)}),Mn.filterSeries=async(o,n,r)=>{const a=[];for(let c=0;c<o.length;c++)c in o&&await n.call(r||globalThis,await o[c],c,o)&&a.push(await o[c]);return a},Mn.reduce=async(o,n,r)=>{if(o.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let a,c;for(r!==void 0?(c=r,a=0):(c=o[0],a=1),a;a<o.length;a++)a in o&&(c=await n(await c,await o[a],a,o));return c};var bf={};(function(o){const n=Mn;Object.keys(n).forEach(r=>{const a=r.charAt(0).toUpperCase()+r.slice(1);o[`async${a}`]=async function(...c){return n[r](this,...c)}})})(bf);var XA=Object.assign(Mn,{instanceMethods:bf});const Br={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"},JA={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 QA={exports:{}};(function(o){var n=function(r){var a=Object.prototype,c=a.hasOwnProperty,e=Object.defineProperty||function(Ae,fe,se){Ae[fe]=se.value},_,g=typeof Symbol=="function"?Symbol:{},d=g.iterator||"@@iterator",A=g.asyncIterator||"@@asyncIterator",S=g.toStringTag||"@@toStringTag";function R(Ae,fe,se){return Object.defineProperty(Ae,fe,{value:se,enumerable:!0,configurable:!0,writable:!0}),Ae[fe]}try{R({},"")}catch{R=function(Ae,fe,se){return Ae[fe]=se}}function N(Ae,fe,se,st){var We=fe&&fe.prototype instanceof De?fe:De,ht=Object.create(We.prototype),It=new Se(st||[]);return e(ht,"_invoke",{value:ue(Ae,se,It)}),ht}r.wrap=N;function H(Ae,fe,se){try{return{type:"normal",arg:Ae.call(fe,se)}}catch(st){return{type:"throw",arg:st}}}var W="suspendedStart",G="suspendedYield",K="executing",ae="completed",ee={};function De(){}function X(){}function re(){}var be={};R(be,d,function(){return this});var Ne=Object.getPrototypeOf,Q=Ne&&Ne(Ne($e([])));Q&&Q!==a&&c.call(Q,d)&&(be=Q);var ce=re.prototype=De.prototype=Object.create(be);X.prototype=re,e(ce,"constructor",{value:re,configurable:!0}),e(re,"constructor",{value:X,configurable:!0}),X.displayName=R(re,S,"GeneratorFunction");function me(Ae){["next","throw","return"].forEach(function(fe){R(Ae,fe,function(se){return this._invoke(fe,se)})})}r.isGeneratorFunction=function(Ae){var fe=typeof Ae=="function"&&Ae.constructor;return fe?fe===X||(fe.displayName||fe.name)==="GeneratorFunction":!1},r.mark=function(Ae){return Object.setPrototypeOf?Object.setPrototypeOf(Ae,re):(Ae.__proto__=re,R(Ae,S,"GeneratorFunction")),Ae.prototype=Object.create(ce),Ae},r.awrap=function(Ae){return{__await:Ae}};function _e(Ae,fe){function se(ht,It,qe,Ue){var wt=H(Ae[ht],Ae,It);if(wt.type==="throw")Ue(wt.arg);else{var Yt=wt.arg,Xe=Yt.value;return Xe&&typeof Xe=="object"&&c.call(Xe,"__await")?fe.resolve(Xe.__await).then(function(Je){se("next",Je,qe,Ue)},function(Je){se("throw",Je,qe,Ue)}):fe.resolve(Xe).then(function(Je){Yt.value=Je,qe(Yt)},function(Je){return se("throw",Je,qe,Ue)})}}var st;function We(ht,It){function qe(){return new fe(function(Ue,wt){se(ht,It,Ue,wt)})}return st=st?st.then(qe,qe):qe()}e(this,"_invoke",{value:We})}me(_e.prototype),R(_e.prototype,A,function(){return this}),r.AsyncIterator=_e,r.async=function(Ae,fe,se,st,We){We===void 0&&(We=Promise);var ht=new _e(N(Ae,fe,se,st),We);return r.isGeneratorFunction(fe)?ht:ht.next().then(function(It){return It.done?It.value:ht.next()})};function ue(Ae,fe,se){var st=W;return function(We,ht){if(st===K)throw new Error("Generator is already running");if(st===ae){if(We==="throw")throw ht;return zt()}for(se.method=We,se.arg=ht;;){var It=se.delegate;if(It){var qe=ye(It,se);if(qe){if(qe===ee)continue;return qe}}if(se.method==="next")se.sent=se._sent=se.arg;else if(se.method==="throw"){if(st===W)throw st=ae,se.arg;se.dispatchException(se.arg)}else se.method==="return"&&se.abrupt("return",se.arg);st=K;var Ue=H(Ae,fe,se);if(Ue.type==="normal"){if(st=se.done?ae:G,Ue.arg===ee)continue;return{value:Ue.arg,done:se.done}}else Ue.type==="throw"&&(st=ae,se.method="throw",se.arg=Ue.arg)}}}function ye(Ae,fe){var se=fe.method,st=Ae.iterator[se];if(st===_)return fe.delegate=null,se==="throw"&&Ae.iterator.return&&(fe.method="return",fe.arg=_,ye(Ae,fe),fe.method==="throw")||se!=="return"&&(fe.method="throw",fe.arg=new TypeError("The iterator does not provide a '"+se+"' method")),ee;var We=H(st,Ae.iterator,fe.arg);if(We.type==="throw")return fe.method="throw",fe.arg=We.arg,fe.delegate=null,ee;var ht=We.arg;if(!ht)return fe.method="throw",fe.arg=new TypeError("iterator result is not an object"),fe.delegate=null,ee;if(ht.done)fe[Ae.resultName]=ht.value,fe.next=Ae.nextLoc,fe.method!=="return"&&(fe.method="next",fe.arg=_);else return ht;return fe.delegate=null,ee}me(ce),R(ce,S,"Generator"),R(ce,d,function(){return this}),R(ce,"toString",function(){return"[object Generator]"});function Re(Ae){var fe={tryLoc:Ae[0]};1 in Ae&&(fe.catchLoc=Ae[1]),2 in Ae&&(fe.finallyLoc=Ae[2],fe.afterLoc=Ae[3]),this.tryEntries.push(fe)}function J(Ae){var fe=Ae.completion||{};fe.type="normal",delete fe.arg,Ae.completion=fe}function Se(Ae){this.tryEntries=[{tryLoc:"root"}],Ae.forEach(Re,this),this.reset(!0)}r.keys=function(Ae){var fe=Object(Ae),se=[];for(var st in fe)se.push(st);return se.reverse(),function We(){for(;se.length;){var ht=se.pop();if(ht in fe)return We.value=ht,We.done=!1,We}return We.done=!0,We}};function $e(Ae){if(Ae){var fe=Ae[d];if(fe)return fe.call(Ae);if(typeof Ae.next=="function")return Ae;if(!isNaN(Ae.length)){var se=-1,st=function We(){for(;++se<Ae.length;)if(c.call(Ae,se))return We.value=Ae[se],We.done=!1,We;return We.value=_,We.done=!0,We};return st.next=st}}return{next:zt}}r.values=$e;function zt(){return{value:_,done:!0}}return Se.prototype={constructor:Se,reset:function(Ae){if(this.prev=0,this.next=0,this.sent=this._sent=_,this.done=!1,this.delegate=null,this.method="next",this.arg=_,this.tryEntries.forEach(J),!Ae)for(var fe in this)fe.charAt(0)==="t"&&c.call(this,fe)&&!isNaN(+fe.slice(1))&&(this[fe]=_)},stop:function(){this.done=!0;var Ae=this.tryEntries[0],fe=Ae.completion;if(fe.type==="throw")throw fe.arg;return this.rval},dispatchException:function(Ae){if(this.done)throw Ae;var fe=this;function se(Ue,wt){return ht.type="throw",ht.arg=Ae,fe.next=Ue,wt&&(fe.method="next",fe.arg=_),!!wt}for(var st=this.tryEntries.length-1;st>=0;--st){var We=this.tryEntries[st],ht=We.completion;if(We.tryLoc==="root")return se("end");if(We.tryLoc<=this.prev){var It=c.call(We,"catchLoc"),qe=c.call(We,"finallyLoc");if(It&&qe){if(this.prev<We.catchLoc)return se(We.catchLoc,!0);if(this.prev<We.finallyLoc)return se(We.finallyLoc)}else if(It){if(this.prev<We.catchLoc)return se(We.catchLoc,!0)}else if(qe){if(this.prev<We.finallyLoc)return se(We.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Ae,fe){for(var se=this.tryEntries.length-1;se>=0;--se){var st=this.tryEntries[se];if(st.tryLoc<=this.prev&&c.call(st,"finallyLoc")&&this.prev<st.finallyLoc){var We=st;break}}We&&(Ae==="break"||Ae==="continue")&&We.tryLoc<=fe&&fe<=We.finallyLoc&&(We=null);var ht=We?We.completion:{};return ht.type=Ae,ht.arg=fe,We?(this.method="next",this.next=We.finallyLoc,ee):this.complete(ht)},complete:function(Ae,fe){if(Ae.type==="throw")throw Ae.arg;return Ae.type==="break"||Ae.type==="continue"?this.next=Ae.arg:Ae.type==="return"?(this.rval=this.arg=Ae.arg,this.method="return",this.next="end"):Ae.type==="normal"&&fe&&(this.next=fe),ee},finish:function(Ae){for(var fe=this.tryEntries.length-1;fe>=0;--fe){var se=this.tryEntries[fe];if(se.finallyLoc===Ae)return this.complete(se.completion,se.afterLoc),J(se),ee}},catch:function(Ae){for(var fe=this.tryEntries.length-1;fe>=0;--fe){var se=this.tryEntries[fe];if(se.tryLoc===Ae){var st=se.completion;if(st.type==="throw"){var We=st.arg;J(se)}return We}}throw new Error("illegal catch attempt")},delegateYield:function(Ae,fe,se){return this.delegate={iterator:$e(Ae),resultName:fe,nextLoc:se},this.method==="next"&&(this.arg=_),ee}},r}(o.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})(QA);var wf={exports:{}};(function(o){(function(n,r){o.exports?o.exports=r():n.log=r()})(Sb,function(){var n=function(){},r="undefined",a=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),c=["trace","debug","info","warn","error"];function e(G,K){var ae=G[K];if(typeof ae.bind=="function")return ae.bind(G);try{return Function.prototype.bind.call(ae,G)}catch{return function(){return Function.prototype.apply.apply(ae,[G,arguments])}}}function _(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function g(G){return G==="debug"&&(G="log"),typeof console===r?!1:G==="trace"&&a?_:console[G]!==void 0?e(console,G):console.log!==void 0?e(console,"log"):n}function d(G,K){for(var ae=0;ae<c.length;ae++){var ee=c[ae];this[ee]=ae<G?n:this.methodFactory(ee,G,K)}this.log=this.debug}function A(G,K,ae){return function(){typeof console!==r&&(d.call(this,K,ae),this[G].apply(this,arguments))}}function S(G,K,ae){return g(G)||A.apply(this,arguments)}function R(G,K,ae){var ee=this,De;K=K??"WARN";var X="loglevel";typeof G=="string"?X+=":"+G:typeof G=="symbol"&&(X=void 0);function re(ce){var me=(c[ce]||"silent").toUpperCase();if(!(typeof window===r||!X)){try{window.localStorage[X]=me;return}catch{}try{window.document.cookie=encodeURIComponent(X)+"="+me+";"}catch{}}}function be(){var ce;if(!(typeof window===r||!X)){try{ce=window.localStorage[X]}catch{}if(typeof ce===r)try{var me=window.document.cookie,_e=me.indexOf(encodeURIComponent(X)+"=");_e!==-1&&(ce=/^([^;]+)/.exec(me.slice(_e))[1])}catch{}return ee.levels[ce]===void 0&&(ce=void 0),ce}}function Ne(){if(!(typeof window===r||!X)){try{window.localStorage.removeItem(X);return}catch{}try{window.document.cookie=encodeURIComponent(X)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}ee.name=G,ee.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},ee.methodFactory=ae||S,ee.getLevel=function(){return De},ee.setLevel=function(ce,me){if(typeof ce=="string"&&ee.levels[ce.toUpperCase()]!==void 0&&(ce=ee.levels[ce.toUpperCase()]),typeof ce=="number"&&ce>=0&&ce<=ee.levels.SILENT){if(De=ce,me!==!1&&re(ce),d.call(ee,ce,G),typeof console===r&&ce<ee.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+ce},ee.setDefaultLevel=function(ce){K=ce,be()||ee.setLevel(ce,!1)},ee.resetLevel=function(){ee.setLevel(K,!1),Ne()},ee.enableAll=function(ce){ee.setLevel(ee.levels.TRACE,ce)},ee.disableAll=function(ce){ee.setLevel(ee.levels.SILENT,ce)};var Q=be();Q==null&&(Q=K),ee.setLevel(Q,!1)}var N=new R,H={};N.getLogger=function(G){if(typeof G!="symbol"&&typeof G!="string"||G==="")throw new TypeError("You must supply a name when creating a logger.");var K=H[G];return K||(K=H[G]=new R(G,N.getLevel(),N.methodFactory)),K};var W=typeof window!==r?window.log:void 0;return N.noConflict=function(){return typeof window!==r&&window.log===N&&(window.log=W),N},N.getLoggers=function(){return H},N.default=N,N})})(wf);var Vn=wf.exports;const Hs=()=>`${new Date().toISOString()} | metrics`,zs=(o,n,r)=>`${o} | ${n} | ${r}`;Vn.setDefaultLevel(Vn.levels.TRACE);const ZA=o=>{Vn.info(zs(Hs(),"log ",`set log level to ${o?"verbose":"info"}`)),Vn.setLevel(o?Vn.levels.TRACE:Vn.levels.INFO)},e1=o=>{const n=[...Object.keys(Vn.levels)];n.includes(o)?(Vn.info(zs(Hs(),"log ",`update log level to ${o.toLowerCase()}`)),Vn.setLevel(o)):Vn.warn(zs(Hs(),"log ","Incorrect log level please choose one of "),n)},Rt=(o,n,r)=>{r?Vn.debug(zs(Hs(),o,n),r):Vn.debug(zs(Hs(),o,n))},Ud=(o,n)=>{Vn.info(zs(Hs(),o,n))},wa=(o,n)=>{Vn.info(zs(Hs(),o,n))},Fu=(o,n)=>{Vn.warn(zs(Hs(),o,n))},so=(o,n)=>{Vn.error(zs(Hs(),o,n))};function t1(o){return Math.floor(Math.random()*o).toString()}function Sf(o,n){let r=n;return o.forEach(a=>{r=r.replace(a,"")}),r}function n1(o,n){let r="";for(let a=0;a<n;a+=1)r+=o[t1(o.length)];return r}function r1({length:o=20,useLetters:n=!0,useNumbers:r=!0,includeSymbols:a=[],excludeSymbols:c=[]}={}){let e="abcdefghijklmnopqrstuvwxyz",_="0123456789",g=[],d=[],A=[];return n&&(c.length&&(e=Sf(c,e)),d=e.split("")),r&&(c.length&&(_=Sf(c,_)),A=_.split("")),g=[...d,...A,...a],n1(g,o)}var s1=r1;const fl=Qt(s1),i1=()=>"WebRTCMetrics",a1=()=>"5.0.3",Ht={INBOUND:"inbound",OUTBOUND:"outbound"},Fs={IDLE:"idle",RUNNING:"running",MUTED:"muted"},ml={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},o1=()=>({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:[]}),Ef={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:Ht.INBOUND},Cf={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:Ht.OUTBOUND},Af={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:Ht.INBOUND},If={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:Ht.OUTBOUND},l1=o=>{const n={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(o){const r={...o,audio:{},video:{},data:{...o.data},network:{...o.network},experimental:{...o.experimental}};return Object.keys(o.audio).forEach(a=>{r.audio[a]={...o.audio[a]}}),Object.keys(o.video).forEach(a=>{r.video[a]={...o.video[a]}}),r}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},u1={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${fl()}`,cid:`c-${fl()}`,uid:`u-${fl()}`,record:!1,ticket:!0},Vr={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"},ge={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"},ie={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},gl={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Pd={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Me={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Ld="config ",c1=(o,n={},r)=>{const a={...r,...n};return n.pname||Fu(Ld,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),n.cid||Fu(Ld,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),n.uid||Fu(Ld,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),a.pc=o,a},d1=(o={})=>{const n={...u1,...o};return n.name=i1(),n.version=a1(),n},yl=(o,n,r,a=!1,c)=>{let e=o.map(_=>{if(!r)return _[n];if(!c)return _[n][r];const g=_[n][c];return g?g[r]:null});return e=e.filter(_=>a?Number.isFinite(_)&&_>0:Number.isFinite(_)),e.length===0?[]:e},mi=o=>o.reduce((n,r)=>n+r,0)/o.length,h1=()=>`probe-${fl()}`,p1=()=>`coltr-${fl()}`,Rf=o=>new Promise(n=>setTimeout(n,o)),qd=(o,n,r)=>{n?o.call(n,r):o(r)},Zt=(o,n,r,a)=>{const c=yl(o,n,r,!0,a);if(c.length===0)return null;const e=c.reduce((_,g)=>_+g,0)/c.length;return e===0?null:c.map(_=>Math.abs(e-_)).reduce((_,g)=>_+g,0)/c.length*100/e},nn=(o,n,r,a=!1,c)=>{const e=yl(o,n,r,a,c);return e.length===0?null:e.reduce((_,g)=>_+g,0)/e.length},Sa=(o,n,r)=>yl(o,n,r).reduce((a,c)=>a+c,0),en=(o,n,r,a)=>{const c=yl(o,n,r,!0,a);return c.length===0?null:Math.min(...c)},tn=(o,n,r,a)=>{const c=yl(o,n,r,!1,a);return c.length===0?null:Math.max(...c)},Un=(o,n,r,a)=>{const c=o.slice().pop();if(!c)return null;if(!r)return c[n];if(!a)return c[n][r];const e=c[n][a];return e?e[r]:null},_1=o=>o.slice().pop(),wn=(o,n,r)=>{if(!n)return null;const a={};let c=n[ie.AUDIO][o];c||(c=r===Ht.INBOUND?{...Ef}:{...Cf}),a[ie.AUDIO]=c;let e=n[ie.VIDEO][o];return e||(e=r===Ht.INBOUND?{...Af}:{...If}),a[ie.VIDEO]=e,a},vl="exporter ",f1="2.0",$f=(o,n,r)=>{if(!o||o.length===0)return 0;const a=o[o.length-1];if(!a)return 0;const c=a[n][r];if(c){const e=c.total_rtt_ms_out,_=c.total_rtt_measure_out;return!_||!e?nn(o,n,"delta_rtt_ms_out",!1,r):Number(e/_)}return null},m1=(o,n)=>{if(!o||o.length===0)return 0;const r=o[o.length-1];if(!r)return 0;const a=r[n].total_rtt_connectivity_ms,c=r[n].total_rtt_connectivity_measure;return!c||!a?nn(o,n,"delta_rtt_connectivity_ms"):Number(a/c)},g1=o=>Un(o,"network","local_candidate_type")!=="relay"?`direct/${Un(o,"network","local_candidate_protocol")}`:`turn/${Un(o,"network","local_candidate_relay_protocol")}`,y1=o=>{const n=Un(o,"network","remote_candidate_type"),r=Un(o,"network","remote_candidate_protocol");return n!=="relay"?`direct/${r}`:`turn/${r}`};class v1{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){Ud(vl,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){Ud(vl,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Rt(vl,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){Ud(vl,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Rt(vl,"ticket() - generate ticket");const n=Un(this._reports,"audio","total_packets_lost_in"),r=Un(this._reports,"audio","total_packets_in"),a=Un(this._reports,"video","total_packets_lost_in"),c=Un(this._reports,"video","total_packets_in"),e={},_=_1(this._reports);return _&&(Object.keys(_[ie.AUDIO]).forEach(g=>{const d=_[ie.AUDIO][g];if(e[d.ssrc]={type:ie.AUDIO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_kbs_in",g),max:tn(this._reports,ie.AUDIO,"delta_kbs_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_in",!1,g),min:en(this._reports,ie.AUDIO,"delta_KBytes_in",g),max:tn(this._reports,ie.AUDIO,"delta_KBytes_in",g),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_in",!1,g),min:en(this._reports,ie.AUDIO,"mos_emodel_in",g),max:tn(this._reports,ie.AUDIO,"mos_emodel_in",g),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_in",g)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_in",!1,g),min:en(this._reports,ie.AUDIO,"mos_in",g),max:tn(this._reports,ie.AUDIO,"mos_in",g),volatility:Zt(this._reports,ie.AUDIO,"mos_in",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_in",g),W=Un(this._reports,ie.AUDIO,"total_packets_in",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].mos=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G}else{const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_kbs_out",g),max:tn(this._reports,ie.AUDIO,"delta_kbs_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_out",!1,g),min:en(this._reports,ie.AUDIO,"delta_KBytes_out",g),max:tn(this._reports,ie.AUDIO,"delta_KBytes_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},N={avg:$f(this._reports,ie.AUDIO,g),min:en(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),max:tn(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),volatility:Zt(this._reports,ie.AUDIO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_out",g),W=Un(this._reports,ie.AUDIO,"total_packets_out",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},K={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_out",!1,g),min:en(this._reports,ie.AUDIO,"mos_emodel_out",g),max:tn(this._reports,ie.AUDIO,"mos_emodel_out",g),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_out",g)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_out",!1,g),min:en(this._reports,ie.AUDIO,"mos_out",g),max:tn(this._reports,ie.AUDIO,"mos_out",g),volatility:Zt(this._reports,ie.AUDIO,"mos_out",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[g].jitter=A,e[g].rtt=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G,e[g].mos=K}}),Object.keys(_[ie.VIDEO]).forEach(g=>{const d=_[ie.VIDEO][g];if(e[g]={type:ie.VIDEO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_kbs_in",g),max:tn(this._reports,ie.VIDEO,"delta_kbs_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_in",!1,g),min:en(this._reports,ie.VIDEO,"delta_KBytes_in",g),max:tn(this._reports,ie.VIDEO,"delta_KBytes_in",g),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N=Un(this._reports,ie.VIDEO,"total_packets_lost_in",g),H=Un(this._reports,ie.VIDEO,"total_packets_in",g),W={lost:N,avg:Math.round((N/(N+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].traffic=R,e[g].bitrate=S,e[g].loss=W}else{const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_kbs_out",g),max:tn(this._reports,ie.VIDEO,"delta_kbs_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_out",!1,g),min:en(this._reports,ie.VIDEO,"delta_KBytes_out",g),max:tn(this._reports,ie.VIDEO,"delta_KBytes_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={avg:$f(this._reports,ie.VIDEO,g),min:en(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),max:tn(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),volatility:Zt(this._reports,ie.VIDEO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.VIDEO,"total_packets_lost_out",g),W=Un(this._reports,ie.VIDEO,"total_packets_out",g),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[g].jitter=A,e[g].rtt=N,e[g].traffic=R,e[g].bitrate=S,e[g].loss=G}})),{version:f1,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:e,data:{rtt:{avg:m1(this._reports,"data"),min:en(this._reports,"data","delta_rtt_connectivity_ms"),max:tn(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Zt(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+r)*100||0)*100)/100}},video:{in:{avg:Math.round((a/(a+c)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:nn(this._reports,"data","delta_kbs_in"),min:en(this._reports,"data","delta_kbs_in"),max:tn(this._reports,"data","delta_kbs_in"),volatility:Zt(this._reports,"data","delta_kbs_in")},out:{avg:nn(this._reports,"data","delta_kbs_out"),min:en(this._reports,"data","delta_kbs_out"),max:tn(this._reports,"data","delta_kbs_out"),volatility:Zt(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:nn(this._reports,"data","delta_KBytes_in"),min:en(this._reports,"data","delta_KBytes_in"),max:tn(this._reports,"data","delta_KBytes_in"),volatility:Zt(this._reports,"data","delta_KBytes_in")},out:{avg:nn(this._reports,"data","delta_KBytes_out"),min:en(this._reports,"data","delta_KBytes_out"),max:tn(this._reports,"data","delta_KBytes_out"),volatility:Zt(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:g1(this._reports),remoteConnection:y1(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const gi="extractor ",xf=(o,n,r,a)=>{let c=!1;const e=a[n].total_rtt_ms_out,_=a[n].total_rtt_measure_out,g=r?r[n].total_rtt_ms_out:0,d=r?r[n].total_rtt_measure_out:0,A={rtt:null,totalRTT:e,totalRTTMeasurements:_};if(o[ge.TIMESTAMP]===a[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ge.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(c=!0,Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d===_))return A;const S=1e3*Number(o[ge.ROUND_TRIP_TIME]);let R=e+S,N=_+1;return c&&(R=1e3*Number(o[ge.TOTAL_ROUND_TRIP_TIME])-g,N=Number(o[ge.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-d),{rtt:S,totalRTT:R,totalRTTMeasurements:N}},T1=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:a[n].total_rtt_connectivity_ms,totalRTTMeasurements:a[n].total_rtt_connectivity_measure};const c=1e3*Number(o[ge.CURRENT_ROUND_TRIP_TIME]);let e=a[n].total_rtt_connectivity_ms+c,_=a[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ROUND_TRIP_TIME)&&(e=1e3*Number(o[ge.TOTAL_ROUND_TRIP_TIME])-(r?r[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(o,ge.RESPONSES_RECEIVED)&&(_=Number(o[ge.RESPONSES_RECEIVED])-(r?r[n].total_rtt_connectivity_measure:0)),{rtt:c,totalRTT:e,totalRTTMeasurements:_}},Bu=(o,n,r)=>o[ge.TIMESTAMP]===r[n].timestamp_out||!Object.prototype.hasOwnProperty.call(o,ge.JITTER)?null:1e3*(Number(o[ge.JITTER])||0),b1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(o,ge.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[ie.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[ie.VIDEO].total_frames_decoded_in,total_decode_time:n[ie.VIDEO].total_time_decoded_in};const r=o[ge.FRAMES_DECODED],a=o[ge.TOTAL_DECODE_TIME],c=a-n[ie.VIDEO].total_time_decoded_in,e=r-n[ie.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:e>0?c*1e3/e:0,frames_decoded:r,total_decode_time:a}},w1=(o,n)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(o,ge.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[ie.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[ie.VIDEO].total_frames_encoded_out,total_encode_time:n[ie.VIDEO].total_time_encoded_out};const r=o[ge.FRAMES_ENCODED],a=o[ge.TOTAL_ENCODE_TIME],c=a-n[ie.VIDEO].total_time_encoded_out,e=r-n[ie.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:e>0&&c?c*1e3/e:0,frames_encoded:r,total_encode_time:a}},Of=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(o,ge.BYTES_SENT))return{packetsSent:r[n].total_packets_out,packetsLost:r[n].total_packets_lost_out,bytesSent:r[n].total_KBytes_out};const c=Number(o[ge.PACKETS_SENT])||0-(a?a[n].total_packets_out:0),e=c-r[n].total_packets_out,_=Number(o[ge.BYTES_SENT])/1024-(a?a[n].total_KBytes_out:0),g=_-r[n].total_KBytes_out,d=o[ge.TIMESTAMP]||Date.now(),A=a?a.timestamp:null;let S=r.timestamp;!S&&A&&(S=A);const R=S?d-S:0,N=R>0?g*.008*1024/R*1e3:0;return{packetsSent:c,deltaPacketsSent:e,KBytesSent:_,deltaKBytesSent:g,kbsSent:N}},kf=(o,n,r,a)=>{let c=r[n].total_packets_lost_out,e=0,_=0;return Object.prototype.hasOwnProperty.call(o,ge.PACKETS_LOST)&&(c=Number(o[ge.PACKETS_LOST])||0-(a?a[n].total_packets_lost_out:0),e=c-r[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(o,ge.FRACTION_LOST)&&(_=Number(100*o[ge.FRACTION_LOST])),{packetsLost:c,deltaPacketsLost:e,fractionLost:_}},Df=(o,n,r,a)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(o,ge.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(o,ge.BYTES_RECEIVED))return{percent_packets_lost:r[n].percent_packets_lost_in,packetsReceived:r[n].total_packets_in,packetsLost:r[n].total_packets_lost_in,bytesReceived:r[n].total_KBytes_in};const c=Number(o[ge.PACKETS_RECEIVED])||0-(a?a[n].total_packets_in:0),e=Number(o[ge.PACKETS_LOST])||0-(a?a[n].total_packets_lost_in:0),_=e-r[n].total_packets_lost_in,g=c-r[n].total_packets_in,d=c!==r[n].total_packets_in?_*100/(_+g):0,A=Number(o[ge.BYTES_RECEIVED])/1024-(a?a[n].total_KBytes_in:0),S=A-r[n].total_KBytes_in,R=o[ge.TIMESTAMP]||Date.now(),N=a?a.timestamp:null;let H=r.timestamp;!H&&N&&(H=N);const W=H?R-H:0,G=W>0?S*.008*1024/W*1e3:0;return{percentPacketsLost:d,packetsReceived:c,deltaPacketsReceived:g,packetsLost:e,deltaPacketsLost:_,KBytesReceived:A,deltaKBytesReceived:S,kbsReceived:G}},S1=o=>o[ge.CANDIDATE_TYPE]!=="relay"?"":o[ge.RELAY_PROTOCOL]||"",E1=o=>{if(!Object.prototype.hasOwnProperty.call(o,ge.NETWORK_TYPE))return gl.WIFI;switch(o[ge.NETWORK_TYPE]){case Pd.ETHERNET:return gl.ETHERNET;case Pd.CELLULAR_4G:return gl.CELLULAR_4G;case Pd.WIFI:return gl.WIFI;default:return gl.CELLULAR}},Nf=o=>!Object.prototype.hasOwnProperty.call(o,ge.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(o,ge.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:o[ge.FRAME_WIDTH]||null,height:o[ge.FRAME_HEIGHT]||null,framerate:o[ge.FRAMES_PER_SECOND]},C1=o=>{const n=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_REASON)?o[ge.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_RESOLUTION_CHANGES)?o[ge.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,a=Object.prototype.hasOwnProperty.call(o,ge.QUALITY_LIMITATION_DURATIONS)?o[ge.QUALITY_LIMITATION_DURATIONS]:null;return a&&Object.keys(a).forEach(c=>{a[c]>1e3&&(a[c]=Number(a[c]/1e3))}),{reason:n,durations:a,resolutionChanges:r}},A1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PLI)||!Object.prototype.hasOwnProperty.call(o,ge.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const a=(o[ge.PLI]||0)-(r?r[ie.VIDEO].total_pli_sent_in:0),c=(o[ge.NACK]||0)-(r?r[ie.VIDEO].total_nack_sent_in:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ie.VIDEO].total_pli_sent_in,deltaNackCount:c-n[ie.VIDEO].total_nack_sent_in}},I1=(o,n,r)=>{if(!Object.prototype.hasOwnProperty.call(o,ge.PLI)||!Object.prototype.hasOwnProperty.call(o,ge.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const a=(o[ge.PLI]||0)-(r?r[ie.VIDEO].total_pli_received_out:0),c=(o[ge.NACK]||0)-(r?r[ie.VIDEO].total_nack_received_out:0);return{pliCount:a,nackCount:c,deltaPliCount:a-n[ie.VIDEO].total_pli_received_out,deltaNackCount:c-n[ie.VIDEO].total_nack_received_out}},R1=o=>({channels:o[ge.CHANNELS]||null,clock_rate:o[ge.CLOCK_RATE]||null,mime_type:o[ge.MIME_TYPE]||null,sdp_fmtp_line:o[ge.SDP_FMTP_LINE]||null}),$1=o=>({clock_rate:o[ge.CLOCK_RATE]||null,mime_type:o[ge.MIME_TYPE]||null}),x1=(o,n,r)=>{const a=(o[ge.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),c=(o[ge.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),e=o[ge.TIMESTAMP]||Date.now(),_=a-n.data.total_KBytes_in,g=c-n.data.total_KBytes_out,d=r?r.timestamp:null;let A=n.timestamp;!A&&d&&(A=d);const S=A?e-A:0,R=S>0?_*.008*1024/S*1e3:0,N=S>0?g*.008*1024/S*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:c,delta_KBytes_received:_,delta_KBytes_sent:g,kbs_speed_received:R,kbs_speed_sent:N}},O1=o=>{const n=o[ge.AVAILABLE_INCOMING_BITRATE]/1024||0,r=o[ge.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:r}},k1=(o,n,r,a)=>{if(!o)return[];switch(o[ge.TYPE]){case Vr.CANDIDATE_PAIR:let c=!1;if(o[ge.NOMINATED]&&o[ge.STATE]===ie.SUCCEEDED&&(c=!0,Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o),ge.SELECTED in o&&!o[ge.SELECTED]&&(c=!1)),c){const _=o[ge.LOCAL_CANDIDATE_ID],g=o[ge.REMOTE_CANDIDATE_ID],d=x1(o,n,a),A=O1(o),S=T1(o,"data",a,n);return[{type:Me.NETWORK,value:{local_candidate_id:_}},{type:Me.NETWORK,value:{remote_candidate_id:g}},{type:Me.DATA,value:{total_KBytes_in:d.total_KBytes_received}},{type:Me.DATA,value:{total_KBytes_out:d.total_KBytes_sent}},{type:Me.DATA,value:{delta_KBytes_in:d.delta_KBytes_received}},{type:Me.DATA,value:{delta_KBytes_out:d.delta_KBytes_sent}},{type:Me.DATA,value:{delta_kbs_in:d.kbs_speed_received}},{type:Me.DATA,value:{delta_kbs_out:d.kbs_speed_sent}},{type:Me.DATA,value:{delta_kbs_bandwidth_in:A.kbs_incoming_bandwidth}},{type:Me.DATA,value:{delta_kbs_bandwidth_out:A.kbs_outgoing_bandwidth}},{type:Me.DATA,value:{delta_rtt_connectivity_ms:S.rtt}},{type:Me.DATA,value:{total_rtt_connectivity_ms:S.totalRTT}},{type:Me.DATA,value:{total_rtt_connectivity_measure:S.totalRTTMeasurements}}]}break;case Vr.LOCAL_CANDIDATE:if(o[ge.ID]===n.network.local_candidate_id)return[{type:Me.NETWORK,value:{infrastructure:E1(o)}},{type:Me.NETWORK,value:{local_candidate_type:o[ge.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{local_candidate_protocol:o[ge.PROTOCOL]||""}},{type:Me.NETWORK,value:{local_candidate_relay_protocol:S1(o)}}];break;case Vr.REMOTE_CANDIDATE:if(o[ge.ID]===n.network.remote_candidate_id)return[{type:Me.NETWORK,value:{remote_candidate_type:o[ge.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{remote_candidate_protocol:o[ge.PROTOCOL]||""}}];break;case Vr.INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const _=o[ge.SSRC],g=wn(_,n,Ht.INBOUND);g&&(g.timestamp=n.timestamp);const d=wn(_,a,Ht.INBOUND);if(d&&(d.timestamp=a.timestamp),o[ge.MEDIA_TYPE]===ie.AUDIO){const A=Df(o,ie.AUDIO,g,d),S=Bu(o,ie.AUDIO,g),R=o[ge.CODEC_ID]||"";return[{ssrc:_,type:Me.AUDIO,value:{codec_id_in:R}},{ssrc:_,type:Me.AUDIO,value:{total_packets_in:A.packetsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_in:A.deltaPacketsReceived}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_in:A.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_in:A.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_in:A.percentPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_in:A.KBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_in:A.deltaKBytesReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_in:A.kbsReceived}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_in:S}}]}if(o[ge.MEDIA_TYPE]===ie.VIDEO){const A=b1(o,g),S=Df(o,ie.VIDEO,g,d),R=Bu(o,ie.VIDEO,g),N=o[ge.DECODER_IMPLEMENTATION]||null,H=o[ge.CODEC_ID]||null,W=Nf(o),G=A1(o,g,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_in:H}},{ssrc:_,type:Me.VIDEO,value:{total_packets_in:S.packetsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_in:S.deltaPacketsReceived}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_in:S.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_in:S.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_in:S.percentPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_in:S.KBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_in:S.deltaKBytesReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_in:S.kbsReceived}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_in:R}},{ssrc:_,type:Me.VIDEO,value:{decoder_in:N}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_decode_frame_in:A.delta_ms_decode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_decoded_in:A.frames_decoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_decoded_in:A.total_decode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_sent_in:G.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_sent_in:G.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_sent_in:G.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_sent_in:G.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_in:W}}]}break}case Vr.OUTBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const _=o[ge.SSRC],g=wn(_,n,Ht.OUTBOUND);g&&(g.timestamp=n.timestamp);const d=wn(_,a,Ht.OUTBOUND);if(d&&(d.timestamp=a.timestamp),o[ge.MEDIA_TYPE]===ie.AUDIO){const A=o[ge.CODEC_ID]||null,S=Of(o,ie.AUDIO,g,d);return[{ssrc:_,type:Me.AUDIO,value:{codec_id_out:A}},{ssrc:_,type:Me.AUDIO,value:{total_packets_out:S.packetsSent}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_out:S.deltaPacketsSent}},{ssrc:_,type:Me.AUDIO,value:{total_KBytes_out:S.KBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_KBytes_out:S.deltaKBytesSent}},{ssrc:_,type:Me.AUDIO,value:{delta_kbs_out:S.kbsSent}}]}if(o[ge.MEDIA_TYPE]===ie.VIDEO){const A=o[ge.ENCODER_IMPLEMENTATION]||null,S=o[ge.CODEC_ID]||null,R=w1(o,g),N=Nf(o),H=C1(o),W=I1(o,g,d),G=Of(o,ie.VIDEO,g,d);return[{ssrc:_,type:Me.VIDEO,value:{codec_id_out:S}},{ssrc:_,type:Me.VIDEO,value:{total_packets_out:G.packetsSent}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_out:G.deltaPacketsSent}},{ssrc:_,type:Me.VIDEO,value:{total_KBytes_out:G.KBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_KBytes_out:G.deltaKBytesSent}},{ssrc:_,type:Me.VIDEO,value:{delta_kbs_out:G.kbsSent}},{ssrc:_,type:Me.VIDEO,value:{encoder_out:A}},{ssrc:_,type:Me.VIDEO,value:{delta_ms_encode_frame_out:R.delta_ms_encode_frame}},{ssrc:_,type:Me.VIDEO,value:{total_frames_encoded_out:R.frames_encoded}},{ssrc:_,type:Me.VIDEO,value:{total_time_encoded_out:R.total_encode_time}},{ssrc:_,type:Me.VIDEO,value:{total_nack_received_out:W.nackCount}},{ssrc:_,type:Me.VIDEO,value:{delta_nack_received_out:W.deltaNackCount}},{ssrc:_,type:Me.VIDEO,value:{total_pli_received_out:W.pliCount}},{ssrc:_,type:Me.VIDEO,value:{delta_pli_received_out:W.deltaPliCount}},{ssrc:_,type:Me.VIDEO,value:{size_out:N}},{ssrc:_,type:Me.VIDEO,value:{limitation_out:H}}]}break}case Vr.MEDIA_SOURCE:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);break}case Vr.TRACK:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);break}case Vr.CODEC:const e=[];return Object.keys(n[ie.AUDIO]).forEach(_=>{const g=n[ie.AUDIO][_];if(g.codec_id_in===o[ge.ID]||g.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=R1(o);o[ge.ID]===g.codec_id_in?e.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_in:d}}):e.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_out:d}})}}),Object.keys(n[ie.VIDEO]).forEach(_=>{const g=n[ie.VIDEO][_];if(g.codec_id_in===o[ge.ID]||g.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=$1(o);o[ge.ID]===g.codec_id_in?e.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_in:d}}):e.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_out:d}})}}),e;case Vr.REMOTE_INBOUND_RTP:{Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const _=o[ge.SSRC],g=wn(_,n,Ht.OUTBOUND),d=wn(_,a,Ht.OUTBOUND);if(o[ge.KIND]===ie.AUDIO){const A=xf(o,ie.AUDIO,d,g),S=Bu(o,ie.AUDIO,g),R=kf(o,ie.AUDIO,g,d);return[{ssrc:_,type:Me.AUDIO,value:{delta_rtt_ms_out:A.rtt}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_ms_out:A.totalRTT}},{ssrc:_,type:Me.AUDIO,value:{total_rtt_measure_out:A.totalRTTMeasurements}},{ssrc:_,type:Me.AUDIO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.AUDIO,value:{timestamp_out:o[ge.TIMESTAMP]}},{ssrc:_,type:Me.AUDIO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.AUDIO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.AUDIO,value:{percent_packets_lost_out:R.fractionLost}}]}if(o[ge.KIND]===ie.VIDEO){const A=xf(o,ie.VIDEO,d,g),S=Bu(o,ie.VIDEO,g),R=kf(o,ie.VIDEO,g,d);return[{ssrc:_,type:Me.VIDEO,value:{delta_rtt_ms_out:A.rtt}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_ms_out:A.totalRTT}},{ssrc:_,type:Me.VIDEO,value:{total_rtt_measure_out:A.totalRTTMeasurements}},{ssrc:_,type:Me.VIDEO,value:{delta_jitter_ms_out:S}},{ssrc:_,type:Me.VIDEO,value:{timestamp_out:o[ge.TIMESTAMP]}},{ssrc:_,type:Me.VIDEO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:_,type:Me.VIDEO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:_,type:Me.VIDEO,value:{percent_packets_lost_out:R.fractionLost}}]}break}}return[]},Vu=o=>o<0?1:o>100?4.5:1+.035*o+7/1e6*o*(o-60)*(100-o),D1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.INBOUND),_=wn(c,r,Ht.INBOUND),g=wn(c,a,Ht.INBOUND),d=[],A=[],S=e[n].percent_packets_lost_in,R=e[n].delta_jitter_ms_in,N=_&&_[n].delta_jitter_ms_in||null,H=g&&g[n].delta_jitter_ms_in||null,W=o.data.delta_rtt_connectivity_ms,G=r&&r.data.delta_rtt_connectivity_ms||null,K=a&&a.data.delta_rtt_connectivity_ms||null;W&&d.push(W),G&&d.push(G),K&&d.push(K),R&&A.push(R),r&&N&&A.push(N),a&&H&&A.push(H);const ae=d.length>0?mi(d):100,ee=A.length>0?mi(A):10,De=93.2-S,X=.18*De*De-27.9*De+1126.62,re=(ae+ee)/2,be=re-177.3<0?0:1,Ne=.024*re+.11*(re-177.3)*be,Q=X-Ne;return Vu(Q)},N1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.OUTBOUND),_=wn(c,r,Ht.OUTBOUND),g=wn(c,a,Ht.OUTBOUND),d=[],A=[],S=e[n].percent_packets_lost_out,R=e[n].delta_rtt_ms_out,N=_&&_[n].delta_rtt_ms_out||null,H=g&&g[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=g&&g[n].delta_jitter_ms_out||null,ae=o.data.delta_rtt_connectivity_ms,ee=r&&r.data.delta_rtt_connectivity_ms||null,De=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):ae&&d.push(ae),N?d.push(N):ee&&d.push(ee),H?d.push(H):De&&d.push(De),W&&A.push(W),r&&G&&A.push(G),a&&K&&A.push(K);const X=d.length>0?mi(d):100,re=A.length>0?mi(A):10,be=93.2-S,Ne=.18*be*be-27.9*be+1126.62,Q=(X+re)/2,ce=Q-177.3<0?0:1,me=.024*Q+.11*(Q-177.3)*ce,_e=Ne-me;return Vu(_e)},M1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.INBOUND),_=wn(c,r,Ht.INBOUND),g=wn(c,a,Ht.INBOUND),d=[],A=[],S=e[n].percent_packets_lost_in/100,R=e[n].delta_jitter_ms_in,N=_&&_[n].delta_jitter_ms_in||null,H=g&&g[n].delta_jitter_ms_in||null,W=o.data.delta_rtt_connectivity_ms,G=r&&r.data.delta_rtt_connectivity_ms||null,K=a&&a.data.delta_rtt_connectivity_ms||null;W&&d.push(W),G&&d.push(G),K&&d.push(K),R&&A.push(R),_&&N&&A.push(N),g&&H&&A.push(H);const ae=d.length>0?mi(d):100,ee=A.length>0?mi(A):10,De=0,X=19.8,re=29.7,be=30,Ne=(ae+ee)/2+be,Q=Ne-177.3<0?0:1,ce=.024*Ne+.11*(Ne-177.3)*Q,me=93.2-(De+X*Math.log(1+re*S)+ce);return Vu(me)},U1=(o,n=ie.AUDIO,r,a,c)=>{const e=wn(c,o,Ht.OUTBOUND),_=wn(c,r,Ht.OUTBOUND),g=wn(c,a,Ht.OUTBOUND),d=[],A=[],S=e[n].percent_packets_lost_out/100,R=e[n].delta_rtt_ms_out,N=_&&_[n].delta_rtt_ms_out||null,H=g&&g[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=g&&g[n].delta_jitter_ms_out||null,ae=o.data.delta_rtt_connectivity_ms,ee=r&&r.data.delta_rtt_connectivity_ms||null,De=a&&a.data.delta_rtt_connectivity_ms||null;R?d.push(R):ae&&d.push(ae),N?d.push(N):ee&&d.push(ee),H?d.push(H):De&&d.push(De),W&&A.push(W),_&&G&&A.push(G),g&&K&&A.push(K);const X=d.length>0?mi(d):100,re=A.length>0?mi(A):10,be=0,Ne=19.8,Q=29.7,ce=30,me=(X+re)/2+ce,_e=me-177.3<0?0:1,ue=.024*me+.11*(me-177.3)*_e,ye=93.2-(be+Ne*Math.log(1+Q*S)+ue);return Vu(ye)};class P1{constructor(n,r){this._callbacks={onreport:null,onticket:null},this._id=p1(),this._moduleName=this._id,this._probeId=r,this._config=n,this._exporter=new v1(n),this._state=Fs.IDLE,this.registerToPCEvents(),wa(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,r,a,c){const e=(d,A)=>d===ie.AUDIO?A===Vr.INBOUND_RTP?{...Ef}:{...Cf}:A===Vr.INBOUND_RTP?{...Af}:{...If},_=l1(r);_.pname=this._config.pname,_.call_id=this._config.cid,_.user_id=this._config.uid,_.count=r?r.count+1:1;let g=null;return n.forEach(d=>{!g&&d.timestamp&&(g=d.timestamp),k1(d,_,_.pname,c).forEach(A=>{if(A.value&&A.type)if(A.ssrc){let S=_[A.type][A.ssrc];S||(S=e(A.type,d.type),S.ssrc=A.ssrc,_[A.type][A.ssrc]=S),Object.keys(A.value).forEach(R=>{S[R]=A.value[R]})}else Object.keys(A.value).forEach(S=>{_[A.type][S]=A.value[S]})})}),_.timestamp=g,Object.keys(_[ie.AUDIO]).forEach(d=>{const A=_[ie.AUDIO][d];A.direction===Ht.INBOUND?(A.mos_emodel_in=D1(_,ie.AUDIO,r,a,A.ssrc),A.mos_in=M1(_,ie.AUDIO,r,a,A.ssrc)):(A.mos_emodel_out=N1(_,ie.AUDIO,r,a,A.ssrc),A.mos_out=U1(_,ie.AUDIO,r,a,A.ssrc))}),_}async takeReferenceStats(){return new Promise((n,r)=>{const a=Date.now();setTimeout(async()=>{try{const c=Date.now()-a,e=Date.now(),_=await this._config.pc.getStats(),g=this.analyze(_,null,null,null),d=Date.now();g.experimental.time_to_measure_ms=d-e,g.experimental.time_to_wait_ms=c,this._exporter.saveReferenceReport(g),Rt(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(c){r(c)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Fs.RUNNING||!this._config.pc)return Rt(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),r=await this._config.pc.getStats(),a=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),c=Date.now();return a.experimental.time_to_measure_ms=c-n,this._exporter.addReport(a),Rt(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(a),a}catch(n){return so(this._moduleName,`got error ${n}`),null}}async start(){Rt(this._moduleName,"starting"),this.state=Fs.RUNNING,this._startedTime=this._exporter.start(),Rt(this._moduleName,"started")}async mute(){this.state=Fs.MUTED,Rt(this._moduleName,"muted")}async unmute(){this.state=Fs.RUNNING,Rt(this._moduleName,"unmuted")}async stop(n){if(Rt(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Fs.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Rt(this._moduleName,"stopped")}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(this._moduleName,`registered callback '${n}'`)):so(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&qd(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&qd(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Rt(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,r,a,c){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:r,name:a,description:c})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const r=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${r.length} devices found`,"Media Devices state")}catch{so(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const a=n.iceConnectionState;a===ml.CONNECTED||a===ml.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.DISCONNECTED||a===ml.FAILED?this.addCustomEvent(new Date().toJSON(),"call",a,"ICE connection state"):a===ml.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const a=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",a,"ICE gathering state")},n.ontrack=a=>{this.addCustomEvent(new Date().toJSON(),"call",`${a.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=n.getReceivers();if(r&&r.length>0){const a=r[0],{transport:c}=a;if(c){const{iceTransport:e}=c;e&&(e.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class L1{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||h1(),this._moduleName=this._id,wa(this._moduleName,"probe created"),this._config=n,this._collector=new P1(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):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(n){this._collector.state=n}addCustomEvent(n,r,a,c=new Date().toJSON()){this._collector.addCustomEvent(c,r,n,a)}get isRunning(){return this._collector.state===Fs.RUNNING}get isIdle(){return this._collector.state===Fs.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Fu(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const jn="engine ";class q1{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},wa(jn,`configured for probing every ${this._config.refreshEvery}ms`),wa(jn,`configured for starting after ${this._config.startAfter}ms`),wa(jn,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Rt(jn,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,r){if(!n)throw new Error("undefined peer connection");const a=c1(n,r,this._config),c=new L1(a);return this._probes.push(c),Rt(jn,`${this._probes.length} probes registered`),c}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===Fs.RUNNING&&n.stop(),this._probes=this._probes.filter(r=>n.id!==r.id)}async start(){const n=()=>{this._probes.forEach(e=>e.start())},r=async()=>Promise.all(this._probes.map(e=>e.takeReferenceStats())),a=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,c=async()=>{const e=o1(),_=this._probes.filter(g=>g.isRunning);for(const g of _){const d=await g.collectStats();d&&e.probes.push(d),Rt(jn,`got probe ${g.id}`),await Rf(0)}return e.delta_time_to_measure_probes_ms=Sa(e.probes,"experimental","time_to_measure_ms"),e.delta_KBytes_in=Sa(e.probes,"data","delta_KBytes_in"),e.delta_KBytes_out=Sa(e.probes,"data","delta_KBytes_out"),e.delta_kbs_in=Sa(e.probes,"data","delta_kbs_in"),e.delta_kbs_out=Sa(e.probes,"data","delta_kbs_out"),e.total_time_decoded_in=Sa(e.probes,"video","total_time_decoded_in"),e.total_time_encoded_out=Sa(e.probes,"video","total_time_encoded_out"),e};for(Rt(jn,"starting to collect"),n(),Rt(jn,"generating reference reports..."),await r(),Rt(jn,"reference reports generated"),this._startedTime=Date.now();a();)if(Rt(jn,`wait ${this._config.refreshEvery}ms before collecting`),await Rf(this._config.refreshEvery),a()){Rt(jn,"collecting...");const e=Date.now(),_=await c(),g=Date.now();_.delta_time_consumed_to_measure_ms=g-e,this.fireOnReports(_),Rt(jn,"collected")}Rt(jn,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const r=a=>{this._probes.forEach(c=>{c.stop(a)})};wa(jn,"stop collecting"),r(n)}registerCallback(n,r,a){n in this._callbacks?(this._callbacks[n]={callback:r,context:a},Rt(jn,`registered callback '${n}'`)):so(jn,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Rt(this._moduleName,`unregistered callback '${n}'`)):so(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&qd(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const H1="interface ";class z1{constructor(n){this._config=d1(n),wa(H1,`welcome to ${this._config.name} version ${this._config.version}`),ZA(this._config.verbose||!1),this._engine=new q1(this._config)}setupLogLevel(n){e1(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,r){return this._engine.addNewProbe(n,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function F1(o,n){return Object.keys(o).filter(r=>n.includes(r)).reduce((r,a)=>{const c=a;return{...r,[c]:o[c]}},{})}const B1=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],V1={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class j1{constructor(n){this.intervals={},this.analysers={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}async start(n,r,a){r&&r.getTracks().length&&await this.beginCalculation(n,r,a)}stop(n){this.clearVolumeInterval(n),this.analysers[n]&&typeof this.analysers[n].disconnect=="function"&&(this.analysers[n].disconnect(),delete this.analysers[n])}clearVolumeInterval(n){this.intervals[n]&&(clearInterval(this.intervals[n]),delete this.intervals[n])}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{this.stop(n)}),this.intervals={},this.analysers={}}async beginCalculation(n,r,a){this.clearVolumeInterval(a);const c=n.createAnalyser(),e=n.createMediaStreamSource(r);c.smoothingTimeConstant=.8,c.fftSize=1024,e.connect(c),this.analysers[a]=c,this.intervals[a]=setInterval(()=>{const _=new Uint8Array(c.frequencyBinCount);c.getByteFrequencyData(_);let g=0;const d=_.length;for(let S=0;S<d;S++)g+=_[S];const A=g/d;this.onChangeFunction(a,A)},this.emitInterval)}}class G1{constructor(){this.resumePromise=null,this.context=new AudioContext}async getContext(){return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{throw this.resumePromise=null,n})),await this.resumePromise),this.context}}const ju={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},W1=0;class K1{constructor(n){var r;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.managedAudioContext=new G1,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new j1({onChangeFunction:this.emitVolumeChange.bind(this)}),this.initializeMediaDevices(),this.processVADConfiguration(((r=this.context.options.configuration)==null?void 0:r.noiseReductionOptions)||{}),this.setupVADInstance()}setVADConfiguration(n){if(!this.MicVAD)throw new Error("VAD module is not provided in the initial configuration");const r=Object.keys(n);for(const a of r)this.noiseReduction[a]=n[a];this.hasActiveCalls&&this.roomReconfigure(this.currentActiveRoomId)}setupVADInstance(){var n,r;const a=(r=(n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)==null?void 0:r.vadModule;a&&a.MicVAD?(this.MicVAD=a.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(n){this.noiseReduction={mode:n.mode||"disabled",checkEveryMs:n.checkEveryMs||500,noiseCheckInterval:n.noiseCheckInterval||2e3,noiseThreshold:n.noiseThreshold||.004,vadConfig:n.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}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(n=>!n.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return Tf()?{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(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(ju.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(ju.SELECTED_OUTPUT_DEVICE)||"default";try{const a=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),c=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(c),await this.setMicrophone(n),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}),a.getTracks().forEach(e=>e.stop())}catch(a){console.error(a)}}async cleanupConferenceNodes(n){const r=this.conferenceNodes[n];if(!r)return;let a=0;r.sources.forEach((_,g)=>{try{_.disconnect(),a++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting source ${g}:`,d)}});let c=0;r.destinations.forEach((_,g)=>{try{_.disconnect(),c++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${g}:`,d)}});let e=0;r.gains.forEach((_,g)=>{try{_.disconnect(),e++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${g}:`,d)}}),delete this.conferenceNodes[n]}setCallTime(n){const r={...n};delete r.callId,this.callTime={...this.callTime,[n.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const r={...this.callTime};delete r[n],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,r){this.timeIntervals={...this.timeIntervals,[n]:r}}removeTimeInterval(n){const r={...this.timeIntervals};r[n]&&(clearInterval(r[n]),delete r[n],this.timeIntervals={...r})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,r){this.context.emit("changeCallVolume",{callId:n,volume:r})}getNoiseReductionMode(){return this.noiseReduction.mode}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,r){if(!/^[A-D0-9*#]+$/g.test(r))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[n].sendDTMF(r)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const r=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(a=>a.enabled=!n),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:r,automatic:a}){const c=this.extendedCalls[n];if(!c)return;c._automaticHold=a??!1;const e=new Promise((_,g)=>{const d=setTimeout(()=>{g(new Error("Hold operation timeout"))},5e3),A=()=>{clearTimeout(d),c.putOnHoldTimestamp=r?Date.now():void 0,_()},S=R=>{clearTimeout(d),g(R)};try{r?(this.stopSessionVad(c._id),c.hold({},A)):c.unhold({},A)}catch(R){S(R)}});try{await e,this.updateCall(c);const _=Object.values(this.extendedCalls).filter(g=>g.roomId===c.roomId&&(r?n!==g._id:!0));_.length>1&&await this.doConference(_)}catch(_){throw console.error("Hold operation failed:",_),_}}holdCall(n,r=!1){return this.processHold({callId:n,automatic:r,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===W1).forEach(n=>this.terminateCall(n._id))}answerCall(n){const r=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",a=>{this.triggerAddStream(a,r)})}async moveCall(n,r){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:r}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=yf(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const r={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...r}},this.context.emit("updateRoom",{room:r,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const r=/answer-after=0/,a=n.request.getHeader("Call-Info");return a&&r.test(a)}addCall(n,r=!0){this.activeCalls={...this.activeCalls,[n._id]:yf(n)},this.extendedCalls[n._id]=n,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const r={...this.callStatus[n.callId]};n.isMoving!==void 0&&(r.isMoving=n.isMoving),n.isTransferring!==void 0&&(r.isTransferring=n.isTransferring),n.isMerging!==void 0&&(r.isMerging=n.isMerging),n.isTransferred!==void 0&&(r.isTransferred=n.isTransferred),this.callStatus={...this.callStatus,[n.callId]:{...r}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const r={...this.callStatus};delete r[n],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}async setupActiveStream(){const n=await Dd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n)}async getActiveStream(){const n=await Dd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:a})=>a===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(a=>a.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async a=>{await this.setupActiveStream();const c=this.activeStream;a.connection.getSenders()[0].replaceTrack(c.getTracks()[0]),this.updateCall(a)}):await this.doConference(r)}async setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:c})=>c===n))return;this.setSelectedOutputDevice(n);const r=Object.values(this.extendedCalls);if(r.length===0)return;const a=r.filter(c=>c.roomId===this.currentActiveRoomId);a.length===1?r.forEach(c=>{var e;(e=c.audioTag)==null||e.setSinkId(n),this.updateCall(c)}):await this.doConference(a)}removeRoom(n){const r={...this.activeRooms},a={...r[n]};delete r[n],this.activeRooms={...r},this.context.emit("removeRoom",{room:a,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}startNoiseMonitor({sessionId:n,stream:r,onNoiseDetected:a,onNoiseStop:c}){const e=new AudioContext,_=e.createMediaStreamSource(r.clone()),g=e.createAnalyser();g.fftSize=1024;const d=new Float32Array(g.fftSize);_.connect(g);const A=[];this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),this.vadIntervals[n]=null),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),this.vadMrsIntervals[n]=null),this.vadMrsIntervals[n]=setInterval(()=>{g.getFloatTimeDomainData(d);const S=KA(d);A.push(S);const R=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);A.length>R&&A.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[n]=setInterval(()=>{if(A.length===0)return;const S=A.reduce((H,W)=>H+W,0)/A.length,R=this.vadSessionsState[n],N=S>this.noiseReduction.noiseThreshold;R.isSpeaking||(N&&R.currentMode==="clean"?(R.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!0}),a()):!N&&R.currentMode==="noisy"&&(R.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!1}),c()))},this.noiseReduction.noiseCheckInterval)}async processVAD(n,r){const a=r.clone();this.stopSessionVad(n._id),this.vadSessionsState[n._id]={currentMode:"clean",isSpeaking:!1};const c=await this.managedAudioContext.getContext(),e=await YA(a,c,150);let _=!1;const g=await this.MicVAD.new({getStream:()=>new Promise(d=>d(a)),...V1,...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:()=>{if(!_){if(_=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){n.connection.getSenders()[0]&&n.connection.getSenders()[0].replaceTrack(e.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:n._id,stream:a,onNoiseDetected:async()=>{var d;console.log("Replace track with Vad Controlled"),await((d=n.connection.getSenders()[0])==null?void 0:d.replaceTrack(e.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const d=n.connection.getSenders()[0];d&&d.track&&d.transport&&d.transport.state!=="closed"&&d.transport.state!=="failed"&&(console.log("Replace track with Original"),await d.replaceTrack(a.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var d;console.log("🎤 Speech started"),e.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((d=n.connection.getSenders()[0])==null||d.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!0},onSpeechEnd:()=>{var d;console.log("🛑 Speech end"),e.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((d=n.connection.getSenders()[0])==null||d.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!1}});this.vadSessions[n._id]&&(this.vadSessions[n._id].pause(),delete this.vadSessions[n._id]),this.vadSessions[n._id]=g,g.start()}stopSessionVad(n){this.vadSessions[n]&&(this.vadSessions[n].pause(),delete this.vadSessions[n]),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]),this.vadSessionsState[n]&&delete this.vadSessionsState[n]}async roomReconfigure(n){var r;if(n===void 0)return;const a=Object.values(this.extendedCalls).filter(e=>e.roomId===n),c=this.currentActiveRoomId===n;if(a.forEach((e,_)=>{if(e.audioTag){e.connection.getReceivers().forEach(d=>{d.track.enabled=!e.localMuted}),c&&this.muteReconfigure(e);const g=!c;e.audioTag.muted=g,this.updateCall(e)}}),a.length===0){this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n),this.deleteRoomIfEmpty(n);return}if(a.length===1&&!c){const e=a[0];e.isOnHold().local||await this.holdCall(e._id,!0),this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}if(a.length===1&&c){const e=a[0];e.isOnHold().local&&e._automaticHold&&await this.unholdCall(e._id);const _=(((r=e.connection)==null?void 0:r.getSenders())||[])[0];if(e.connection&&_)try{await this.setupActiveStream();const g=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(a[0],g);const d=g.getTracks();await _.replaceTrack(d[0]),this.muteReconfigure(e)}catch(g){console.error(g)}this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}a.length>1&&await this.doConference(a)}async doConference(n){if(n.length===0)return;const r=n[0].roomId,a=this.currentActiveRoomId===r;if(n.find(g=>g.roomId!==r))return;const c=await this.managedAudioContext.getContext();if(c.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${c.state}`);return}await this.cleanupConferenceNodes(r),this.conferenceNodes[r]={sources:new Map,destinations:new Map,gains:new Map};const e=this.conferenceNodes[r],_=new Map;n.forEach((g,d)=>{g&&g.connection&&g.connection.getReceivers().forEach((A,S)=>{var R,N,H;A.track.enabled=!g.localMuted;const W=(R=A.track)==null?void 0:R.id;(N=A.track)==null||N.readyState,(H=A.track)==null||H.kind;const G=`${g._id}-${W}`;A.track&&A.track.readyState==="live"&&_.set(G,A.track)})}),await this.setupActiveStream(),await XA.forEach(n,async(g,d)=>{if(!g||!g.connection)return;const A=c.createMediaStreamDestination();e.destinations.set(g._id,A);let S=0;if(_.forEach((H,W)=>{if(!W.startsWith(g._id))try{const G=c.createMediaStreamSource(new MediaStream([H])),K=c.createGain(),ae=`${g._id}-${W}`;G.connect(K),K.connect(A),e.sources.set(ae,G),e.gains.set(ae,K),S++}catch(G){console.error(G)}}),a&&this.activeStreamValue)try{const H=this.activeStream,W=c.createMediaStreamSource(H),G=c.createGain(),K=`${g._id}-local`;W.connect(G),G.connect(A),e.sources.set(K,W),e.gains.set(K,G)}catch(H){console.error(H)}else a&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${g._id}`);const R=g.connection.getSenders()[0],N=A.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(g,A.stream),R&&N[0])try{await R.replaceTrack(N[0]),this.muteReconfigure(g)}catch(H){console.error(H)}})}processCallerMute(n,r){const a=this.extendedCalls[n];a&&a.connection.getReceivers().length&&(a.localMuted=r,a.connection.getReceivers().forEach(c=>{c.track.enabled=!r}),this.updateCall(a))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const r=this.extendedCalls[n];r._status===4?r.terminate({status_code:603,reason_phrase:"Decline"}):r._status!==8&&r.terminate()}transferCall(n,r){if(r.toString().length===0)return new Error("Target must be passed");const a=this.extendedCalls[n];if(!a._is_confirmed&&!a._is_canceled){const c=`sip:${r}@${this.context.sipDomain}`;a.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${c}`]});return}this.updateCallStatus({callId:n,isTransferring:!0,isTransferred:!1}),a.refer(`sip:${r}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(a)}mergeCall(n){const r=Object.values(this.extendedCalls).filter(e=>e.roomId===n);if(r.length!==2)return;const a=r[0],c=r[1];!a||!c||(this.updateCallStatus({callId:a._id,isMerging:!0}),this.updateCallStatus({callId:c._id,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a))}mergeCallByIds(n,r){const a=Object.values(this.extendedCalls).find(e=>e._id===n),c=Object.values(this.extendedCalls).find(e=>e._id===r);if(!a||!c)throw new Error("Call ID is not provided");this.updateCallStatus({callId:n,isMerging:!0}),this.updateCallStatus({callId:r,isMerging:!0}),a.refer(c.remote_identity.uri.toString(),{replaces:c}),this.updateCall(a)}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}setCallWaiting(n){this.isCallWaitingEnabled=n,this.context.emit("changeIsCallWaiting",n)}startCallTimer(n){this.removeTimeInterval(n);const r={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const a=setInterval(()=>{const c={...this.callTime[n]},e=WA(c);this.setCallTime({callId:n,...e})},1e3);this.setTimeInterval(n,a)}async setActiveRoom(n){const r=this.currentActiveRoomId;n!==r&&(this.currentActiveRoomId=n,await this.roomReconfigure(r),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var r,a;const c=n.session;if(this.getActiveCalls[c.id]!==void 0)return;const e=this.getNewRoomId(),_={started:new Date,incomingInProgress:!1,roomId:e};if(c.direction==="incoming")this.context.logger.log("New incoming call from",(a=(r=c._remote_identity)==null?void 0:r._uri)==null?void 0:a._user),_.incomingInProgress=!0,this.context.subscribe(Br.CALL_CONFIRMED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.startCallTimer(c.id))}),this.context.subscribe(Br.CALL_FAILED,S=>{c.id===S.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.deleteRoomIfEmpty(e))});else if(c.direction==="outgoing"){const S=R=>{R.response&&R.response.status_code===JA.SESSION_PROGRESS&&(this.startCallTimer(c.id),c.off("progress",S))};c.on("progress",S),c.once("confirmed",()=>{this.startCallTimer(c.id)})}const g=c,d=this.hasAutoAnswerHeaders(n),A=g.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);g.roomId=e,g.localMuted=!1,g.autoAnswer=A,A?this.addCall(g,!1):this.addCall(g),this.addCallStatus(c.id),this.addRoom(_),A&&this.answerCall(g._id)}removeCall(n){const r={...this.activeCalls};delete r[n],this.activeCalls={...r};const a={...this.extendedCalls};delete a[n],this.extendedCalls={...a},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const r=this.extendedCalls[n._id];if(!r)return;this.stopVUMeter("origin"),this.stopVUMeter(n._id);const a=r.roomId;this.removeCall(n._id),this.roomReconfigure(a).then(()=>{}).catch(c=>{console.error("Error reconfiguring room after call removal:",c)})}shouldTerminateNewSession(n){if(n.session.direction==="outgoing")return!1;const r=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||r}async newRTCSessionCallback(n){const r=n.session;if(this.shouldTerminateNewSession(n)){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}this.context.triggerListener({listenerType:Br.NEW_CALL,session:r,event:n}),r.on("ended",c=>{var e,_,g;if(this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_ENDED,session:r,event:c}),r.connection){const A=r.connection.connectionState;(A==="closed"||A==="disconnected")&&this.context.emit("connectionStateChange",A)}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(A=>A.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("progress",c=>{var e,_;this.context.logger.log("Session in progress for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_PROGRESS,session:r,event:c})}),r.on("failed",c=>{var e,_,g;if(this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_FAILED,session:r,event:c}),r.connection){const A=r.connection.connectionState;(A==="closed"||A==="disconnected")&&this.context.emit("connectionStateChange",A)}["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const d=this.getActiveCalls[r.id];d&&this.activeCallListRemove(d),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(A=>A.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("confirmed",c=>{var e,_;this.context.logger.log("Session confirmed for",(_=(e=r._remote_identity)==null?void 0:e._uri)==null?void 0:_._user),this.context.triggerListener({listenerType:Br.CALL_CONFIRMED,session:r,event:c}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)});const a=c=>{c&&c.addEventListener("connectionstatechange",e=>{this.context.emit("connectionStateChange",c.connectionState)})};if(r.connection&&a(r.connection),r.on("peerconnection",({peerconnection:c})=>{a(c)}),await this.setupCall(n),r.direction==="outgoing"){const c=this.getActiveCalls[r.id].roomId;await this.setActiveRoom(c)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=n,this.updateCall(r))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(ju.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(ju.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const r={...n};delete r.callId,this.callMetrics={...this.callMetrics,[n.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const r={...this.callMetrics};delete r[n],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const r=new z1(this.metricConfig),a=r.createProbe(n.connection,{cid:n._id}),c=[];let e;a.onreport=_=>{Object.entries(_.audio).forEach(([A,S])=>{S.direction==="inbound"&&!c.includes(A)&&(c.push(A),e=A)});const g=_.audio[e];if(!g)return;const d=F1(g,B1);d.callId=n._id,this.setCallMetrics(d)},this.context.subscribe(Br.CALL_ENDED,_=>{_._id===n._id&&r.stopAllProbes()}),r.startAllProbes()}async setupVUMeter(n,r){await this.VUMeter.start(await this.managedAudioContext.getContext(),n,r)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){try{const n=Date.now(),r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((a,c)=>{a.stop()}),this.initialStreamValue=null),this.initialStreamValue=r}catch(n){throw n}}async triggerAddStream(n,r){const a=this.muteWhenJoin||this.isMuted;this.setIsMuted(a),this.initialStreamValue||await this.setupStream();const c=await this.managedAudioContext.getContext(),e=await Dd(c,this.initialStreamValue,this.microphoneInputLevel*2),_=this.isMuted||this.muteWhenJoin;e.getTracks().forEach(A=>{A.enabled=!_}),await this.setActiveStream(e),await r.connection.getSenders()[0].replaceTrack(e.getTracks()[0]);const g=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(A=>A.audioTag&&A.audioTag.id===r._id)&&kA(g,r,this.selectedOutputDevice,this.speakerVolume);const d=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!d),await this.setupVUMeter(g,r._id),this.getCallQuality(r),this.updateCall(r),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r,e)}initCall(n,r,a=!1){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const c=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=c.id,r&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:c.id,roomId:this.currentActiveRoomId}),a)){const e=Object.values(this.extendedCalls).filter(_=>_.roomId===this.currentActiveRoomId&&_._id!==c.id);for(const _ of e)this.holdCall(_._id,!0)}c.connection.addEventListener("track",e=>{this.triggerAddStream(e,c)})}async processRoomChange({callId:n,roomId:r}){const a=this.extendedCalls[n];if(!a)return;const c=a.roomId;a.roomId=r,this.updateCall(a),await this.roomReconfigure(c),await this.roomReconfigure(r)}}class Y1{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n,r){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,r,this.sipOptions)}stop(n={}){this.context.terminateJanusSessions(n)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(n){this.context.changeMediaConstraints(n)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class X1{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const r=this.extendedMessages[n];this.updateMSRPSession(r)}updateMSRPSession(n){this.activeMessages[n._id]=vf(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:vf(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,r){const a=this.msrpHistory[r.id]||[];a.push(n),this.msrpHistory={...this.msrpHistory,[r.id]:[...a]},this.context.emit("newMSRPMessage",{message:n,session:r})}messageTerminate(n){const r=this.extendedMessages[n];r._status!==8&&r.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const r=n;this.addMMSRPSession(r)}triggerMSRPListener({listenerType:n,session:r,event:a}){const c=this.context.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}removeMMSRPSession(n){const r={...this.activeMessages};delete r[n],this.activeMessages={...r};const a={...this.extendedMessages};delete a[n],this.extendedMessages={...a},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){n.session._id||(n.session._id=n.request.call_id+n.request.from._parameters.tag);const r=n.session;r.on("ended",a=>{this.triggerMSRPListener({listenerType:Br.CALL_ENDED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("failed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_FAILED,session:r,event:a});const c=this.getActiveMessages[r.id];this.activeMessageListRemove(c)}),r.on("confirmed",a=>{this.triggerMSRPListener({listenerType:Br.CALL_CONFIRMED,session:r,event:a}),this.updateMSRPSession(r)}),r.on("newMessage",a=>{this.addMSRPMessage(a,r)}),this.addMessageSession(r)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,r,a){if(n.length===0)return console.error("Target must be a valid string");const c=this.context.startMSRP(n,a);c.on("active",()=>{this.addMessageSession(c),c.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,r){const a=this.extendedMessages[n];if(!a)throw new Error(`MSRP session with id ${n} doesn't exist!`);a.sendMSRP(r)}}const Gu={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Mf{constructor(n){this.opensips=null,this.session=null,this.name=null,this.name=n}setOpensips(n){this.opensips=n}setSession(n){this.session=n}kill(){this.opensips.kill(this.name)}}class J1 extends Mf{constructor(n,r){super(n),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=r}connect(n={}){this.opaqueId=this.session.generateOpaqueId();const r=kt.cloneArray(n.extraHeaders),a={from_tag:this.session._from_tag};n.fromUserName&&(a.from_uri=new ba("sip",n.fromUserName,this.session._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(a.from_display_name=n.fromDisplayName),r.push(`Contact: ${this.session._contact}`),r.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&r.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new On.InitialOutgoingInviteRequest(this.session.target,this.session._ua,a,r),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 n;this._connection.onicecandidate=r=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||r.candidate&&(this._candidates.push(r.candidate),clearTimeout(n),n=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(n){n.forEach(r=>{this._connection.addTrack(r)})}async _sendInitialRequest(){const n=new sl(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const r={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(r),await this._connection.setLocalDescription(this.jsep_offer);const a={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},c=JSON.stringify(a);this._request.body=c,n.send()}_receiveInviteResponse(n){if(this._publisherSubscribeSent||!n.body)return;const r=JSON.parse(n.body);this.handleId=r.data.id;const a={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},c=[this.session.getPTypeHeader(ir.PUBLISHER)];this.session.sendRequest(oe.SUBSCRIBE,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{var _,g,d,A;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((g=(_=S.plugindata)==null?void 0:_.data)==null?void 0:g.videoroom)==="joined"&&this.session.myFeedList.push(S.plugindata.data.id),(A=(d=S.plugindata)==null?void 0:d.data)!=null&&A.publishers&&this.session.receivePublishers(S)}catch(S){console.error(S)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(n){const r=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handleId,session_id:this.session.session_id})),a={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...n},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...r]},c=["Content-Type: application/json",this.session.getPTypeHeader(ir.ICE)];this.session.sendRequest(oe.INFO,{extraHeaders:c,body:JSON.stringify(a),eventHandlers:{onSuccessResponse:async e=>{this._configureSent=!0;const _=e.data.split(`\r
|
|
159
|
+
`),g=_[_.length-1],d=JSON.parse(g);await this._connection.setRemoteDescription(d.jsep),this._candidates=[]}}})}_sendDetach(){const n={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},r=[this.session.getPTypeHeader(ir.DETACH)];this.session.sendRequest(oe.INFO,{extraHeaders:r,body:JSON.stringify(n)}),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 n=this._connection.getSenders();n.forEach(r=>{const a=r.track;a&&a.stop()}),n.forEach(r=>{this._connection.removeTrack(r)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class Q1 extends Mf{constructor(n,r,a={}){super(n),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=a.immediate||!1,this.type=r}start(n){return n}stop(){throw new Error("stop method is not implemented")}async process(n){if(this.immediate){const r=await this.start(n);return this.running=!0,r}return n}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 Z1 extends CA{constructor(n,r){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const a={...n.configuration,sockets:n.socketInterfaces.map(c=>new GA.WebSocketInterface(c))};super(a),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=[],n.pnExtraHeaders&&Object.keys(n.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(n.pnExtraHeaders),this.options=n,this.modules=n.modules,n.configuration.reconnectionAttemptsLimit&&(this.reconnectionAttemptsLimit=n.configuration.reconnectionAttemptsLimit),r&&DA(r)&&(this.logger=r)}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(Gu.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(n,r){return super.on(n,r)}off(n,r){return super.off(n,r)}emit(n,r){return super.emit(n,r)}get sipDomain(){return this.options.sipDomain}use(n){if(this.newStreamPlugins.find(r=>r.name===n.name)||this.processStreamPlugins.find(r=>r.name===n.name))throw new Error(`Plugin with name ${n.name} already exists`);if(n instanceof J1)n.setOpensips(this),this.newStreamPlugins.push(n);else if(n instanceof Q1)n.setOpensips(this),this.processStreamPlugins.push(n);else throw new Error("Wrong plugin instance")}getPlugin(n){return this.newStreamPlugins.find(r=>r.name===n)||this.processStreamPlugins.find(r=>r.name===n)}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(Gu.AUDIO)&&(this.audio=new K1(this)),this.modules.includes(Gu.MSRP)&&(this.msrp=new X1(this)),this.modules.includes(Gu.VIDEO)&&(this.video=new Y1(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(n,r){const a=!this.listenersList[n]||!this.listenersList[n].length?[r]:[...this.listenersList[n],r];this.listenersList={...this.listenersList,[n]:a}}removeIListener(n){const r={...this.listenersList};delete r[n],this.listenersList={...r}}triggerListener({listenerType:n,session:r,event:a}){const c=this.listenersList[n];!c||!c.length||c.forEach(e=>{e(r,a)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}setConnected(n){this.connected=n,this.emit("connection",n)}setReconnecting(n){this.isReconnecting=n,this.emit("reconnecting",n)}}var Gn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function eI(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var Hd={},Tl={};Object.defineProperty(Tl,"__esModule",{value:!0}),Tl.baseAssetPath=void 0;const Uf=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let Pf="/";Uf&&(Pf=Uf.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),Tl.baseAssetPath=Pf;var io={};Object.defineProperty(io,"__esModule",{value:!0}),io.defaultModelFetcher=void 0;const tI=o=>fetch(o).then(n=>n.arrayBuffer());io.defaultModelFetcher=tI;var us={},ao={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.log=o.LOG_PREFIX=void 0,o.LOG_PREFIX="[VAD]";const n=["error","debug","warn"];function r(c){return(...e)=>{console[c](o.LOG_PREFIX,...e)}}const a=n.reduce((c,e)=>(c[e]=r(e),c),{});o.log=a})(ao);var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.Message=void 0;var Lf;(function(o){o.AudioFrame="AUDIO_FRAME",o.SpeechStart="SPEECH_START",o.VADMisfire="VAD_MISFIRE",o.SpeechEnd="SPEECH_END",o.SpeechStop="SPEECH_STOP",o.SpeechRealStart="SPEECH_REAL_START",o.FrameProcessed="FRAME_PROCESSED"})(Lf||(Ea.Message=Lf={})),Object.defineProperty(us,"__esModule",{value:!0}),us.FrameProcessor=us.validateOptions=us.defaultFrameProcessorOptions=void 0;const bl=ao,Ca=Ea;us.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function nI(o){(o.positiveSpeechThreshold<0||o.positiveSpeechThreshold>1)&&bl.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(o.negativeSpeechThreshold<0||o.negativeSpeechThreshold>o.positiveSpeechThreshold)&&bl.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),o.preSpeechPadMs<0&&bl.log.error("preSpeechPadMs should be positive"),o.redemptionMs<0&&bl.log.error("redemptionMs should be positive"),o.minSpeechMs<0&&bl.log.error("minSpeechMs should be positive")}us.validateOptions=nI;const qf=o=>{const n=o.reduce((a,c)=>(a.push(a.at(-1)+c.length),a),[0]),r=new Float32Array(n.at(-1));return o.forEach((a,c)=>{const e=n[c];r.set(a,e)}),r};class rI{constructor(n,r,a,c){this.modelProcessFunc=n,this.modelResetFunc=r,this.options=a,this.msPerFrame=c,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=e=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(e):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=e=>{const _=this.audioBuffer;this.audioBuffer=[];const g=this.speaking;if(this.reset(),g)if(_.reduce((A,S)=>S.isSpeech?A+1:A,0)>=this.minSpeechFrames){const A=qf(_.map(S=>S.frame));e({msg:Ca.Message.SpeechEnd,audio:A})}else e({msg:Ca.Message.VADMisfire});return{}},this.process=async(e,_)=>{if(!this.active)return;const g=await this.modelProcessFunc(e),d=g.isSpeech>=this.options.positiveSpeechThreshold;if(_({probs:g,msg:Ca.Message.FrameProcessed,frame:e}),this.audioBuffer.push({frame:e,isSpeech:d}),d&&(this.speechFrameCount++,this.redemptionCounter=0),d&&!this.speaking&&(this.speaking=!0,_({msg:Ca.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,_({msg:Ca.Message.SpeechRealStart})),g.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const A=this.audioBuffer;if(this.audioBuffer=[],A.reduce((R,N)=>N.isSpeech?R+1:R,0)>=this.minSpeechFrames){const R=qf(A.map(N=>N.frame));_({msg:Ca.Message.SpeechEnd,audio:R})}else _({msg:Ca.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[],this.redemptionFrames=Math.floor(a.redemptionMs/this.msPerFrame),this.preSpeechPadFrames=Math.floor(a.preSpeechPadMs/this.msPerFrame),this.minSpeechFrames=Math.floor(a.minSpeechMs/this.msPerFrame),this.reset()}}us.FrameProcessor=rI;var Hf={};function oo(o){throw new Error('Could not dynamically require "'+o+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var zf={exports:{}};/*!
|
|
160
160
|
* ONNX Runtime Web v1.23.2
|
|
161
161
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
162
162
|
* Licensed under the MIT License.
|
|
163
|
-
*/(function(o,n){var r=(()=>{var a=Object.defineProperty,c=Object.getOwnPropertyDescriptor,e=Object.getOwnPropertyNames,f=Object.prototype.hasOwnProperty,g=(s=>typeof oo<"u"?oo:typeof Proxy<"u"?new Proxy(s,{get:(u,p)=>(typeof oo<"u"?oo:u)[p]}):s)(function(s){if(typeof oo<"u")return oo.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')}),d=(s,u)=>()=>(s&&(u=s(s=0)),u),A=(s,u)=>{for(var p in u)a(s,p,{get:u[p],enumerable:!0})},S=(s,u,p,m)=>{if(u&&typeof u=="object"||typeof u=="function")for(let y of e(u))!f.call(s,y)&&y!==p&&a(s,y,{get:()=>u[y],enumerable:!(m=c(u,y))||m.enumerable});return s},R=s=>S(a({},"__esModule",{value:!0}),s),N,H,W,G,K,ae=d(()=>{N=new Map,H=[],W=(s,u,p)=>{if(u&&typeof u.init=="function"&&typeof u.createInferenceSessionHandler=="function"){let m=N.get(s);if(m===void 0)N.set(s,{backend:u,priority:p});else{if(m.priority>p)return;if(m.priority===p&&m.backend!==u)throw new Error(`cannot register backend "${s}" using priority ${p}`)}if(p>=0){let y=H.indexOf(s);y!==-1&&H.splice(y,1);for(let T=0;T<H.length;T++)if(N.get(H[T]).priority<=p){H.splice(T,0,s);return}H.push(s)}return}throw new TypeError("not a valid backend")},G=async s=>{let u=N.get(s);if(!u)return"backend not found.";if(u.initialized)return u.backend;if(u.aborted)return u.error;{let p=!!u.initPromise;try{return p||(u.initPromise=u.backend.init(s)),await u.initPromise,u.initialized=!0,u.backend}catch(m){return p||(u.error=`${m}`,u.aborted=!0),u.error}finally{delete u.initPromise}}},K=async s=>{let u=s.executionProviders||[],p=u.map(E=>typeof E=="string"?E:E.name),m=p.length===0?H:p,y,T=[],b=new Set;for(let E of m){let C=await G(E);typeof C=="string"?T.push({name:E,err:C}):(y||(y=C),y===C&&b.add(E))}if(!y)throw new Error(`no available backend found. ERR: ${T.map(E=>`[${E.name}] ${E.err}`).join(", ")}`);for(let{name:E,err:C}of T)p.includes(E)&&console.warn(`removing requested execution provider "${E}" from session options because it is not available: ${C}`);let w=u.filter(E=>b.has(typeof E=="string"?E:E.name));return[y,new Proxy(s,{get:(E,C)=>C==="executionProviders"?w:Reflect.get(E,C)})]}}),ee=d(()=>{ae()}),De,X=d(()=>{De="1.23.2"}),re,be,Ne=d(()=>{X(),re="warning",be={wasm:{},webgl:{},webgpu:{},versions:{common:De},set logLevel(s){if(s!==void 0){if(typeof s!="string"||["verbose","info","warning","error","fatal"].indexOf(s)===-1)throw new Error(`Unsupported logging level: ${s}`);re=s}},get logLevel(){return re}},Object.defineProperty(be,"logLevel",{enumerable:!0})}),Q,ce=d(()=>{Ne(),Q=be}),me,_e,ue=d(()=>{me=(s,u)=>{let p=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);p.width=s.dims[3],p.height=s.dims[2];let m=p.getContext("2d");if(m!=null){let y,T;u?.tensorLayout!==void 0&&u.tensorLayout==="NHWC"?(y=s.dims[2],T=s.dims[3]):(y=s.dims[3],T=s.dims[2]);let b=u?.format!==void 0?u.format:"RGB",w=u?.norm,E,C;w===void 0||w.mean===void 0?E=[255,255,255,255]:typeof w.mean=="number"?E=[w.mean,w.mean,w.mean,w.mean]:(E=[w.mean[0],w.mean[1],w.mean[2],0],w.mean[3]!==void 0&&(E[3]=w.mean[3])),w===void 0||w.bias===void 0?C=[0,0,0,0]:typeof w.bias=="number"?C=[w.bias,w.bias,w.bias,w.bias]:(C=[w.bias[0],w.bias[1],w.bias[2],0],w.bias[3]!==void 0&&(C[3]=w.bias[3]));let $=T*y,x=0,O=$,k=$*2,D=-1;b==="RGBA"?(x=0,O=$,k=$*2,D=$*3):b==="RGB"?(x=0,O=$,k=$*2):b==="RBG"&&(x=0,k=$,O=$*2);for(let P=0;P<T;P++)for(let F=0;F<y;F++){let L=(s.data[x++]-C[0])*E[0],U=(s.data[O++]-C[1])*E[1],V=(s.data[k++]-C[2])*E[2],B=D===-1?255:(s.data[D++]-C[3])*E[3];m.fillStyle="rgba("+L+","+U+","+V+","+B+")",m.fillRect(F,P,1,1)}if("toDataURL"in p)return p.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},_e=(s,u)=>{let p=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),m;if(p!=null){let y,T,b;u?.tensorLayout!==void 0&&u.tensorLayout==="NHWC"?(y=s.dims[2],T=s.dims[1],b=s.dims[3]):(y=s.dims[3],T=s.dims[2],b=s.dims[1]);let w=u!==void 0&&u.format!==void 0?u.format:"RGB",E=u?.norm,C,$;E===void 0||E.mean===void 0?C=[255,255,255,255]:typeof E.mean=="number"?C=[E.mean,E.mean,E.mean,E.mean]:(C=[E.mean[0],E.mean[1],E.mean[2],255],E.mean[3]!==void 0&&(C[3]=E.mean[3])),E===void 0||E.bias===void 0?$=[0,0,0,0]:typeof E.bias=="number"?$=[E.bias,E.bias,E.bias,E.bias]:($=[E.bias[0],E.bias[1],E.bias[2],0],E.bias[3]!==void 0&&($[3]=E.bias[3]));let x=T*y;if(u!==void 0&&(u.format!==void 0&&b===4&&u.format!=="RGBA"||b===3&&u.format!=="RGB"&&u.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let O=4,k=0,D=1,P=2,F=3,L=0,U=x,V=x*2,B=-1;w==="RGBA"?(L=0,U=x,V=x*2,B=x*3):w==="RGB"?(L=0,U=x,V=x*2):w==="RBG"&&(L=0,V=x,U=x*2),m=p.createImageData(y,T);for(let Y=0;Y<T*y;k+=O,D+=O,P+=O,F+=O,Y++)m.data[k]=(s.data[L++]-$[0])*C[0],m.data[D]=(s.data[U++]-$[1])*C[1],m.data[P]=(s.data[V++]-$[2])*C[2],m.data[F]=B===-1?255:(s.data[B++]-$[3])*C[3]}else throw new Error("Can not access image data");return m}}),ye,Re,J,Se,$e,zt,Ae=d(()=>{Yt(),ye=(s,u)=>{if(s===void 0)throw new Error("Image buffer must be defined");if(u.height===void 0||u.width===void 0)throw new Error("Image height and width must be defined");if(u.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:p,width:m}=u,y=u.norm??{mean:255,bias:0},T,b;typeof y.mean=="number"?T=[y.mean,y.mean,y.mean,y.mean]:T=[y.mean[0],y.mean[1],y.mean[2],y.mean[3]??255],typeof y.bias=="number"?b=[y.bias,y.bias,y.bias,y.bias]:b=[y.bias[0],y.bias[1],y.bias[2],y.bias[3]??0];let w=u.format!==void 0?u.format:"RGBA",E=u.tensorFormat!==void 0&&u.tensorFormat!==void 0?u.tensorFormat:"RGB",C=p*m,$=E==="RGBA"?new Float32Array(C*4):new Float32Array(C*3),x=4,O=0,k=1,D=2,P=3,F=0,L=C,U=C*2,V=-1;w==="RGB"&&(x=3,O=0,k=1,D=2,P=-1),E==="RGBA"?V=C*3:E==="RBG"?(F=0,U=C,L=C*2):E==="BGR"&&(U=0,L=C,F=C*2);for(let B=0;B<C;B++,O+=x,D+=x,k+=x,P+=x)$[F++]=(s[O]+b[0])/T[0],$[L++]=(s[k]+b[1])/T[1],$[U++]=(s[D]+b[2])/T[2],V!==-1&&P!==-1&&($[V++]=(s[P]+b[3])/T[3]);return E==="RGBA"?new wt("float32",$,[1,4,p,m]):new wt("float32",$,[1,3,p,m])},Re=async(s,u)=>{let p=typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement,m=typeof ImageData<"u"&&s instanceof ImageData,y=typeof ImageBitmap<"u"&&s instanceof ImageBitmap,T=typeof s=="string",b,w=u??{},E=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},C=$=>typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||$ instanceof OffscreenCanvas?$.getContext("2d"):null;if(p){let $=E();$.width=s.width,$.height=s.height;let x=C($);if(x!=null){let O=s.height,k=s.width;if(u!==void 0&&u.resizedHeight!==void 0&&u.resizedWidth!==void 0&&(O=u.resizedHeight,k=u.resizedWidth),u!==void 0){if(w=u,u.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");w.tensorFormat="RGBA",w.height=O,w.width=k}else w.tensorFormat="RGBA",w.height=O,w.width=k;x.drawImage(s,0,0),b=x.getImageData(0,0,k,O).data}else throw new Error("Can not access image data")}else if(m){let $,x;if(u!==void 0&&u.resizedWidth!==void 0&&u.resizedHeight!==void 0?($=u.resizedHeight,x=u.resizedWidth):($=s.height,x=s.width),u!==void 0&&(w=u),w.format="RGBA",w.height=$,w.width=x,u!==void 0){let O=E();O.width=x,O.height=$;let k=C(O);if(k!=null)k.putImageData(s,0,0),b=k.getImageData(0,0,x,$).data;else throw new Error("Can not access image data")}else b=s.data}else if(y){if(u===void 0)throw new Error("Please provide image config with format for Imagebitmap");let $=E();$.width=s.width,$.height=s.height;let x=C($);if(x!=null){let O=s.height,k=s.width;return x.drawImage(s,0,0,k,O),b=x.getImageData(0,0,k,O).data,w.height=O,w.width=k,ye(b,w)}else throw new Error("Can not access image data")}else{if(T)return new Promise(($,x)=>{let O=E(),k=C(O);if(!s||!k)return x();let D=new Image;D.crossOrigin="Anonymous",D.src=s,D.onload=()=>{O.width=D.width,O.height=D.height,k.drawImage(D,0,0,O.width,O.height);let P=k.getImageData(0,0,O.width,O.height);w.height=O.height,w.width=O.width,$(ye(P.data,w))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(b!==void 0)return ye(b,w);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(s,u)=>{let{width:p,height:m,download:y,dispose:T}=u,b=[1,m,p,4];return new wt({location:"texture",type:"float32",texture:s,dims:b,download:y,dispose:T})},Se=(s,u)=>{let{dataType:p,dims:m,download:y,dispose:T}=u;return new wt({location:"gpu-buffer",type:p??"float32",gpuBuffer:s,dims:m,download:y,dispose:T})},$e=(s,u)=>{let{dataType:p,dims:m,download:y,dispose:T}=u;return new wt({location:"ml-tensor",type:p??"float32",mlTensor:s,dims:m,download:y,dispose:T})},zt=(s,u,p)=>new wt({location:"cpu-pinned",type:s,data:u,dims:p??[u.length]})}),fe,se,st,We,ht=d(()=>{fe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),se=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),st=!1,We=()=>{if(!st){st=!0;let s=typeof BigInt64Array<"u"&&BigInt64Array.from,u=typeof BigUint64Array<"u"&&BigUint64Array.from,p=globalThis.Float16Array,m=typeof p<"u"&&p.from;s&&(fe.set("int64",BigInt64Array),se.set(BigInt64Array,"int64")),u&&(fe.set("uint64",BigUint64Array),se.set(BigUint64Array,"uint64")),m?(fe.set("float16",p),se.set(p,"float16")):fe.set("float16",Uint16Array)}}}),It,qe,Ue=d(()=>{Yt(),It=s=>{let u=1;for(let p=0;p<s.length;p++){let m=s[p];if(typeof m!="number"||!Number.isSafeInteger(m))throw new TypeError(`dims[${p}] must be an integer, got: ${m}`);if(m<0)throw new RangeError(`dims[${p}] must be a non-negative integer, got: ${m}`);u*=m}return u},qe=(s,u)=>{switch(s.location){case"cpu":return new wt(s.type,s.data,u);case"cpu-pinned":return new wt({location:"cpu-pinned",data:s.data,type:s.type,dims:u});case"texture":return new wt({location:"texture",texture:s.texture,type:s.type,dims:u});case"gpu-buffer":return new wt({location:"gpu-buffer",gpuBuffer:s.gpuBuffer,type:s.type,dims:u});case"ml-tensor":return new wt({location:"ml-tensor",mlTensor:s.mlTensor,type:s.type,dims:u});default:throw new Error(`tensorReshape: tensor location ${s.location} is not supported`)}}}),wt,Yt=d(()=>{ue(),Ae(),ht(),Ue(),wt=class{constructor(s,u,p){We();let m,y;if(typeof s=="object"&&"location"in s)switch(this.dataLocation=s.location,m=s.type,y=s.dims,s.location){case"cpu-pinned":{let b=fe.get(m);if(!b)throw new TypeError(`unsupported type "${m}" to create tensor from pinned buffer`);if(!(s.data instanceof b))throw new TypeError(`buffer should be of type ${b.name}`);this.cpuData=s.data;break}case"texture":{if(m!=="float32")throw new TypeError(`unsupported type "${m}" to create tensor from texture`);this.gpuTextureData=s.texture,this.downloader=s.download,this.disposer=s.dispose;break}case"gpu-buffer":{if(m!=="float32"&&m!=="float16"&&m!=="int32"&&m!=="int64"&&m!=="uint32"&&m!=="uint8"&&m!=="bool"&&m!=="uint4"&&m!=="int4")throw new TypeError(`unsupported type "${m}" to create tensor from gpu buffer`);this.gpuBufferData=s.gpuBuffer,this.downloader=s.download,this.disposer=s.dispose;break}case"ml-tensor":{if(m!=="float32"&&m!=="float16"&&m!=="int32"&&m!=="int64"&&m!=="uint32"&&m!=="uint64"&&m!=="int8"&&m!=="uint8"&&m!=="bool"&&m!=="uint4"&&m!=="int4")throw new TypeError(`unsupported type "${m}" to create tensor from MLTensor`);this.mlTensorData=s.mlTensor,this.downloader=s.download,this.disposer=s.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let b,w;if(typeof s=="string")if(m=s,w=p,s==="string"){if(!Array.isArray(u))throw new TypeError("A string tensor's data must be a string array.");b=u}else{let E=fe.get(s);if(E===void 0)throw new TypeError(`Unsupported tensor type: ${s}.`);if(Array.isArray(u)){if(s==="float16"&&E===Uint16Array||s==="uint4"||s==="int4")throw new TypeError(`Creating a ${s} tensor from number array is not supported. Please use ${E.name} as data.`);s==="uint64"||s==="int64"?b=E.from(u,BigInt):b=E.from(u)}else if(u instanceof E)b=u;else if(u instanceof Uint8ClampedArray)if(s==="uint8")b=Uint8Array.from(u);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(s==="float16"&&u instanceof Uint16Array&&E!==Uint16Array)b=new globalThis.Float16Array(u.buffer,u.byteOffset,u.length);else throw new TypeError(`A ${m} tensor's data must be type of ${E}`)}else if(w=u,Array.isArray(s)){if(s.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let E=typeof s[0];if(E==="string")m="string",b=s;else if(E==="boolean")m="bool",b=Uint8Array.from(s);else throw new TypeError(`Invalid element type of data array: ${E}.`)}else if(s instanceof Uint8ClampedArray)m="uint8",b=Uint8Array.from(s);else{let E=se.get(s.constructor);if(E===void 0)throw new TypeError(`Unsupported type for tensor data: ${s.constructor}.`);m=E,b=s}if(w===void 0)w=[b.length];else if(!Array.isArray(w))throw new TypeError("A tensor's dims must be a number array");y=w,this.cpuData=b,this.dataLocation="cpu"}let T=It(y);if(this.cpuData&&T!==this.cpuData.length&&!((m==="uint4"||m==="int4")&&Math.ceil(T/2)===this.cpuData.length))throw new Error(`Tensor's size(${T}) does not match data length(${this.cpuData.length}).`);this.type=m,this.dims=y,this.size=T}static async fromImage(s,u){return Re(s,u)}static fromTexture(s,u){return J(s,u)}static fromGpuBuffer(s,u){return Se(s,u)}static fromMLTensor(s,u){return $e(s,u)}static fromPinnedBuffer(s,u,p){return zt(s,u,p)}toDataURL(s){return me(this,s)}toImageData(s){return _e(this,s)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(s){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let u=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=u,s&&this.disposer&&(this.disposer(),this.disposer=void 0),u}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(s){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return qe(this,s)}}}),Xe,Je=d(()=>{Yt(),Xe=wt}),ut,_t,mt,Le,Pe,Ze,Tt=d(()=>{Ne(),ut=(s,u)=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||console.timeStamp(`${s}::ORT::${u}`)},_t=(s,u)=>{let p=new Error().stack?.split(/\r\n|\r|\n/g)||[],m=!1;for(let y=0;y<p.length;y++){if(m&&!p[y].includes("TRACE_FUNC")){let T=`FUNC_${s}::${p[y].trim().split(" ")[1]}`;u&&(T+=`::${u}`),ut("CPU",T);return}p[y].includes("TRACE_FUNC")&&(m=!0)}},mt=s=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||_t("BEGIN",s)},Le=s=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||_t("END",s)},Pe=s=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||console.time(`ORT::${s}`)},Ze=s=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||console.timeEnd(`ORT::${s}`)}}),qt,rn=d(()=>{ae(),Je(),Tt(),qt=class yb{constructor(u){this.handler=u}async run(u,p,m){mt(),Pe("InferenceSession.run");let y={},T={};if(typeof u!="object"||u===null||u instanceof Xe||Array.isArray(u))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let b=!0;if(typeof p=="object"){if(p===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(p instanceof Xe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(p)){if(p.length===0)throw new TypeError("'fetches' cannot be an empty array.");b=!1;for(let C of p){if(typeof C!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(C)===-1)throw new RangeError(`'fetches' contains invalid output name: ${C}.`);y[C]=null}if(typeof m=="object"&&m!==null)T=m;else if(typeof m<"u")throw new TypeError("'options' must be an object.")}else{let C=!1,$=Object.getOwnPropertyNames(p);for(let x of this.outputNames)if($.indexOf(x)!==-1){let O=p[x];(O===null||O instanceof Xe)&&(C=!0,b=!1,y[x]=O)}if(C){if(typeof m=="object"&&m!==null)T=m;else if(typeof m<"u")throw new TypeError("'options' must be an object.")}else T=p}}else if(typeof p<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let C of this.inputNames)if(typeof u[C]>"u")throw new Error(`input '${C}' is missing in 'feeds'.`);if(b)for(let C of this.outputNames)y[C]=null;let w=await this.handler.run(u,y,T),E={};for(let C in w)if(Object.hasOwnProperty.call(w,C)){let $=w[C];$ instanceof Xe?E[C]=$:E[C]=new Xe($.type,$.data,$.dims)}return Ze("InferenceSession.run"),Le(),E}async release(){return this.handler.dispose()}static async create(u,p,m,y){mt(),Pe("InferenceSession.create");let T,b={};if(typeof u=="string"){if(T=u,typeof p=="object"&&p!==null)b=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else if(u instanceof Uint8Array){if(T=u,typeof p=="object"&&p!==null)b=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else if(u instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&u instanceof SharedArrayBuffer){let $=u,x=0,O=u.byteLength;if(typeof p=="object"&&p!==null)b=p;else if(typeof p=="number"){if(x=p,!Number.isSafeInteger(x))throw new RangeError("'byteOffset' must be an integer.");if(x<0||x>=$.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${$.byteLength}).`);if(O=u.byteLength-x,typeof m=="number"){if(O=m,!Number.isSafeInteger(O))throw new RangeError("'byteLength' must be an integer.");if(O<=0||x+O>$.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${$.byteLength-x}].`);if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else if(typeof m<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof p<"u")throw new TypeError("'options' must be an object.");T=new Uint8Array($,x,O)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[w,E]=await K(b),C=await w.createInferenceSessionHandler(T,E);return Ze("InferenceSession.create"),Le(),new yb(C)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Dt,Wn=d(()=>{rn(),Dt=qt}),Pn=d(()=>{}),Bs=d(()=>{}),Aa=d(()=>{}),jr=d(()=>{}),ar={};A(ar,{InferenceSession:()=>Dt,TRACE:()=>ut,TRACE_EVENT_BEGIN:()=>Pe,TRACE_EVENT_END:()=>Ze,TRACE_FUNC_BEGIN:()=>mt,TRACE_FUNC_END:()=>Le,Tensor:()=>Xe,env:()=>Q,registerBackend:()=>W});var _n=d(()=>{ee(),ce(),Wn(),Je(),Pn(),Bs(),Tt(),Aa(),jr()}),Gr=d(()=>{}),yi={};A(yi,{default:()=>de});var Wr,Kr,de,Pt=d(()=>{tb(),gr(),Ks(),Wr="ort-wasm-proxy-worker",Kr=globalThis.self?.name===Wr,Kr&&(self.onmessage=s=>{let{type:u,in:p}=s.data;try{switch(u){case"init-wasm":Ia(p.wasm).then(()=>{kh(p).then(()=>{postMessage({type:u})},m=>{postMessage({type:u,err:m})})},m=>{postMessage({type:u,err:m})});break;case"init-ep":{let{epName:m,env:y}=p;Dh(y,m).then(()=>{postMessage({type:u})},T=>{postMessage({type:u,err:T})});break}case"copy-from":{let{buffer:m}=p,y=ic(m);postMessage({type:u,out:y});break}case"create":{let{model:m,options:y}=p;Mh(m,y).then(T=>{postMessage({type:u,out:T})},T=>{postMessage({type:u,err:T})});break}case"release":Uh(p),postMessage({type:u});break;case"run":{let{sessionId:m,inputIndices:y,inputs:T,outputIndices:b,options:w}=p;Lh(m,y,T,b,new Array(b.length).fill(null),w).then(E=>{E.some(C=>C[3]!=="cpu")?postMessage({type:u,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:u,out:E},Hh([...T,...E]))},E=>{postMessage({type:u,err:E})});break}case"end-profiling":qh(p),postMessage({type:u});break;default:}}catch(m){postMessage({type:u,err:m})}}),de=Kr?null:s=>new Worker(s??gn,{type:"classic",name:Wr})}),or,lr,gn,Vs,$r,vi,Ti,js,bi,Gs,wi,Ws,Si,Ks=d(()=>{Gr(),or=typeof location>"u"?void 0:location.origin,lr=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,gn=lr(),Vs=()=>{if(gn&&!gn.startsWith("blob:"))return gn.substring(0,gn.lastIndexOf("/")+1)},$r=(s,u)=>{try{let p=u??gn;return(p?new URL(s,p):new URL(s)).origin===or}catch{return!1}},vi=(s,u)=>{let p=u??gn;try{return(p?new URL(s,p):new URL(s)).href}catch{return}},Ti=(s,u)=>`${u??"./"}${s}`,js=async s=>{let u=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(u)},bi=async s=>(await import(s)).default,Gs=(Pt(),R(yi)).default,wi=async()=>{if(!gn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if($r(gn))return[void 0,Gs()];let s=await js(gn);return[s,Gs(s)]},Ws=void 0,Si=async(s,u,p,m)=>{let y=Ws&&!(s||u);if(y)if(gn)y=$r(gn);else if(m&&!p)y=!0;else throw new Error("cannot determine the script source URL.");if(y)return[void 0,Ws];{let T="ort-wasm-simd-threaded.jsep.mjs",b=s??vi(T,u),w=p&&b&&!$r(b,u),E=w?await js(b):b??Ti(T,u);return[w?E:void 0,await bi(E)]}}}),Qn,ds,Yr,mr,Ei,Ci,ur,Ia,$t,gr=d(()=>{Ks(),ds=!1,Yr=!1,mr=!1,Ei=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Ci=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},ur=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Ia=async s=>{if(ds)return Promise.resolve();if(Yr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(mr)throw new Error("previous call to 'initializeWebAssembly()' failed.");Yr=!0;let u=s.initTimeout,p=s.numThreads;if(s.simd!==!1){if(s.simd==="relaxed"){if(!ur())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ci())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let m=Ei();p>1&&!m&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+p+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),s.numThreads=p=1);let y=s.wasmPaths,T=typeof y=="string"?y:void 0,b=y?.mjs,w=b?.href??b,E=y?.wasm,C=E?.href??E,$=s.wasmBinary,[x,O]=await Si(w,T,p>1,!!$||!!C),k=!1,D=[];if(u>0&&D.push(new Promise(P=>{setTimeout(()=>{k=!0,P()},u)})),D.push(new Promise((P,F)=>{let L={numThreads:p};if($)L.wasmBinary=$;else if(C||T)L.locateFile=U=>C??T+U;else if(w&&w.indexOf("blob:")!==0)L.locateFile=U=>new URL(U,w).href;else if(x){let U=Vs();U&&(L.locateFile=V=>U+V)}O(L).then(U=>{Yr=!1,ds=!0,Qn=U,P(),x&&URL.revokeObjectURL(x)},U=>{Yr=!1,mr=!0,F(U)})})),await Promise.race(D),k)throw new Error(`WebAssembly backend initializing failed due to timeout: ${u}ms`)},$t=()=>{if(ds&&Qn)return Qn;throw new Error("WebAssembly is not initialized yet.")}}),yn,hs,Et,yr=d(()=>{gr(),yn=(s,u)=>{let p=$t(),m=p.lengthBytesUTF8(s)+1,y=p._malloc(m);return p.stringToUTF8(s,y,m),u.push(y),y},hs=(s,u,p,m)=>{if(typeof s=="object"&&s!==null){if(p.has(s))throw new Error("Circular reference in options");p.add(s)}Object.entries(s).forEach(([y,T])=>{let b=u?u+y:y;if(typeof T=="object")hs(T,b+".",p,m);else if(typeof T=="string"||typeof T=="number")m(b,T.toString());else if(typeof T=="boolean")m(b,T?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof T}`)})},Et=s=>{let u=$t(),p=u.stackSave();try{let m=u.PTR_SIZE,y=u.stackAlloc(2*m);u._OrtGetLastError(y,y+m);let T=Number(u.getValue(y,m===4?"i32":"i64")),b=u.getValue(y+m,"*"),w=b?u.UTF8ToString(b):"";throw new Error(`${s} ERROR_CODE: ${T}, ERROR_MESSAGE: ${w}`)}finally{u.stackRestore(p)}}}),Ai,vr=d(()=>{gr(),yr(),Ai=s=>{let u=$t(),p=0,m=[],y=s||{};try{if(s?.logSeverityLevel===void 0)y.logSeverityLevel=2;else if(typeof s.logSeverityLevel!="number"||!Number.isInteger(s.logSeverityLevel)||s.logSeverityLevel<0||s.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${s.logSeverityLevel}`);if(s?.logVerbosityLevel===void 0)y.logVerbosityLevel=0;else if(typeof s.logVerbosityLevel!="number"||!Number.isInteger(s.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${s.logVerbosityLevel}`);s?.terminate===void 0&&(y.terminate=!1);let T=0;return s?.tag!==void 0&&(T=yn(s.tag,m)),p=u._OrtCreateRunOptions(y.logSeverityLevel,y.logVerbosityLevel,!!y.terminate,T),p===0&&Et("Can't create run options."),s?.extra!==void 0&&hs(s.extra,"",new WeakSet,(b,w)=>{let E=yn(b,m),C=yn(w,m);u._OrtAddRunConfigEntry(p,E,C)!==0&&Et(`Can't set a run config entry: ${b} - ${w}.`)}),[p,m]}catch(T){throw p!==0&&u._OrtReleaseRunOptions(p),m.forEach(b=>u._free(b)),T}}}),Ii,Ri,xr,Tr,cr,$i,Ra=d(()=>{gr(),yr(),Ii=s=>{switch(s){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${s}`)}},Ri=s=>{switch(s){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${s}`)}},xr=s=>{s.extra||(s.extra={}),s.extra.session||(s.extra.session={});let u=s.extra.session;u.use_ort_model_bytes_directly||(u.use_ort_model_bytes_directly="1"),s.executionProviders&&s.executionProviders.some(p=>(typeof p=="string"?p:p.name)==="webgpu")&&(s.enableMemPattern=!1)},Tr=(s,u,p,m)=>{let y=yn(u,m),T=yn(p,m);$t()._OrtAddSessionConfigEntry(s,y,T)!==0&&Et(`Can't set a session config entry: ${u} - ${p}.`)},cr=async(s,u,p)=>{for(let m of u){let y=typeof m=="string"?m:m.name,T=[];switch(y){case"webnn":if(y="WEBNN",typeof m!="string"){let $=m?.deviceType;$&&Tr(s,"deviceType",$,p)}break;case"webgpu":if(y="JS",typeof m!="string"){let $=m;if($?.preferredLayout){if($.preferredLayout!=="NCHW"&&$.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${$.preferredLayout}`);Tr(s,"preferredLayout",$.preferredLayout,p)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${y}`)}let b=yn(y,p),w=T.length,E=0,C=0;if(w>0){E=$t()._malloc(w*$t().PTR_SIZE),p.push(E),C=$t()._malloc(w*$t().PTR_SIZE),p.push(C);for(let $=0;$<w;$++)$t().setValue(E+$*$t().PTR_SIZE,T[$][0],"*"),$t().setValue(C+$*$t().PTR_SIZE,T[$][1],"*")}await $t()._OrtAppendExecutionProvider(s,b,E,C,w)!==0&&Et(`Can't append execution provider: ${y}.`)}},$i=async s=>{let u=$t(),p=0,m=[],y=s||{};xr(y);try{let T=Ii(y.graphOptimizationLevel??"all"),b=Ri(y.executionMode??"sequential"),w=typeof y.logId=="string"?yn(y.logId,m):0,E=y.logSeverityLevel??2;if(!Number.isInteger(E)||E<0||E>4)throw new Error(`log severity level is not valid: ${E}`);let C=y.logVerbosityLevel??0;if(!Number.isInteger(C)||C<0||C>4)throw new Error(`log verbosity level is not valid: ${C}`);let $=typeof y.optimizedModelFilePath=="string"?yn(y.optimizedModelFilePath,m):0;if(p=u._OrtCreateSessionOptions(T,!!y.enableCpuMemArena,!!y.enableMemPattern,b,!!y.enableProfiling,0,w,E,C,$),p===0&&Et("Can't create session options."),y.executionProviders&&await cr(p,y.executionProviders,m),y.enableGraphCapture!==void 0){if(typeof y.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${y.enableGraphCapture}`);Tr(p,"enableGraphCapture",y.enableGraphCapture.toString(),m)}if(y.freeDimensionOverrides)for(let[x,O]of Object.entries(y.freeDimensionOverrides)){if(typeof x!="string")throw new Error(`free dimension override name must be a string: ${x}`);if(typeof O!="number"||!Number.isInteger(O)||O<0)throw new Error(`free dimension override value must be a non-negative integer: ${O}`);let k=yn(x,m);u._OrtAddFreeDimensionOverride(p,k,O)!==0&&Et(`Can't set a free dimension override: ${x} - ${O}.`)}return y.extra!==void 0&&hs(y.extra,"",new WeakSet,(x,O)=>{Tr(p,x,O,m)}),[p,m]}catch(T){throw p!==0&&u._OrtReleaseSessionOptions(p)!==0&&Et("Can't release session options."),m.forEach(b=>u._free(b)),T}}}),br,Zn,wr,Or,ps,Ys,Xs,Js,rt=d(()=>{br=s=>{switch(s){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${s}`)}},Zn=s=>{switch(s){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${s}`)}},wr=(s,u)=>{let p=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][s],m=typeof u=="number"?u:u.reduce((y,T)=>y*T,1);return p>0?Math.ceil(m*p):void 0},Or=s=>{switch(s){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${s}`)}},ps=s=>{switch(s){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${s}`)}},Ys=s=>s==="float32"||s==="float16"||s==="int32"||s==="int64"||s==="uint32"||s==="uint8"||s==="bool"||s==="uint4"||s==="int4",Xs=s=>s==="float32"||s==="float16"||s==="int32"||s==="int64"||s==="uint32"||s==="uint64"||s==="int8"||s==="uint8"||s==="bool"||s==="uint4"||s==="int4",Js=s=>{switch(s){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${s}`)}}}),Qs,xi=d(()=>{Gr(),Qs=async s=>{if(typeof s=="string"){let u=await fetch(s);if(!u.ok)throw new Error(`failed to load external data file: ${s}`);let p=u.headers.get("Content-Length"),m=p?parseInt(p,10):0;if(m<1073741824)return new Uint8Array(await u.arrayBuffer());{if(!u.body)throw new Error(`failed to load external data file: ${s}, no response body.`);let y=u.body.getReader(),T;try{T=new ArrayBuffer(m)}catch(w){if(w instanceof RangeError){let E=Math.ceil(m/65536);T=new WebAssembly.Memory({initial:E,maximum:E}).buffer}else throw w}let b=0;for(;;){let{done:w,value:E}=await y.read();if(w)break;let C=E.byteLength;new Uint8Array(T,b,C).set(E),b+=C}return new Uint8Array(T,0,m)}}else return s instanceof Blob?new Uint8Array(await s.arrayBuffer()):s instanceof Uint8Array?s:new Uint8Array(s)}}),Oi,ki,kr,Di,Zs,Ni,vt,Sr=d(()=>{rt(),Oi=["V","I","W","E","F"],ki=(s,u)=>{console.log(`[${Oi[s]},${new Date().toISOString()}]${u}`)},Zs=(s,u)=>{kr=s,Di=u},Ni=(s,u)=>{let p=ps(s),m=ps(kr);p>=m&&ki(p,typeof u=="function"?u():u)},vt=(...s)=>{Di&&Ni(...s)}}),lo,_s,ne,fn,Dr,fs,Mi,ct=d(()=>{lo=class{static calcMatMulShape(s,u){return s[1]!==u[0]?void 0:[s[0],u[1]]}},_s=class{static calcShape(s,u,p=!1){let m=s.length,y=u.length;if(m===0)return u;if(y===0)return s;let T=Math.max(s.length,u.length),b=new Array(T);if(p){if(m<2||y<2)return;let w=lo.calcMatMulShape([s[m-2],s[m-1]],[u[y-2],u[y-1]]);if(w===void 0)return;[b[T-2],b[T-1]]=w}for(let w=p?3:1;w<=T;w++){let E=m-w<0?1:s[m-w],C=y-w<0?1:u[y-w];if(E!==C&&E>1&&C>1)return;let $=Math.max(E,C);if(E&&C)b[T-w]=Math.max(E,C);else{if($>1)return;b[T-w]=0}}return b}static isValidBroadcast(s,u){let p=s.length,m=u.length;if(p>m)return!1;for(let y=1;y<=p;y++)if(s[p-y]!==1&&s[p-y]!==u[m-y])return!1;return!0}},ne=class lc{static size(u){return lc.getSizeFromDimensionRange(u,0,u.length)}static convertShape(u,p=4){let m=u.length;if(m===0)return[];let y=new Array(m),T=m-1;for(;T>=0;){if(u[T]%p===0){y[T]=u[T]/p;break}if(p%u[T]!==0)throw new Error("cannot convert shape");y[T]=1,p/=u[T],T--}for(T--;T>=0;T--)y[T]=u[T];return y}static sizeFromDimension(u,p){if(p<0||p>u.length)throw new Error(`invalid dimension of ${p} for sizeFromDimension as Tensor has ${u.length} dimensions.`);return lc.getSizeFromDimensionRange(u,p,u.length)}static sizeToDimension(u,p){if(p<0||p>u.length)throw new Error(`invalid dimension of ${p} for sizeToDimension as Tensor has ${u.length} dimensions.`);return lc.getSizeFromDimensionRange(u,0,p)}static getSizeFromDimensionRange(u,p,m){let y=1;for(let T=p;T<m;T++){if(u[T]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");y*=Number(u[T])}return y}static computeStrides(u){let p=u.length;if(p===0)return[];if(p===1)return[1];let m=new Array(p);m[p-1]=1,m[p-2]=u[p-1];for(let y=p-3;y>=0;--y)m[y]=m[y+1]*u[y+1];return m}static normalizeAxis(u,p){if(u<-p&&u>=p)throw new Error("unsupported axis for this operation.");return u<0?u+p:u}static normalizeAxes(u,p){return u.map(m=>this.normalizeAxis(m,p??u.length))}static sortBasedOnPerm(u,p){return p?p.map(m=>u[m]):u.slice().reverse()}static padShape(u,p){let m=u.length;return u.map((y,T)=>y+p[T]+p[T+m])}static areEqual(u,p){return u.length!==p.length?!1:u.every((m,y)=>m===p[y])}},fn=class Ul{static adjustPoolAttributes(u,p,m,y,T,b){if(!u&&m.length!==p.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(u)for(let w=0;w<p.length-2;w++)w>=m.length?m.push(p[w+2]):m[w]=p[w+2];for(let w=0;w<m.length;w++)if(w<y.length){if(y[w]<0)throw new Error("strides should be greater than or equal to 1")}else y.push(1);for(let w=0;w<m.length;w++)if(w<T.length){if(T[w]<0)throw new Error("dilations should be greater than or equal to 1")}else T.push(1);for(let w=0;w<m.length*2;w++)if(w<b.length){if(b[w]<0)throw new Error("pad should be greater than or equal to 1")}else b.push(0);for(let w=0;w<m.length;w++){if(m[w]<=0)throw new Error("kernel shapes need to be greater than 0");if(b[w]>=m[w]||b[w+m.length]>=m[w])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(u,p,m,y,T,b,w){if(w){if(T.length!==2*(u.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(p.length!==u.length-2)throw new Error("length of strides should be the length of data dimensions");if(y.length!==u.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let E=0;E<u.length-2;E++)Ul.adjustPadAndReturnShape(u[E+(b?1:2)],p[E],m[E],y[E],T,E,E+u.length-2,w)}}static computePoolOutputShape(u,p,m,y,T,b,w){if(p.length<=0)throw new Error("input shape must be of size greater than 0");let E=[p[0],p[1]];return Ul.computeShapeHelper(u,p,E,m,y,T,b,w),E}static computeConvOutputShape(u,p,m,y,T,b,w){if(u.length<=0||p.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let E=[u[0],p[0]];return Ul.computeShapeHelper(!1,u,E,m,y,T,b,w),E}static computeShapeHelper(u,p,m,y,T,b,w,E){if(u)for(let C=0;C<p.length-2;C++)m.push(1);else for(let C=0;C<p.length-2;C++)m.push(Ul.adjustPadAndReturnShape(p[C+2],y[C],T[C],b[C],w,C,C+p.length-2,E))}static adjustPadAndReturnShape(u,p,m,y,T,b,w,E){let C=m*(y-1)+1;if(E&&E!=="NOTSET")switch(E){case"VALID":return T[b]=0,T[w]=0,Math.floor((u-C)/p+1);case"SAME_LOWER":case"SAME_UPPER":if(m!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let $=((u+p-1)/p-1)*p+y-u;return T[b]=Math.floor(E==="SAME_LOWER"?($+1)/2:$/2),T[w]=$-T[b],Math.floor((u+$-y)/p+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((u+T[b]+T[w]-C)/p+1)}},Dr=class{static getShapeOfGemmResult(s,u,p,m,y){if(s.length!==2||p.length!==2)throw new Error("shape need to be of size 2");let T,b,w;u?(T=s[1],b=s[0]):(T=s[0],b=s[1]);let E=-1;if(m?(w=p[0],E=1):(w=p[1],E=0),p[E]!==b)throw new Error("dimension mismatch");if(T<=0||w<=0||b<=0)throw new Error("invalid shape specified");if(y&&!_s.isValidBroadcast(y,[T,w]))throw new Error("gemm: invalid bias shape for broadcast");return[T,w,b]}},fs=-34028234663852886e22,Mi=34028234663852886e22}),vn,Ui=d(()=>{rt(),vn=(s,u)=>new(Or(u))(s)}),gt,ei,$a,Pi,Xr,Li,xa,Oa,ka,qi,Hi,Da=d(()=>{rt(),Sr(),gt=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ei=(s,u)=>{if(u==="int32")return s;let p=gt.get(u);if(!p)throw new Error(`WebNN backend does not support data type: ${u}`);let m=p/8;if(s.byteLength%m!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${m}.`);let y=s.byteLength/m,T=new(Or(u))(s.buffer,s.byteOffset,y);switch(u){case"int64":case"uint64":{let b=new Int32Array(y);for(let w=0;w<y;w++){let E=T[w];if(E>2147483647n||E<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");b[w]=Number(E)}return new Uint8Array(b.buffer)}case"int8":case"uint8":case"uint32":{if(u==="uint32"&&T.some(w=>w>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let b=Int32Array.from(T,Number);return new Uint8Array(b.buffer)}default:throw new Error(`Unsupported data conversion from ${u} to 'int32'`)}},$a=(s,u)=>{if(u==="int32")return s;if(s.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let p=s.byteLength/4,m=new Int32Array(s.buffer,s.byteOffset,p);switch(u){case"int64":{let y=BigInt64Array.from(m,BigInt);return new Uint8Array(y.buffer)}case"uint64":{if(m.some(T=>T<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let y=BigUint64Array.from(m,BigInt);return new Uint8Array(y.buffer)}case"int8":{if(m.some(T=>T<-128||T>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let y=Int8Array.from(m,Number);return new Uint8Array(y.buffer)}case"uint8":{if(m.some(y=>y<0||y>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(m,Number)}case"uint32":{if(m.some(T=>T<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let y=Uint32Array.from(m,Number);return new Uint8Array(y.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${u}`)}},Pi=1,Xr=()=>Pi++,Li=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),xa=(s,u)=>{let p=gt.get(s);if(!p)throw new Error(`WebNN backend does not support data type: ${s}`);return u.length>0?Math.ceil(u.reduce((m,y)=>m*y)*p/8):0},Oa=class{constructor(s){this.isDataConverted=!1;let{sessionId:u,context:p,tensor:m,dataType:y,shape:T,fallbackDataType:b}=s;this.sessionId=u,this.mlContext=p,this.mlTensor=m,this.dataType=y,this.tensorShape=T,this.fallbackDataType=b}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return xa(this.dataType,this.tensorShape)}destroy(){vt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(s){this.mlContext.writeTensor(this.mlTensor,s)}async read(s){if(this.fallbackDataType){let u=await this.mlContext.readTensor(this.mlTensor),p=$a(new Uint8Array(u),this.dataType);if(s){(s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)).set(p);return}else return p.buffer}else return s?this.mlContext.readTensor(this.mlTensor,s):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(s,u,p){return this.mlContext===s&&this.dataType===u&&this.tensorShape.length===p.length&&this.tensorShape.every((m,y)=>m===p[y])}setIsDataConverted(s){this.isDataConverted=s}},ka=class{constructor(s,u){this.tensorManager=s,this.wrapper=u}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(s,u,p,m){let y=this.tensorManager.getMLContext(s),T;if(!y.opSupportLimits().input.dataTypes.includes(u)){if(T=Li.get(u),!T||!y.opSupportLimits().input.dataTypes.includes(T))throw new Error(`WebNN backend does not support data type: ${u}`);vt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${u} to ${T}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(y,u,p))return this.wrapper.tensor;if(m){if(this.wrapper.byteLength!==xa(u,p))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let b=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(s,u,p,b,!0,!0,T),m&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(s){let u=s;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")u=ei(s,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(s.byteLength===this.wrapper.byteLength){this.wrapper.write(u);return}else vt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(u):this.activeUpload=new Uint8Array(u)}async download(s){if(this.activeUpload){let u=this.wrapper?.isDataConverted?$a(this.activeUpload,this.wrapper?.type):this.activeUpload;if(s){s instanceof ArrayBuffer?new Uint8Array(s).set(u):new Uint8Array(s.buffer,s.byteOffset,s.byteLength).set(u);return}else return u.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return s?this.wrapper.read(s):this.wrapper.read()}},qi=class{constructor(s){this.backend=s,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(s){let u=this.backend.getMLContext(s);if(!u)throw new Error("MLContext not found for session.");return u}reserveTensorId(){let s=Xr();return this.tensorTrackersById.set(s,new ka(this)),s}releaseTensorId(s){let u=this.tensorTrackersById.get(s);u&&(this.tensorTrackersById.delete(s),u.tensorWrapper&&this.releaseTensor(u.tensorWrapper))}async ensureTensor(s,u,p,m,y){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${u}, dataType: ${p}, shape: ${m}, copyOld: ${y}}`);let T=this.tensorTrackersById.get(u);if(!T)throw new Error("Tensor not found.");return T.ensureTensor(s,p,m,y)}upload(s,u){let p=this.tensorTrackersById.get(s);if(!p)throw new Error("Tensor not found.");p.upload(u)}async download(s,u){vt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${s}, dstBuffer: ${u?.byteLength}}`);let p=this.tensorTrackersById.get(s);if(!p)throw new Error("Tensor not found.");return p.download(u)}releaseTensorsForSession(s){for(let u of this.freeTensors)u.sessionId===s&&u.destroy();this.freeTensors=this.freeTensors.filter(u=>u.sessionId!==s)}registerTensor(s,u,p,m){let y=this.getMLContext(s),T=Xr(),b=new Oa({sessionId:s,context:y,tensor:u,dataType:p,shape:m});return this.tensorTrackersById.set(T,new ka(this,b)),this.externalTensors.add(b),T}async getCachedTensor(s,u,p,m,y,T,b){let w=this.getMLContext(s);for(let[C,$]of this.freeTensors.entries())if($.canReuseTensor(w,u,p)){vt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${u}, ${b?`fallbackDataType: ${b},`:""} shape: ${p}`);let x=this.freeTensors.splice(C,1)[0];return x.sessionId=s,x}vt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${u}, ${b?`fallbackDataType: ${b},`:""} shape: ${p}}`);let E=await w.createTensor({dataType:b??u,shape:p,dimensions:p,usage:m,writable:y,readable:T});return new Oa({sessionId:s,context:w,tensor:E,dataType:u,shape:p,fallbackDataType:b})}releaseTensor(s){this.externalTensors.has(s)&&this.externalTensors.delete(s),this.freeTensors.push(s)}},Hi=(...s)=>new qi(...s)}),Jr,Nr,zi,Na=d(()=>{rt(),gr(),Ui(),Da(),Sr(),Jr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Nr=(s,u)=>{if(s===u)return!0;if(s===void 0||u===void 0)return!1;let p=Object.keys(s).sort(),m=Object.keys(u).sort();return p.length===m.length&&p.every((y,T)=>y===m[T]&&s[y]===u[y])},zi=class{constructor(s){this.tensorManager=Hi(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,Zs(s.logLevel,!!s.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(s){vt("verbose",()=>`[WebNN] onRunStart {sessionId: ${s}}`),this.activeSessionId=s}onRunEnd(s){vt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${s}}`);let u=this.temporarySessionTensorIds.get(s);if(u){for(let p of u)vt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${p}}`),this.tensorManager.releaseTensorId(p);this.temporarySessionTensorIds.delete(s),this.activeSessionId=void 0}}async createMLContext(s){if(s instanceof GPUDevice){let p=this.mlContextCache.findIndex(m=>m.gpuDevice===s);if(p!==-1)return this.mlContextCache[p].mlContext;{let m=await navigator.ml.createContext(s);return this.mlContextCache.push({gpuDevice:s,mlContext:m}),m}}else if(s===void 0){let p=this.mlContextCache.findIndex(m=>m.options===void 0&&m.gpuDevice===void 0);if(p!==-1)return this.mlContextCache[p].mlContext;{let m=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:m}),m}}let u=this.mlContextCache.findIndex(p=>Nr(p.options,s));if(u!==-1)return this.mlContextCache[u].mlContext;{let p=await navigator.ml.createContext(s);return this.mlContextCache.push({options:s,mlContext:p}),p}}registerMLContext(s,u){this.mlContextBySessionId.set(s,u);let p=this.sessionIdsByMLContext.get(u);p||(p=new Set,this.sessionIdsByMLContext.set(u,p)),p.add(s),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(s,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(s,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(s){this.sessionGraphInputs.delete(s),this.sessionGraphOutputs.delete(s);let u=this.mlContextBySessionId.get(s);if(!u)return;this.tensorManager.releaseTensorsForSession(s),this.mlContextBySessionId.delete(s);let p=this.sessionIdsByMLContext.get(u);if(p.delete(s),p.size===0){this.sessionIdsByMLContext.delete(u);let m=this.mlContextCache.findIndex(y=>y.mlContext===u);m!==-1&&this.mlContextCache.splice(m,1)}}getMLContext(s){return this.mlContextBySessionId.get(s)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(s){vt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${s}}`),this.tensorManager.releaseTensorId(s)}async ensureTensor(s,u,p,m,y){let T=Jr.get(p);if(!T)throw new Error(`Unsupported ONNX data type: ${p}`);return this.tensorManager.ensureTensor(s??this.currentSessionId,u,T,m,y)}async createTemporaryTensor(s,u,p){vt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${u}, shape: ${p}}`);let m=Jr.get(u);if(!m)throw new Error(`Unsupported ONNX data type: ${u}`);let y=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(s,y,m,p,!1);let T=this.temporarySessionTensorIds.get(s);return T?T.push(y):this.temporarySessionTensorIds.set(s,[y]),y}uploadTensor(s,u){if(!$t().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");vt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${s}, data: ${u.byteLength}}`),this.tensorManager.upload(s,u)}async downloadTensor(s,u){return this.tensorManager.download(s,u)}createMLTensorDownloader(s,u){return async()=>{let p=await this.tensorManager.download(s);return vn(p,u)}}registerMLTensor(s,u,p,m){let y=Jr.get(p);if(!y)throw new Error(`Unsupported ONNX data type: ${p}`);let T=this.tensorManager.registerTensor(s,u,y,m);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${u}, dataType: ${y}, dimensions: ${m}} -> {tensorId: ${T}}`),T}registerMLConstant(s,u,p,m,y,T,b=!1){if(!T)throw new Error("External mounted files are not available.");let w=s;s.startsWith("./")&&(w=s.substring(2));let E=T.get(w);if(!E)throw new Error(`File with name ${w} not found in preloaded files.`);if(u+p>E.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let C=E.slice(u,u+p).buffer,$;switch(y.dataType){case"float32":$=new Float32Array(C);break;case"float16":$=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(C):new Uint16Array(C);break;case"int32":$=new Int32Array(C);break;case"uint32":$=new Uint32Array(C);break;case"int64":if(b){let x=ei(new Uint8Array(C),"int64");$=new Int32Array(x.buffer),y.dataType="int32"}else $=new BigInt64Array(C);break;case"uint64":$=new BigUint64Array(C);break;case"int8":$=new Int8Array(C);break;case"int4":case"uint4":case"uint8":$=new Uint8Array(C);break;default:throw new Error(`Unsupported data type: ${y.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${y.dataType}, shape: ${y.shape}}} ${b?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),m.constant(y,$)}registerGraphInput(s){this.temporaryGraphInputs.push(s)}registerGraphOutput(s){this.temporaryGraphOutputs.push(s)}isGraphInput(s,u){let p=this.sessionGraphInputs.get(s);return p?p.includes(u):!1}isGraphOutput(s,u){let p=this.sessionGraphOutputs.get(s);return p?p.includes(u):!1}isGraphInputOutputTypeSupported(s,u,p=!0){let m=this.mlContextBySessionId.get(s),y=Jr.get(br(u));return typeof y>"u"?!1:p?!!m?.opSupportLimits().input.dataTypes.includes(y):!!m?.opSupportLimits().output.dataTypes.includes(y)}flush(){}}}),Qr=d(()=>{}),ti,Fi,ms,uo,co,er,Ma,gs,ys,El=d(()=>{Sr(),Qr(),ti=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Fi=[],ms=s=>Math.ceil(Number(s)/16)*16,uo=s=>{for(let u=0;u<Fi.length;u++){let p=Fi[u];if(s<=p)return p}return Math.ceil(s/16)*16},co=1,er=()=>co++,Ma=async(s,u,p,m)=>{let y=ms(p),T=s.device.createBuffer({size:y,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let b=s.getCommandEncoder();s.endComputePass(),b.copyBufferToBuffer(u,0,T,0,y),s.flush(),await T.mapAsync(GPUMapMode.READ);let w=T.getMappedRange();if(m){let E=m();return E.set(new Uint8Array(w,0,p)),E}else return new Uint8Array(w.slice(0,p))}finally{T.destroy()}},gs=class{constructor(s){this.backend=s,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[u]of ti)Fi.push(u),this.freeBuffers.set(u,[]),this.freeUniformBuffers.set(u,[]);this.sessionCount=0}upload(s,u){let p=u.buffer,m=u.byteOffset,y=u.byteLength,T=ms(y),b=this.storageCache.get(s);if(!b)throw new Error("gpu data for uploading does not exist");if(Number(b.originalSize)!==y)throw new Error(`inconsistent data size. gpu data size=${b.originalSize}, data size=${y}`);let w=this.backend.device.createBuffer({mappedAtCreation:!0,size:T,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),E=w.getMappedRange();new Uint8Array(E).set(new Uint8Array(p,m,y)),w.unmap();let C=this.backend.device.createCommandEncoder();C.copyBufferToBuffer(w,0,b.gpuData.buffer,0,T),this.backend.device.queue.submit([C.finish()]),w.destroy(),vt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${s})`)}memcpy(s,u){let p=this.storageCache.get(s);if(!p)throw new Error("source gpu data for memcpy does not exist");let m=this.storageCache.get(u);if(!m)throw new Error("destination gpu data for memcpy does not exist");if(p.originalSize!==m.originalSize)throw new Error("inconsistent source and destination gpu data size");let y=ms(p.originalSize),T=this.backend.getCommandEncoder();this.backend.endComputePass(),T.copyBufferToBuffer(p.gpuData.buffer,0,m.gpuData.buffer,0,y)}registerExternalBuffer(s,u,p){let m;if(p){if(m=p[0],s===p[1])return vt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${u}) => id=${m}, buffer is the same, skip.`),m;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
163
|
+
*/(function(o,n){var r=(()=>{var a=Object.defineProperty,c=Object.getOwnPropertyDescriptor,e=Object.getOwnPropertyNames,_=Object.prototype.hasOwnProperty,g=(s=>typeof oo<"u"?oo:typeof Proxy<"u"?new Proxy(s,{get:(u,p)=>(typeof oo<"u"?oo:u)[p]}):s)(function(s){if(typeof oo<"u")return oo.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')}),d=(s,u)=>()=>(s&&(u=s(s=0)),u),A=(s,u)=>{for(var p in u)a(s,p,{get:u[p],enumerable:!0})},S=(s,u,p,m)=>{if(u&&typeof u=="object"||typeof u=="function")for(let y of e(u))!_.call(s,y)&&y!==p&&a(s,y,{get:()=>u[y],enumerable:!(m=c(u,y))||m.enumerable});return s},R=s=>S(a({},"__esModule",{value:!0}),s),N,H,W,G,K,ae=d(()=>{N=new Map,H=[],W=(s,u,p)=>{if(u&&typeof u.init=="function"&&typeof u.createInferenceSessionHandler=="function"){let m=N.get(s);if(m===void 0)N.set(s,{backend:u,priority:p});else{if(m.priority>p)return;if(m.priority===p&&m.backend!==u)throw new Error(`cannot register backend "${s}" using priority ${p}`)}if(p>=0){let y=H.indexOf(s);y!==-1&&H.splice(y,1);for(let T=0;T<H.length;T++)if(N.get(H[T]).priority<=p){H.splice(T,0,s);return}H.push(s)}return}throw new TypeError("not a valid backend")},G=async s=>{let u=N.get(s);if(!u)return"backend not found.";if(u.initialized)return u.backend;if(u.aborted)return u.error;{let p=!!u.initPromise;try{return p||(u.initPromise=u.backend.init(s)),await u.initPromise,u.initialized=!0,u.backend}catch(m){return p||(u.error=`${m}`,u.aborted=!0),u.error}finally{delete u.initPromise}}},K=async s=>{let u=s.executionProviders||[],p=u.map(E=>typeof E=="string"?E:E.name),m=p.length===0?H:p,y,T=[],b=new Set;for(let E of m){let C=await G(E);typeof C=="string"?T.push({name:E,err:C}):(y||(y=C),y===C&&b.add(E))}if(!y)throw new Error(`no available backend found. ERR: ${T.map(E=>`[${E.name}] ${E.err}`).join(", ")}`);for(let{name:E,err:C}of T)p.includes(E)&&console.warn(`removing requested execution provider "${E}" from session options because it is not available: ${C}`);let w=u.filter(E=>b.has(typeof E=="string"?E:E.name));return[y,new Proxy(s,{get:(E,C)=>C==="executionProviders"?w:Reflect.get(E,C)})]}}),ee=d(()=>{ae()}),De,X=d(()=>{De="1.23.2"}),re,be,Ne=d(()=>{X(),re="warning",be={wasm:{},webgl:{},webgpu:{},versions:{common:De},set logLevel(s){if(s!==void 0){if(typeof s!="string"||["verbose","info","warning","error","fatal"].indexOf(s)===-1)throw new Error(`Unsupported logging level: ${s}`);re=s}},get logLevel(){return re}},Object.defineProperty(be,"logLevel",{enumerable:!0})}),Q,ce=d(()=>{Ne(),Q=be}),me,_e,ue=d(()=>{me=(s,u)=>{let p=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);p.width=s.dims[3],p.height=s.dims[2];let m=p.getContext("2d");if(m!=null){let y,T;u?.tensorLayout!==void 0&&u.tensorLayout==="NHWC"?(y=s.dims[2],T=s.dims[3]):(y=s.dims[3],T=s.dims[2]);let b=u?.format!==void 0?u.format:"RGB",w=u?.norm,E,C;w===void 0||w.mean===void 0?E=[255,255,255,255]:typeof w.mean=="number"?E=[w.mean,w.mean,w.mean,w.mean]:(E=[w.mean[0],w.mean[1],w.mean[2],0],w.mean[3]!==void 0&&(E[3]=w.mean[3])),w===void 0||w.bias===void 0?C=[0,0,0,0]:typeof w.bias=="number"?C=[w.bias,w.bias,w.bias,w.bias]:(C=[w.bias[0],w.bias[1],w.bias[2],0],w.bias[3]!==void 0&&(C[3]=w.bias[3]));let $=T*y,x=0,O=$,k=$*2,D=-1;b==="RGBA"?(x=0,O=$,k=$*2,D=$*3):b==="RGB"?(x=0,O=$,k=$*2):b==="RBG"&&(x=0,k=$,O=$*2);for(let P=0;P<T;P++)for(let F=0;F<y;F++){let L=(s.data[x++]-C[0])*E[0],U=(s.data[O++]-C[1])*E[1],V=(s.data[k++]-C[2])*E[2],B=D===-1?255:(s.data[D++]-C[3])*E[3];m.fillStyle="rgba("+L+","+U+","+V+","+B+")",m.fillRect(F,P,1,1)}if("toDataURL"in p)return p.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},_e=(s,u)=>{let p=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),m;if(p!=null){let y,T,b;u?.tensorLayout!==void 0&&u.tensorLayout==="NHWC"?(y=s.dims[2],T=s.dims[1],b=s.dims[3]):(y=s.dims[3],T=s.dims[2],b=s.dims[1]);let w=u!==void 0&&u.format!==void 0?u.format:"RGB",E=u?.norm,C,$;E===void 0||E.mean===void 0?C=[255,255,255,255]:typeof E.mean=="number"?C=[E.mean,E.mean,E.mean,E.mean]:(C=[E.mean[0],E.mean[1],E.mean[2],255],E.mean[3]!==void 0&&(C[3]=E.mean[3])),E===void 0||E.bias===void 0?$=[0,0,0,0]:typeof E.bias=="number"?$=[E.bias,E.bias,E.bias,E.bias]:($=[E.bias[0],E.bias[1],E.bias[2],0],E.bias[3]!==void 0&&($[3]=E.bias[3]));let x=T*y;if(u!==void 0&&(u.format!==void 0&&b===4&&u.format!=="RGBA"||b===3&&u.format!=="RGB"&&u.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let O=4,k=0,D=1,P=2,F=3,L=0,U=x,V=x*2,B=-1;w==="RGBA"?(L=0,U=x,V=x*2,B=x*3):w==="RGB"?(L=0,U=x,V=x*2):w==="RBG"&&(L=0,V=x,U=x*2),m=p.createImageData(y,T);for(let Y=0;Y<T*y;k+=O,D+=O,P+=O,F+=O,Y++)m.data[k]=(s.data[L++]-$[0])*C[0],m.data[D]=(s.data[U++]-$[1])*C[1],m.data[P]=(s.data[V++]-$[2])*C[2],m.data[F]=B===-1?255:(s.data[B++]-$[3])*C[3]}else throw new Error("Can not access image data");return m}}),ye,Re,J,Se,$e,zt,Ae=d(()=>{Yt(),ye=(s,u)=>{if(s===void 0)throw new Error("Image buffer must be defined");if(u.height===void 0||u.width===void 0)throw new Error("Image height and width must be defined");if(u.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:p,width:m}=u,y=u.norm??{mean:255,bias:0},T,b;typeof y.mean=="number"?T=[y.mean,y.mean,y.mean,y.mean]:T=[y.mean[0],y.mean[1],y.mean[2],y.mean[3]??255],typeof y.bias=="number"?b=[y.bias,y.bias,y.bias,y.bias]:b=[y.bias[0],y.bias[1],y.bias[2],y.bias[3]??0];let w=u.format!==void 0?u.format:"RGBA",E=u.tensorFormat!==void 0&&u.tensorFormat!==void 0?u.tensorFormat:"RGB",C=p*m,$=E==="RGBA"?new Float32Array(C*4):new Float32Array(C*3),x=4,O=0,k=1,D=2,P=3,F=0,L=C,U=C*2,V=-1;w==="RGB"&&(x=3,O=0,k=1,D=2,P=-1),E==="RGBA"?V=C*3:E==="RBG"?(F=0,U=C,L=C*2):E==="BGR"&&(U=0,L=C,F=C*2);for(let B=0;B<C;B++,O+=x,D+=x,k+=x,P+=x)$[F++]=(s[O]+b[0])/T[0],$[L++]=(s[k]+b[1])/T[1],$[U++]=(s[D]+b[2])/T[2],V!==-1&&P!==-1&&($[V++]=(s[P]+b[3])/T[3]);return E==="RGBA"?new wt("float32",$,[1,4,p,m]):new wt("float32",$,[1,3,p,m])},Re=async(s,u)=>{let p=typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement,m=typeof ImageData<"u"&&s instanceof ImageData,y=typeof ImageBitmap<"u"&&s instanceof ImageBitmap,T=typeof s=="string",b,w=u??{},E=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},C=$=>typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||$ instanceof OffscreenCanvas?$.getContext("2d"):null;if(p){let $=E();$.width=s.width,$.height=s.height;let x=C($);if(x!=null){let O=s.height,k=s.width;if(u!==void 0&&u.resizedHeight!==void 0&&u.resizedWidth!==void 0&&(O=u.resizedHeight,k=u.resizedWidth),u!==void 0){if(w=u,u.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");w.tensorFormat="RGBA",w.height=O,w.width=k}else w.tensorFormat="RGBA",w.height=O,w.width=k;x.drawImage(s,0,0),b=x.getImageData(0,0,k,O).data}else throw new Error("Can not access image data")}else if(m){let $,x;if(u!==void 0&&u.resizedWidth!==void 0&&u.resizedHeight!==void 0?($=u.resizedHeight,x=u.resizedWidth):($=s.height,x=s.width),u!==void 0&&(w=u),w.format="RGBA",w.height=$,w.width=x,u!==void 0){let O=E();O.width=x,O.height=$;let k=C(O);if(k!=null)k.putImageData(s,0,0),b=k.getImageData(0,0,x,$).data;else throw new Error("Can not access image data")}else b=s.data}else if(y){if(u===void 0)throw new Error("Please provide image config with format for Imagebitmap");let $=E();$.width=s.width,$.height=s.height;let x=C($);if(x!=null){let O=s.height,k=s.width;return x.drawImage(s,0,0,k,O),b=x.getImageData(0,0,k,O).data,w.height=O,w.width=k,ye(b,w)}else throw new Error("Can not access image data")}else{if(T)return new Promise(($,x)=>{let O=E(),k=C(O);if(!s||!k)return x();let D=new Image;D.crossOrigin="Anonymous",D.src=s,D.onload=()=>{O.width=D.width,O.height=D.height,k.drawImage(D,0,0,O.width,O.height);let P=k.getImageData(0,0,O.width,O.height);w.height=O.height,w.width=O.width,$(ye(P.data,w))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(b!==void 0)return ye(b,w);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(s,u)=>{let{width:p,height:m,download:y,dispose:T}=u,b=[1,m,p,4];return new wt({location:"texture",type:"float32",texture:s,dims:b,download:y,dispose:T})},Se=(s,u)=>{let{dataType:p,dims:m,download:y,dispose:T}=u;return new wt({location:"gpu-buffer",type:p??"float32",gpuBuffer:s,dims:m,download:y,dispose:T})},$e=(s,u)=>{let{dataType:p,dims:m,download:y,dispose:T}=u;return new wt({location:"ml-tensor",type:p??"float32",mlTensor:s,dims:m,download:y,dispose:T})},zt=(s,u,p)=>new wt({location:"cpu-pinned",type:s,data:u,dims:p??[u.length]})}),fe,se,st,We,ht=d(()=>{fe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),se=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),st=!1,We=()=>{if(!st){st=!0;let s=typeof BigInt64Array<"u"&&BigInt64Array.from,u=typeof BigUint64Array<"u"&&BigUint64Array.from,p=globalThis.Float16Array,m=typeof p<"u"&&p.from;s&&(fe.set("int64",BigInt64Array),se.set(BigInt64Array,"int64")),u&&(fe.set("uint64",BigUint64Array),se.set(BigUint64Array,"uint64")),m?(fe.set("float16",p),se.set(p,"float16")):fe.set("float16",Uint16Array)}}}),It,qe,Ue=d(()=>{Yt(),It=s=>{let u=1;for(let p=0;p<s.length;p++){let m=s[p];if(typeof m!="number"||!Number.isSafeInteger(m))throw new TypeError(`dims[${p}] must be an integer, got: ${m}`);if(m<0)throw new RangeError(`dims[${p}] must be a non-negative integer, got: ${m}`);u*=m}return u},qe=(s,u)=>{switch(s.location){case"cpu":return new wt(s.type,s.data,u);case"cpu-pinned":return new wt({location:"cpu-pinned",data:s.data,type:s.type,dims:u});case"texture":return new wt({location:"texture",texture:s.texture,type:s.type,dims:u});case"gpu-buffer":return new wt({location:"gpu-buffer",gpuBuffer:s.gpuBuffer,type:s.type,dims:u});case"ml-tensor":return new wt({location:"ml-tensor",mlTensor:s.mlTensor,type:s.type,dims:u});default:throw new Error(`tensorReshape: tensor location ${s.location} is not supported`)}}}),wt,Yt=d(()=>{ue(),Ae(),ht(),Ue(),wt=class{constructor(s,u,p){We();let m,y;if(typeof s=="object"&&"location"in s)switch(this.dataLocation=s.location,m=s.type,y=s.dims,s.location){case"cpu-pinned":{let b=fe.get(m);if(!b)throw new TypeError(`unsupported type "${m}" to create tensor from pinned buffer`);if(!(s.data instanceof b))throw new TypeError(`buffer should be of type ${b.name}`);this.cpuData=s.data;break}case"texture":{if(m!=="float32")throw new TypeError(`unsupported type "${m}" to create tensor from texture`);this.gpuTextureData=s.texture,this.downloader=s.download,this.disposer=s.dispose;break}case"gpu-buffer":{if(m!=="float32"&&m!=="float16"&&m!=="int32"&&m!=="int64"&&m!=="uint32"&&m!=="uint8"&&m!=="bool"&&m!=="uint4"&&m!=="int4")throw new TypeError(`unsupported type "${m}" to create tensor from gpu buffer`);this.gpuBufferData=s.gpuBuffer,this.downloader=s.download,this.disposer=s.dispose;break}case"ml-tensor":{if(m!=="float32"&&m!=="float16"&&m!=="int32"&&m!=="int64"&&m!=="uint32"&&m!=="uint64"&&m!=="int8"&&m!=="uint8"&&m!=="bool"&&m!=="uint4"&&m!=="int4")throw new TypeError(`unsupported type "${m}" to create tensor from MLTensor`);this.mlTensorData=s.mlTensor,this.downloader=s.download,this.disposer=s.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let b,w;if(typeof s=="string")if(m=s,w=p,s==="string"){if(!Array.isArray(u))throw new TypeError("A string tensor's data must be a string array.");b=u}else{let E=fe.get(s);if(E===void 0)throw new TypeError(`Unsupported tensor type: ${s}.`);if(Array.isArray(u)){if(s==="float16"&&E===Uint16Array||s==="uint4"||s==="int4")throw new TypeError(`Creating a ${s} tensor from number array is not supported. Please use ${E.name} as data.`);s==="uint64"||s==="int64"?b=E.from(u,BigInt):b=E.from(u)}else if(u instanceof E)b=u;else if(u instanceof Uint8ClampedArray)if(s==="uint8")b=Uint8Array.from(u);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(s==="float16"&&u instanceof Uint16Array&&E!==Uint16Array)b=new globalThis.Float16Array(u.buffer,u.byteOffset,u.length);else throw new TypeError(`A ${m} tensor's data must be type of ${E}`)}else if(w=u,Array.isArray(s)){if(s.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let E=typeof s[0];if(E==="string")m="string",b=s;else if(E==="boolean")m="bool",b=Uint8Array.from(s);else throw new TypeError(`Invalid element type of data array: ${E}.`)}else if(s instanceof Uint8ClampedArray)m="uint8",b=Uint8Array.from(s);else{let E=se.get(s.constructor);if(E===void 0)throw new TypeError(`Unsupported type for tensor data: ${s.constructor}.`);m=E,b=s}if(w===void 0)w=[b.length];else if(!Array.isArray(w))throw new TypeError("A tensor's dims must be a number array");y=w,this.cpuData=b,this.dataLocation="cpu"}let T=It(y);if(this.cpuData&&T!==this.cpuData.length&&!((m==="uint4"||m==="int4")&&Math.ceil(T/2)===this.cpuData.length))throw new Error(`Tensor's size(${T}) does not match data length(${this.cpuData.length}).`);this.type=m,this.dims=y,this.size=T}static async fromImage(s,u){return Re(s,u)}static fromTexture(s,u){return J(s,u)}static fromGpuBuffer(s,u){return Se(s,u)}static fromMLTensor(s,u){return $e(s,u)}static fromPinnedBuffer(s,u,p){return zt(s,u,p)}toDataURL(s){return me(this,s)}toImageData(s){return _e(this,s)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(s){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let u=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=u,s&&this.disposer&&(this.disposer(),this.disposer=void 0),u}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(s){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return qe(this,s)}}}),Xe,Je=d(()=>{Yt(),Xe=wt}),ut,_t,mt,Le,Pe,Ze,Tt=d(()=>{Ne(),ut=(s,u)=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||console.timeStamp(`${s}::ORT::${u}`)},_t=(s,u)=>{let p=new Error().stack?.split(/\r\n|\r|\n/g)||[],m=!1;for(let y=0;y<p.length;y++){if(m&&!p[y].includes("TRACE_FUNC")){let T=`FUNC_${s}::${p[y].trim().split(" ")[1]}`;u&&(T+=`::${u}`),ut("CPU",T);return}p[y].includes("TRACE_FUNC")&&(m=!0)}},mt=s=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||_t("BEGIN",s)},Le=s=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||_t("END",s)},Pe=s=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||console.time(`ORT::${s}`)},Ze=s=>{(typeof be.trace>"u"?!be.wasm.trace:!be.trace)||console.timeEnd(`ORT::${s}`)}}),qt,rn=d(()=>{ae(),Je(),Tt(),qt=class yb{constructor(u){this.handler=u}async run(u,p,m){mt(),Pe("InferenceSession.run");let y={},T={};if(typeof u!="object"||u===null||u instanceof Xe||Array.isArray(u))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let b=!0;if(typeof p=="object"){if(p===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(p instanceof Xe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(p)){if(p.length===0)throw new TypeError("'fetches' cannot be an empty array.");b=!1;for(let C of p){if(typeof C!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(C)===-1)throw new RangeError(`'fetches' contains invalid output name: ${C}.`);y[C]=null}if(typeof m=="object"&&m!==null)T=m;else if(typeof m<"u")throw new TypeError("'options' must be an object.")}else{let C=!1,$=Object.getOwnPropertyNames(p);for(let x of this.outputNames)if($.indexOf(x)!==-1){let O=p[x];(O===null||O instanceof Xe)&&(C=!0,b=!1,y[x]=O)}if(C){if(typeof m=="object"&&m!==null)T=m;else if(typeof m<"u")throw new TypeError("'options' must be an object.")}else T=p}}else if(typeof p<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let C of this.inputNames)if(typeof u[C]>"u")throw new Error(`input '${C}' is missing in 'feeds'.`);if(b)for(let C of this.outputNames)y[C]=null;let w=await this.handler.run(u,y,T),E={};for(let C in w)if(Object.hasOwnProperty.call(w,C)){let $=w[C];$ instanceof Xe?E[C]=$:E[C]=new Xe($.type,$.data,$.dims)}return Ze("InferenceSession.run"),Le(),E}async release(){return this.handler.dispose()}static async create(u,p,m,y){mt(),Pe("InferenceSession.create");let T,b={};if(typeof u=="string"){if(T=u,typeof p=="object"&&p!==null)b=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else if(u instanceof Uint8Array){if(T=u,typeof p=="object"&&p!==null)b=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else if(u instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&u instanceof SharedArrayBuffer){let $=u,x=0,O=u.byteLength;if(typeof p=="object"&&p!==null)b=p;else if(typeof p=="number"){if(x=p,!Number.isSafeInteger(x))throw new RangeError("'byteOffset' must be an integer.");if(x<0||x>=$.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${$.byteLength}).`);if(O=u.byteLength-x,typeof m=="number"){if(O=m,!Number.isSafeInteger(O))throw new RangeError("'byteLength' must be an integer.");if(O<=0||x+O>$.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${$.byteLength-x}].`);if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else if(typeof m<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof p<"u")throw new TypeError("'options' must be an object.");T=new Uint8Array($,x,O)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[w,E]=await K(b),C=await w.createInferenceSessionHandler(T,E);return Ze("InferenceSession.create"),Le(),new yb(C)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Dt,Wn=d(()=>{rn(),Dt=qt}),Pn=d(()=>{}),Bs=d(()=>{}),Aa=d(()=>{}),jr=d(()=>{}),ar={};A(ar,{InferenceSession:()=>Dt,TRACE:()=>ut,TRACE_EVENT_BEGIN:()=>Pe,TRACE_EVENT_END:()=>Ze,TRACE_FUNC_BEGIN:()=>mt,TRACE_FUNC_END:()=>Le,Tensor:()=>Xe,env:()=>Q,registerBackend:()=>W});var _n=d(()=>{ee(),ce(),Wn(),Je(),Pn(),Bs(),Tt(),Aa(),jr()}),Gr=d(()=>{}),yi={};A(yi,{default:()=>de});var Wr,Kr,de,Pt=d(()=>{tb(),gr(),Ks(),Wr="ort-wasm-proxy-worker",Kr=globalThis.self?.name===Wr,Kr&&(self.onmessage=s=>{let{type:u,in:p}=s.data;try{switch(u){case"init-wasm":Ia(p.wasm).then(()=>{kh(p).then(()=>{postMessage({type:u})},m=>{postMessage({type:u,err:m})})},m=>{postMessage({type:u,err:m})});break;case"init-ep":{let{epName:m,env:y}=p;Dh(y,m).then(()=>{postMessage({type:u})},T=>{postMessage({type:u,err:T})});break}case"copy-from":{let{buffer:m}=p,y=ic(m);postMessage({type:u,out:y});break}case"create":{let{model:m,options:y}=p;Mh(m,y).then(T=>{postMessage({type:u,out:T})},T=>{postMessage({type:u,err:T})});break}case"release":Uh(p),postMessage({type:u});break;case"run":{let{sessionId:m,inputIndices:y,inputs:T,outputIndices:b,options:w}=p;Lh(m,y,T,b,new Array(b.length).fill(null),w).then(E=>{E.some(C=>C[3]!=="cpu")?postMessage({type:u,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:u,out:E},Hh([...T,...E]))},E=>{postMessage({type:u,err:E})});break}case"end-profiling":qh(p),postMessage({type:u});break;default:}}catch(m){postMessage({type:u,err:m})}}),de=Kr?null:s=>new Worker(s??gn,{type:"classic",name:Wr})}),or,lr,gn,Vs,$r,vi,Ti,js,bi,Gs,wi,Ws,Si,Ks=d(()=>{Gr(),or=typeof location>"u"?void 0:location.origin,lr=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,gn=lr(),Vs=()=>{if(gn&&!gn.startsWith("blob:"))return gn.substring(0,gn.lastIndexOf("/")+1)},$r=(s,u)=>{try{let p=u??gn;return(p?new URL(s,p):new URL(s)).origin===or}catch{return!1}},vi=(s,u)=>{let p=u??gn;try{return(p?new URL(s,p):new URL(s)).href}catch{return}},Ti=(s,u)=>`${u??"./"}${s}`,js=async s=>{let u=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(u)},bi=async s=>(await import(s)).default,Gs=(Pt(),R(yi)).default,wi=async()=>{if(!gn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if($r(gn))return[void 0,Gs()];let s=await js(gn);return[s,Gs(s)]},Ws=void 0,Si=async(s,u,p,m)=>{let y=Ws&&!(s||u);if(y)if(gn)y=$r(gn);else if(m&&!p)y=!0;else throw new Error("cannot determine the script source URL.");if(y)return[void 0,Ws];{let T="ort-wasm-simd-threaded.jsep.mjs",b=s??vi(T,u),w=p&&b&&!$r(b,u),E=w?await js(b):b??Ti(T,u);return[w?E:void 0,await bi(E)]}}}),Qn,ds,Yr,mr,Ei,Ci,ur,Ia,$t,gr=d(()=>{Ks(),ds=!1,Yr=!1,mr=!1,Ei=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},Ci=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},ur=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Ia=async s=>{if(ds)return Promise.resolve();if(Yr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(mr)throw new Error("previous call to 'initializeWebAssembly()' failed.");Yr=!0;let u=s.initTimeout,p=s.numThreads;if(s.simd!==!1){if(s.simd==="relaxed"){if(!ur())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ci())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let m=Ei();p>1&&!m&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+p+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),s.numThreads=p=1);let y=s.wasmPaths,T=typeof y=="string"?y:void 0,b=y?.mjs,w=b?.href??b,E=y?.wasm,C=E?.href??E,$=s.wasmBinary,[x,O]=await Si(w,T,p>1,!!$||!!C),k=!1,D=[];if(u>0&&D.push(new Promise(P=>{setTimeout(()=>{k=!0,P()},u)})),D.push(new Promise((P,F)=>{let L={numThreads:p};if($)L.wasmBinary=$;else if(C||T)L.locateFile=U=>C??T+U;else if(w&&w.indexOf("blob:")!==0)L.locateFile=U=>new URL(U,w).href;else if(x){let U=Vs();U&&(L.locateFile=V=>U+V)}O(L).then(U=>{Yr=!1,ds=!0,Qn=U,P(),x&&URL.revokeObjectURL(x)},U=>{Yr=!1,mr=!0,F(U)})})),await Promise.race(D),k)throw new Error(`WebAssembly backend initializing failed due to timeout: ${u}ms`)},$t=()=>{if(ds&&Qn)return Qn;throw new Error("WebAssembly is not initialized yet.")}}),yn,hs,Et,yr=d(()=>{gr(),yn=(s,u)=>{let p=$t(),m=p.lengthBytesUTF8(s)+1,y=p._malloc(m);return p.stringToUTF8(s,y,m),u.push(y),y},hs=(s,u,p,m)=>{if(typeof s=="object"&&s!==null){if(p.has(s))throw new Error("Circular reference in options");p.add(s)}Object.entries(s).forEach(([y,T])=>{let b=u?u+y:y;if(typeof T=="object")hs(T,b+".",p,m);else if(typeof T=="string"||typeof T=="number")m(b,T.toString());else if(typeof T=="boolean")m(b,T?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof T}`)})},Et=s=>{let u=$t(),p=u.stackSave();try{let m=u.PTR_SIZE,y=u.stackAlloc(2*m);u._OrtGetLastError(y,y+m);let T=Number(u.getValue(y,m===4?"i32":"i64")),b=u.getValue(y+m,"*"),w=b?u.UTF8ToString(b):"";throw new Error(`${s} ERROR_CODE: ${T}, ERROR_MESSAGE: ${w}`)}finally{u.stackRestore(p)}}}),Ai,vr=d(()=>{gr(),yr(),Ai=s=>{let u=$t(),p=0,m=[],y=s||{};try{if(s?.logSeverityLevel===void 0)y.logSeverityLevel=2;else if(typeof s.logSeverityLevel!="number"||!Number.isInteger(s.logSeverityLevel)||s.logSeverityLevel<0||s.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${s.logSeverityLevel}`);if(s?.logVerbosityLevel===void 0)y.logVerbosityLevel=0;else if(typeof s.logVerbosityLevel!="number"||!Number.isInteger(s.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${s.logVerbosityLevel}`);s?.terminate===void 0&&(y.terminate=!1);let T=0;return s?.tag!==void 0&&(T=yn(s.tag,m)),p=u._OrtCreateRunOptions(y.logSeverityLevel,y.logVerbosityLevel,!!y.terminate,T),p===0&&Et("Can't create run options."),s?.extra!==void 0&&hs(s.extra,"",new WeakSet,(b,w)=>{let E=yn(b,m),C=yn(w,m);u._OrtAddRunConfigEntry(p,E,C)!==0&&Et(`Can't set a run config entry: ${b} - ${w}.`)}),[p,m]}catch(T){throw p!==0&&u._OrtReleaseRunOptions(p),m.forEach(b=>u._free(b)),T}}}),Ii,Ri,xr,Tr,cr,$i,Ra=d(()=>{gr(),yr(),Ii=s=>{switch(s){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${s}`)}},Ri=s=>{switch(s){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${s}`)}},xr=s=>{s.extra||(s.extra={}),s.extra.session||(s.extra.session={});let u=s.extra.session;u.use_ort_model_bytes_directly||(u.use_ort_model_bytes_directly="1"),s.executionProviders&&s.executionProviders.some(p=>(typeof p=="string"?p:p.name)==="webgpu")&&(s.enableMemPattern=!1)},Tr=(s,u,p,m)=>{let y=yn(u,m),T=yn(p,m);$t()._OrtAddSessionConfigEntry(s,y,T)!==0&&Et(`Can't set a session config entry: ${u} - ${p}.`)},cr=async(s,u,p)=>{for(let m of u){let y=typeof m=="string"?m:m.name,T=[];switch(y){case"webnn":if(y="WEBNN",typeof m!="string"){let $=m?.deviceType;$&&Tr(s,"deviceType",$,p)}break;case"webgpu":if(y="JS",typeof m!="string"){let $=m;if($?.preferredLayout){if($.preferredLayout!=="NCHW"&&$.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${$.preferredLayout}`);Tr(s,"preferredLayout",$.preferredLayout,p)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${y}`)}let b=yn(y,p),w=T.length,E=0,C=0;if(w>0){E=$t()._malloc(w*$t().PTR_SIZE),p.push(E),C=$t()._malloc(w*$t().PTR_SIZE),p.push(C);for(let $=0;$<w;$++)$t().setValue(E+$*$t().PTR_SIZE,T[$][0],"*"),$t().setValue(C+$*$t().PTR_SIZE,T[$][1],"*")}await $t()._OrtAppendExecutionProvider(s,b,E,C,w)!==0&&Et(`Can't append execution provider: ${y}.`)}},$i=async s=>{let u=$t(),p=0,m=[],y=s||{};xr(y);try{let T=Ii(y.graphOptimizationLevel??"all"),b=Ri(y.executionMode??"sequential"),w=typeof y.logId=="string"?yn(y.logId,m):0,E=y.logSeverityLevel??2;if(!Number.isInteger(E)||E<0||E>4)throw new Error(`log severity level is not valid: ${E}`);let C=y.logVerbosityLevel??0;if(!Number.isInteger(C)||C<0||C>4)throw new Error(`log verbosity level is not valid: ${C}`);let $=typeof y.optimizedModelFilePath=="string"?yn(y.optimizedModelFilePath,m):0;if(p=u._OrtCreateSessionOptions(T,!!y.enableCpuMemArena,!!y.enableMemPattern,b,!!y.enableProfiling,0,w,E,C,$),p===0&&Et("Can't create session options."),y.executionProviders&&await cr(p,y.executionProviders,m),y.enableGraphCapture!==void 0){if(typeof y.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${y.enableGraphCapture}`);Tr(p,"enableGraphCapture",y.enableGraphCapture.toString(),m)}if(y.freeDimensionOverrides)for(let[x,O]of Object.entries(y.freeDimensionOverrides)){if(typeof x!="string")throw new Error(`free dimension override name must be a string: ${x}`);if(typeof O!="number"||!Number.isInteger(O)||O<0)throw new Error(`free dimension override value must be a non-negative integer: ${O}`);let k=yn(x,m);u._OrtAddFreeDimensionOverride(p,k,O)!==0&&Et(`Can't set a free dimension override: ${x} - ${O}.`)}return y.extra!==void 0&&hs(y.extra,"",new WeakSet,(x,O)=>{Tr(p,x,O,m)}),[p,m]}catch(T){throw p!==0&&u._OrtReleaseSessionOptions(p)!==0&&Et("Can't release session options."),m.forEach(b=>u._free(b)),T}}}),br,Zn,wr,Or,ps,Ys,Xs,Js,rt=d(()=>{br=s=>{switch(s){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${s}`)}},Zn=s=>{switch(s){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${s}`)}},wr=(s,u)=>{let p=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][s],m=typeof u=="number"?u:u.reduce((y,T)=>y*T,1);return p>0?Math.ceil(m*p):void 0},Or=s=>{switch(s){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${s}`)}},ps=s=>{switch(s){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${s}`)}},Ys=s=>s==="float32"||s==="float16"||s==="int32"||s==="int64"||s==="uint32"||s==="uint8"||s==="bool"||s==="uint4"||s==="int4",Xs=s=>s==="float32"||s==="float16"||s==="int32"||s==="int64"||s==="uint32"||s==="uint64"||s==="int8"||s==="uint8"||s==="bool"||s==="uint4"||s==="int4",Js=s=>{switch(s){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${s}`)}}}),Qs,xi=d(()=>{Gr(),Qs=async s=>{if(typeof s=="string"){let u=await fetch(s);if(!u.ok)throw new Error(`failed to load external data file: ${s}`);let p=u.headers.get("Content-Length"),m=p?parseInt(p,10):0;if(m<1073741824)return new Uint8Array(await u.arrayBuffer());{if(!u.body)throw new Error(`failed to load external data file: ${s}, no response body.`);let y=u.body.getReader(),T;try{T=new ArrayBuffer(m)}catch(w){if(w instanceof RangeError){let E=Math.ceil(m/65536);T=new WebAssembly.Memory({initial:E,maximum:E}).buffer}else throw w}let b=0;for(;;){let{done:w,value:E}=await y.read();if(w)break;let C=E.byteLength;new Uint8Array(T,b,C).set(E),b+=C}return new Uint8Array(T,0,m)}}else return s instanceof Blob?new Uint8Array(await s.arrayBuffer()):s instanceof Uint8Array?s:new Uint8Array(s)}}),Oi,ki,kr,Di,Zs,Ni,vt,Sr=d(()=>{rt(),Oi=["V","I","W","E","F"],ki=(s,u)=>{console.log(`[${Oi[s]},${new Date().toISOString()}]${u}`)},Zs=(s,u)=>{kr=s,Di=u},Ni=(s,u)=>{let p=ps(s),m=ps(kr);p>=m&&ki(p,typeof u=="function"?u():u)},vt=(...s)=>{Di&&Ni(...s)}}),lo,_s,ne,fn,Dr,fs,Mi,ct=d(()=>{lo=class{static calcMatMulShape(s,u){return s[1]!==u[0]?void 0:[s[0],u[1]]}},_s=class{static calcShape(s,u,p=!1){let m=s.length,y=u.length;if(m===0)return u;if(y===0)return s;let T=Math.max(s.length,u.length),b=new Array(T);if(p){if(m<2||y<2)return;let w=lo.calcMatMulShape([s[m-2],s[m-1]],[u[y-2],u[y-1]]);if(w===void 0)return;[b[T-2],b[T-1]]=w}for(let w=p?3:1;w<=T;w++){let E=m-w<0?1:s[m-w],C=y-w<0?1:u[y-w];if(E!==C&&E>1&&C>1)return;let $=Math.max(E,C);if(E&&C)b[T-w]=Math.max(E,C);else{if($>1)return;b[T-w]=0}}return b}static isValidBroadcast(s,u){let p=s.length,m=u.length;if(p>m)return!1;for(let y=1;y<=p;y++)if(s[p-y]!==1&&s[p-y]!==u[m-y])return!1;return!0}},ne=class lc{static size(u){return lc.getSizeFromDimensionRange(u,0,u.length)}static convertShape(u,p=4){let m=u.length;if(m===0)return[];let y=new Array(m),T=m-1;for(;T>=0;){if(u[T]%p===0){y[T]=u[T]/p;break}if(p%u[T]!==0)throw new Error("cannot convert shape");y[T]=1,p/=u[T],T--}for(T--;T>=0;T--)y[T]=u[T];return y}static sizeFromDimension(u,p){if(p<0||p>u.length)throw new Error(`invalid dimension of ${p} for sizeFromDimension as Tensor has ${u.length} dimensions.`);return lc.getSizeFromDimensionRange(u,p,u.length)}static sizeToDimension(u,p){if(p<0||p>u.length)throw new Error(`invalid dimension of ${p} for sizeToDimension as Tensor has ${u.length} dimensions.`);return lc.getSizeFromDimensionRange(u,0,p)}static getSizeFromDimensionRange(u,p,m){let y=1;for(let T=p;T<m;T++){if(u[T]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");y*=Number(u[T])}return y}static computeStrides(u){let p=u.length;if(p===0)return[];if(p===1)return[1];let m=new Array(p);m[p-1]=1,m[p-2]=u[p-1];for(let y=p-3;y>=0;--y)m[y]=m[y+1]*u[y+1];return m}static normalizeAxis(u,p){if(u<-p&&u>=p)throw new Error("unsupported axis for this operation.");return u<0?u+p:u}static normalizeAxes(u,p){return u.map(m=>this.normalizeAxis(m,p??u.length))}static sortBasedOnPerm(u,p){return p?p.map(m=>u[m]):u.slice().reverse()}static padShape(u,p){let m=u.length;return u.map((y,T)=>y+p[T]+p[T+m])}static areEqual(u,p){return u.length!==p.length?!1:u.every((m,y)=>m===p[y])}},fn=class Ul{static adjustPoolAttributes(u,p,m,y,T,b){if(!u&&m.length!==p.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(u)for(let w=0;w<p.length-2;w++)w>=m.length?m.push(p[w+2]):m[w]=p[w+2];for(let w=0;w<m.length;w++)if(w<y.length){if(y[w]<0)throw new Error("strides should be greater than or equal to 1")}else y.push(1);for(let w=0;w<m.length;w++)if(w<T.length){if(T[w]<0)throw new Error("dilations should be greater than or equal to 1")}else T.push(1);for(let w=0;w<m.length*2;w++)if(w<b.length){if(b[w]<0)throw new Error("pad should be greater than or equal to 1")}else b.push(0);for(let w=0;w<m.length;w++){if(m[w]<=0)throw new Error("kernel shapes need to be greater than 0");if(b[w]>=m[w]||b[w+m.length]>=m[w])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(u,p,m,y,T,b,w){if(w){if(T.length!==2*(u.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(p.length!==u.length-2)throw new Error("length of strides should be the length of data dimensions");if(y.length!==u.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let E=0;E<u.length-2;E++)Ul.adjustPadAndReturnShape(u[E+(b?1:2)],p[E],m[E],y[E],T,E,E+u.length-2,w)}}static computePoolOutputShape(u,p,m,y,T,b,w){if(p.length<=0)throw new Error("input shape must be of size greater than 0");let E=[p[0],p[1]];return Ul.computeShapeHelper(u,p,E,m,y,T,b,w),E}static computeConvOutputShape(u,p,m,y,T,b,w){if(u.length<=0||p.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let E=[u[0],p[0]];return Ul.computeShapeHelper(!1,u,E,m,y,T,b,w),E}static computeShapeHelper(u,p,m,y,T,b,w,E){if(u)for(let C=0;C<p.length-2;C++)m.push(1);else for(let C=0;C<p.length-2;C++)m.push(Ul.adjustPadAndReturnShape(p[C+2],y[C],T[C],b[C],w,C,C+p.length-2,E))}static adjustPadAndReturnShape(u,p,m,y,T,b,w,E){let C=m*(y-1)+1;if(E&&E!=="NOTSET")switch(E){case"VALID":return T[b]=0,T[w]=0,Math.floor((u-C)/p+1);case"SAME_LOWER":case"SAME_UPPER":if(m!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let $=((u+p-1)/p-1)*p+y-u;return T[b]=Math.floor(E==="SAME_LOWER"?($+1)/2:$/2),T[w]=$-T[b],Math.floor((u+$-y)/p+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((u+T[b]+T[w]-C)/p+1)}},Dr=class{static getShapeOfGemmResult(s,u,p,m,y){if(s.length!==2||p.length!==2)throw new Error("shape need to be of size 2");let T,b,w;u?(T=s[1],b=s[0]):(T=s[0],b=s[1]);let E=-1;if(m?(w=p[0],E=1):(w=p[1],E=0),p[E]!==b)throw new Error("dimension mismatch");if(T<=0||w<=0||b<=0)throw new Error("invalid shape specified");if(y&&!_s.isValidBroadcast(y,[T,w]))throw new Error("gemm: invalid bias shape for broadcast");return[T,w,b]}},fs=-34028234663852886e22,Mi=34028234663852886e22}),vn,Ui=d(()=>{rt(),vn=(s,u)=>new(Or(u))(s)}),gt,ei,$a,Pi,Xr,Li,xa,Oa,ka,qi,Hi,Da=d(()=>{rt(),Sr(),gt=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ei=(s,u)=>{if(u==="int32")return s;let p=gt.get(u);if(!p)throw new Error(`WebNN backend does not support data type: ${u}`);let m=p/8;if(s.byteLength%m!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${m}.`);let y=s.byteLength/m,T=new(Or(u))(s.buffer,s.byteOffset,y);switch(u){case"int64":case"uint64":{let b=new Int32Array(y);for(let w=0;w<y;w++){let E=T[w];if(E>2147483647n||E<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");b[w]=Number(E)}return new Uint8Array(b.buffer)}case"int8":case"uint8":case"uint32":{if(u==="uint32"&&T.some(w=>w>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let b=Int32Array.from(T,Number);return new Uint8Array(b.buffer)}default:throw new Error(`Unsupported data conversion from ${u} to 'int32'`)}},$a=(s,u)=>{if(u==="int32")return s;if(s.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let p=s.byteLength/4,m=new Int32Array(s.buffer,s.byteOffset,p);switch(u){case"int64":{let y=BigInt64Array.from(m,BigInt);return new Uint8Array(y.buffer)}case"uint64":{if(m.some(T=>T<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let y=BigUint64Array.from(m,BigInt);return new Uint8Array(y.buffer)}case"int8":{if(m.some(T=>T<-128||T>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let y=Int8Array.from(m,Number);return new Uint8Array(y.buffer)}case"uint8":{if(m.some(y=>y<0||y>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(m,Number)}case"uint32":{if(m.some(T=>T<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let y=Uint32Array.from(m,Number);return new Uint8Array(y.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${u}`)}},Pi=1,Xr=()=>Pi++,Li=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),xa=(s,u)=>{let p=gt.get(s);if(!p)throw new Error(`WebNN backend does not support data type: ${s}`);return u.length>0?Math.ceil(u.reduce((m,y)=>m*y)*p/8):0},Oa=class{constructor(s){this.isDataConverted=!1;let{sessionId:u,context:p,tensor:m,dataType:y,shape:T,fallbackDataType:b}=s;this.sessionId=u,this.mlContext=p,this.mlTensor=m,this.dataType=y,this.tensorShape=T,this.fallbackDataType=b}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return xa(this.dataType,this.tensorShape)}destroy(){vt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(s){this.mlContext.writeTensor(this.mlTensor,s)}async read(s){if(this.fallbackDataType){let u=await this.mlContext.readTensor(this.mlTensor),p=$a(new Uint8Array(u),this.dataType);if(s){(s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)).set(p);return}else return p.buffer}else return s?this.mlContext.readTensor(this.mlTensor,s):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(s,u,p){return this.mlContext===s&&this.dataType===u&&this.tensorShape.length===p.length&&this.tensorShape.every((m,y)=>m===p[y])}setIsDataConverted(s){this.isDataConverted=s}},ka=class{constructor(s,u){this.tensorManager=s,this.wrapper=u}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(s,u,p,m){let y=this.tensorManager.getMLContext(s),T;if(!y.opSupportLimits().input.dataTypes.includes(u)){if(T=Li.get(u),!T||!y.opSupportLimits().input.dataTypes.includes(T))throw new Error(`WebNN backend does not support data type: ${u}`);vt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${u} to ${T}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(y,u,p))return this.wrapper.tensor;if(m){if(this.wrapper.byteLength!==xa(u,p))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let b=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(s,u,p,b,!0,!0,T),m&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(s){let u=s;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")u=ei(s,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(s.byteLength===this.wrapper.byteLength){this.wrapper.write(u);return}else vt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(u):this.activeUpload=new Uint8Array(u)}async download(s){if(this.activeUpload){let u=this.wrapper?.isDataConverted?$a(this.activeUpload,this.wrapper?.type):this.activeUpload;if(s){s instanceof ArrayBuffer?new Uint8Array(s).set(u):new Uint8Array(s.buffer,s.byteOffset,s.byteLength).set(u);return}else return u.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return s?this.wrapper.read(s):this.wrapper.read()}},qi=class{constructor(s){this.backend=s,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(s){let u=this.backend.getMLContext(s);if(!u)throw new Error("MLContext not found for session.");return u}reserveTensorId(){let s=Xr();return this.tensorTrackersById.set(s,new ka(this)),s}releaseTensorId(s){let u=this.tensorTrackersById.get(s);u&&(this.tensorTrackersById.delete(s),u.tensorWrapper&&this.releaseTensor(u.tensorWrapper))}async ensureTensor(s,u,p,m,y){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${u}, dataType: ${p}, shape: ${m}, copyOld: ${y}}`);let T=this.tensorTrackersById.get(u);if(!T)throw new Error("Tensor not found.");return T.ensureTensor(s,p,m,y)}upload(s,u){let p=this.tensorTrackersById.get(s);if(!p)throw new Error("Tensor not found.");p.upload(u)}async download(s,u){vt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${s}, dstBuffer: ${u?.byteLength}}`);let p=this.tensorTrackersById.get(s);if(!p)throw new Error("Tensor not found.");return p.download(u)}releaseTensorsForSession(s){for(let u of this.freeTensors)u.sessionId===s&&u.destroy();this.freeTensors=this.freeTensors.filter(u=>u.sessionId!==s)}registerTensor(s,u,p,m){let y=this.getMLContext(s),T=Xr(),b=new Oa({sessionId:s,context:y,tensor:u,dataType:p,shape:m});return this.tensorTrackersById.set(T,new ka(this,b)),this.externalTensors.add(b),T}async getCachedTensor(s,u,p,m,y,T,b){let w=this.getMLContext(s);for(let[C,$]of this.freeTensors.entries())if($.canReuseTensor(w,u,p)){vt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${u}, ${b?`fallbackDataType: ${b},`:""} shape: ${p}`);let x=this.freeTensors.splice(C,1)[0];return x.sessionId=s,x}vt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${u}, ${b?`fallbackDataType: ${b},`:""} shape: ${p}}`);let E=await w.createTensor({dataType:b??u,shape:p,dimensions:p,usage:m,writable:y,readable:T});return new Oa({sessionId:s,context:w,tensor:E,dataType:u,shape:p,fallbackDataType:b})}releaseTensor(s){this.externalTensors.has(s)&&this.externalTensors.delete(s),this.freeTensors.push(s)}},Hi=(...s)=>new qi(...s)}),Jr,Nr,zi,Na=d(()=>{rt(),gr(),Ui(),Da(),Sr(),Jr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Nr=(s,u)=>{if(s===u)return!0;if(s===void 0||u===void 0)return!1;let p=Object.keys(s).sort(),m=Object.keys(u).sort();return p.length===m.length&&p.every((y,T)=>y===m[T]&&s[y]===u[y])},zi=class{constructor(s){this.tensorManager=Hi(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,Zs(s.logLevel,!!s.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(s){vt("verbose",()=>`[WebNN] onRunStart {sessionId: ${s}}`),this.activeSessionId=s}onRunEnd(s){vt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${s}}`);let u=this.temporarySessionTensorIds.get(s);if(u){for(let p of u)vt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${p}}`),this.tensorManager.releaseTensorId(p);this.temporarySessionTensorIds.delete(s),this.activeSessionId=void 0}}async createMLContext(s){if(s instanceof GPUDevice){let p=this.mlContextCache.findIndex(m=>m.gpuDevice===s);if(p!==-1)return this.mlContextCache[p].mlContext;{let m=await navigator.ml.createContext(s);return this.mlContextCache.push({gpuDevice:s,mlContext:m}),m}}else if(s===void 0){let p=this.mlContextCache.findIndex(m=>m.options===void 0&&m.gpuDevice===void 0);if(p!==-1)return this.mlContextCache[p].mlContext;{let m=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:m}),m}}let u=this.mlContextCache.findIndex(p=>Nr(p.options,s));if(u!==-1)return this.mlContextCache[u].mlContext;{let p=await navigator.ml.createContext(s);return this.mlContextCache.push({options:s,mlContext:p}),p}}registerMLContext(s,u){this.mlContextBySessionId.set(s,u);let p=this.sessionIdsByMLContext.get(u);p||(p=new Set,this.sessionIdsByMLContext.set(u,p)),p.add(s),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(s,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(s,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(s){this.sessionGraphInputs.delete(s),this.sessionGraphOutputs.delete(s);let u=this.mlContextBySessionId.get(s);if(!u)return;this.tensorManager.releaseTensorsForSession(s),this.mlContextBySessionId.delete(s);let p=this.sessionIdsByMLContext.get(u);if(p.delete(s),p.size===0){this.sessionIdsByMLContext.delete(u);let m=this.mlContextCache.findIndex(y=>y.mlContext===u);m!==-1&&this.mlContextCache.splice(m,1)}}getMLContext(s){return this.mlContextBySessionId.get(s)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(s){vt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${s}}`),this.tensorManager.releaseTensorId(s)}async ensureTensor(s,u,p,m,y){let T=Jr.get(p);if(!T)throw new Error(`Unsupported ONNX data type: ${p}`);return this.tensorManager.ensureTensor(s??this.currentSessionId,u,T,m,y)}async createTemporaryTensor(s,u,p){vt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${u}, shape: ${p}}`);let m=Jr.get(u);if(!m)throw new Error(`Unsupported ONNX data type: ${u}`);let y=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(s,y,m,p,!1);let T=this.temporarySessionTensorIds.get(s);return T?T.push(y):this.temporarySessionTensorIds.set(s,[y]),y}uploadTensor(s,u){if(!$t().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");vt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${s}, data: ${u.byteLength}}`),this.tensorManager.upload(s,u)}async downloadTensor(s,u){return this.tensorManager.download(s,u)}createMLTensorDownloader(s,u){return async()=>{let p=await this.tensorManager.download(s);return vn(p,u)}}registerMLTensor(s,u,p,m){let y=Jr.get(p);if(!y)throw new Error(`Unsupported ONNX data type: ${p}`);let T=this.tensorManager.registerTensor(s,u,y,m);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${u}, dataType: ${y}, dimensions: ${m}} -> {tensorId: ${T}}`),T}registerMLConstant(s,u,p,m,y,T,b=!1){if(!T)throw new Error("External mounted files are not available.");let w=s;s.startsWith("./")&&(w=s.substring(2));let E=T.get(w);if(!E)throw new Error(`File with name ${w} not found in preloaded files.`);if(u+p>E.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let C=E.slice(u,u+p).buffer,$;switch(y.dataType){case"float32":$=new Float32Array(C);break;case"float16":$=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(C):new Uint16Array(C);break;case"int32":$=new Int32Array(C);break;case"uint32":$=new Uint32Array(C);break;case"int64":if(b){let x=ei(new Uint8Array(C),"int64");$=new Int32Array(x.buffer),y.dataType="int32"}else $=new BigInt64Array(C);break;case"uint64":$=new BigUint64Array(C);break;case"int8":$=new Int8Array(C);break;case"int4":case"uint4":case"uint8":$=new Uint8Array(C);break;default:throw new Error(`Unsupported data type: ${y.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${y.dataType}, shape: ${y.shape}}} ${b?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),m.constant(y,$)}registerGraphInput(s){this.temporaryGraphInputs.push(s)}registerGraphOutput(s){this.temporaryGraphOutputs.push(s)}isGraphInput(s,u){let p=this.sessionGraphInputs.get(s);return p?p.includes(u):!1}isGraphOutput(s,u){let p=this.sessionGraphOutputs.get(s);return p?p.includes(u):!1}isGraphInputOutputTypeSupported(s,u,p=!0){let m=this.mlContextBySessionId.get(s),y=Jr.get(br(u));return typeof y>"u"?!1:p?!!m?.opSupportLimits().input.dataTypes.includes(y):!!m?.opSupportLimits().output.dataTypes.includes(y)}flush(){}}}),Qr=d(()=>{}),ti,Fi,ms,uo,co,er,Ma,gs,ys,El=d(()=>{Sr(),Qr(),ti=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Fi=[],ms=s=>Math.ceil(Number(s)/16)*16,uo=s=>{for(let u=0;u<Fi.length;u++){let p=Fi[u];if(s<=p)return p}return Math.ceil(s/16)*16},co=1,er=()=>co++,Ma=async(s,u,p,m)=>{let y=ms(p),T=s.device.createBuffer({size:y,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let b=s.getCommandEncoder();s.endComputePass(),b.copyBufferToBuffer(u,0,T,0,y),s.flush(),await T.mapAsync(GPUMapMode.READ);let w=T.getMappedRange();if(m){let E=m();return E.set(new Uint8Array(w,0,p)),E}else return new Uint8Array(w.slice(0,p))}finally{T.destroy()}},gs=class{constructor(s){this.backend=s,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[u]of ti)Fi.push(u),this.freeBuffers.set(u,[]),this.freeUniformBuffers.set(u,[]);this.sessionCount=0}upload(s,u){let p=u.buffer,m=u.byteOffset,y=u.byteLength,T=ms(y),b=this.storageCache.get(s);if(!b)throw new Error("gpu data for uploading does not exist");if(Number(b.originalSize)!==y)throw new Error(`inconsistent data size. gpu data size=${b.originalSize}, data size=${y}`);let w=this.backend.device.createBuffer({mappedAtCreation:!0,size:T,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),E=w.getMappedRange();new Uint8Array(E).set(new Uint8Array(p,m,y)),w.unmap();let C=this.backend.device.createCommandEncoder();C.copyBufferToBuffer(w,0,b.gpuData.buffer,0,T),this.backend.device.queue.submit([C.finish()]),w.destroy(),vt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${s})`)}memcpy(s,u){let p=this.storageCache.get(s);if(!p)throw new Error("source gpu data for memcpy does not exist");let m=this.storageCache.get(u);if(!m)throw new Error("destination gpu data for memcpy does not exist");if(p.originalSize!==m.originalSize)throw new Error("inconsistent source and destination gpu data size");let y=ms(p.originalSize),T=this.backend.getCommandEncoder();this.backend.endComputePass(),T.copyBufferToBuffer(p.gpuData.buffer,0,m.gpuData.buffer,0,y)}registerExternalBuffer(s,u,p){let m;if(p){if(m=p[0],s===p[1])return vt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${u}) => id=${m}, buffer is the same, skip.`),m;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
164
164
|
Please use the previous external buffer!`)}else m=er();return this.storageCache.set(m,{gpuData:{id:m,type:0,buffer:s},originalSize:u}),vt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${u}) => id=${m}, registered.`),m}unregisterExternalBuffer(s){s!==void 0&&(this.storageCache.delete(s),vt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${s}`))}create(s,u=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let p=uo(s),m,y=(u&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,T=(u&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(y||T){let w=(y?this.freeBuffers:this.freeUniformBuffers).get(p);w?w.length>0?m=w.pop():m=this.backend.device.createBuffer({size:p,usage:u}):m=this.backend.device.createBuffer({size:p,usage:u})}else m=this.backend.device.createBuffer({size:p,usage:u});let b={id:er(),type:0,buffer:m};return this.storageCache.set(b.id,{gpuData:b,originalSize:Number(s)}),vt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${s}) => id=${b.id}`),b}get(s){return this.storageCache.get(s)?.gpuData}release(s){let u=typeof s=="bigint"?Number(s):s,p=this.storageCache.get(u);if(!p){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return vt("verbose",()=>`[WebGPU] GpuDataManager.release(id=${u}), gpuDataId=${p.gpuData.id}`),this.storageCache.delete(u),this.buffersPending.push(p.gpuData.buffer),p.originalSize}async download(s,u){let p=this.storageCache.get(Number(s));if(!p)throw new Error("data does not exist");await Ma(this.backend,p.gpuData.buffer,p.originalSize,u)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let s of this.buffersPending){let u=ti.get(s.size);if((s.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let p=this.freeBuffers.get(s.size)||[];u===void 0||p.length>=u?s.destroy():p.push(s)}else if((s.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let p=this.freeUniformBuffers.get(s.size)||[];u===void 0||p.length>=u?s.destroy():p.push(s)}else s.destroy()}this.buffersPending=[]}else{let s=this.capturedPendingBuffers.get(this.backend.currentSessionId);s||(s=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,s));for(let u of this.buffersPending)s.push(u);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(s=>{s.forEach(u=>{u.destroy()})}),this.freeUniformBuffers.forEach(s=>{s.forEach(u=>{u.destroy()})}),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(s=>{s.forEach(u=>{u.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(s){let u=this.capturedPendingBuffers.get(s);u&&(u.forEach(p=>{p.destroy()}),this.capturedPendingBuffers.delete(s)),this.sessionCount-=1,this.sessionCount===0&&(vt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(p=>{p.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ys=(...s)=>new gs(...s)}),ho,Ct,Ft=d(()=>{ho=class{constructor(s){Object.assign(this,s)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(s=>`${this[s]}`).join(";")),this.key}},Ct=s=>new ho(s)}),dr,vs,Nt,Gt,Qe,Ut,ni,Kn,hr,Ke,Zr,le,Ge,Bi,Er,po,_o,at=d(()=>{rt(),ct(),dr=64,vs=(s,u)=>{if(u===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(s)){case 10:return u>1?`vec${u}<f16>`:"f16";case 1:return u>1?`vec${u}<f32>`:"f32";case 6:return u>1?`vec${u}<i32>`:"i32";case 12:return u>1?`vec${u}<u32>`:"u32";case 7:if(u>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(u>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(u!==4)throw new Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${s}`)}},Nt=(s,u=1)=>{let p=vs(s,u);return typeof p=="string"?p:p[0]},Gt=(s,u=1)=>{let p=vs(s,u);return typeof p=="string"?p:p[1]},Qe=(...s)=>{let u=[];return s.forEach(p=>{p.length!==0&&u.push({type:12,data:p},{type:12,data:ne.computeStrides(p)})}),u},Ut=s=>s%4===0?4:s%2===0?2:1,ni=(s="f32",u,p="0")=>!u||u===1?`${s}(${p})`:`vec${u}<${s}>(${p})`,Kn=(s,u,p)=>s==="f32"?p:u===1?`f32(${p})`:`vec${u}<f32>(${p})`,hr=(s,u)=>u===4?`(${s}.x + ${s}.y + ${s}.z + ${s}.w)`:u===2?`(${s}.x + ${s}.y)`:u===3?`(${s}.x + ${s}.y + ${s}.z)`:s,Ke=(s,u,p,m)=>s.startsWith("uniforms.")&&p>4?typeof u=="string"?m==="f16"?`${s}[(${u}) / 8][(${u}) % 8 / 4][(${u}) % 8 % 4]`:`${s}[(${u}) / 4][(${u}) % 4]`:m==="f16"?`${s}[${Math.floor(u/8)}][${Math.floor(u%8/4)}][${u%8%4}]`:`${s}[${Math.floor(u/4)}][${u%4}]`:p>1?`${s}[${u}]`:s,Zr=(s,u,p,m,y)=>{let T=typeof p=="number",b=T?p:p.length,w=[...new Array(b).keys()],E=b<2?"u32":b<=4?`vec${b}<u32>`:`array<u32, ${b}>`,C=vs(u,y),$=typeof C=="string"?C:C[1],x=typeof C=="string"?C:C[0],O={indices:E,value:$,storage:x,tensor:u},k=ke=>typeof ke=="string"?ke:`${ke}u`,D={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},P=T?"uniforms.":"",F=`${P}${s}_shape`,L=`${P}${s}_strides`,U="";for(let ke=0;ke<b-1;ke++)U+=`
|
|
165
165
|
let dim${ke} = current / ${Ke(L,ke,b)};
|
|
166
166
|
let rest${ke} = current % ${Ke(L,ke,b)};
|
|
@@ -306,7 +306,7 @@ a=path:${n.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization
|
|
|
306
306
|
`)}
|
|
307
307
|
}`},getRunData:()=>({outputs:[{dims:E,dataType:T}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:[{type:12,data:D},...Qe(C,E)]})}},Ua=(s,u)=>{let p=[];return s[1].dims[0]>0&&s[1].getBigInt64Array().forEach(m=>p.push(Number(m))),Ct({axes:p,keepDims:u.keepDims,noopWithEmptyAxes:u.noopWithEmptyAxes})},zn=(s,u,p,m)=>{let y=s.inputs,T=y.length===1?p:Ua(y,p);s.compute(Cs(u,{hint:T.cacheKey,inputDependencies:["rank"]},[y[0]],T.noopWithEmptyAxes&&T.axes.length===0?Es:m,T.axes,y[0].dataType,T.keepDims,T.noopWithEmptyAxes),{inputs:[0]})},So=(s,u)=>{Hn(s.inputs),zn(s,"ReduceLogSum",u,(p,m)=>[`var value = ${m.type.storage}(0);`,"",`value += ${p.getByIndices("input_indices")};`,"value = log(value);"])},Eo=(s,u)=>{Hn(s.inputs),zn(s,"ReduceL1",u,(p,m)=>[`var value = ${m.type.storage}(0);`,"",`value += abs(${p.getByIndices("input_indices")});`,""])},ra=(s,u)=>{Hn(s.inputs),zn(s,"ReduceL2",u,(p,m)=>[`var t = ${m.type.value}(0); var value = ${m.type.value}(0);`,"",`t = ${p.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},sn=(s,u)=>{Hn(s.inputs),zn(s,"ReduceLogSumExp",u,(p,m)=>[`var value = ${m.type.storage}(0);`,"",`value += exp(${p.getByIndices("input_indices")});`,"value = log(value);"])},sa=(s,u)=>{Hn(s.inputs),zn(s,"ReduceMax",u,(p,m,y)=>{let T=[];for(let b=0;b<p.rank;b++)(y.indexOf(b)>=0||y.length===0)&&T.push(p.indicesSet("input_indices",b,0));return[`${T.join(`
|
|
308
308
|
`)}`,`var value = ${p.getByIndices("input_indices")};`,`value = max(value, ${p.getByIndices("input_indices")});`,""]})},ia=(s,u)=>{Hn(s.inputs),zn(s,"ReduceMean",u,(p,m,y)=>{let T=1;for(let b=0;b<p.rank;b++)(y.indexOf(b)>=0||y.length===0)&&(T*=s.inputs[0].dims[b]);return["var sum = f32(0);","",`sum += f32(${p.getByIndices("input_indices")});`,`let value = ${m.type.value}(sum / ${T});`]})},Co=(s,u)=>{Hn(s.inputs),zn(s,"ReduceMin",u,(p,m,y)=>{let T=[];for(let b=0;b<p.rank;b++)(y.indexOf(b)>=0||y.length===0)&&T.push(`input_indices[${b}] = 0;`);return[`${T.join(`
|
|
309
|
-
`)}`,`var value = ${p.getByIndices("input_indices")};`,`value = min(value, ${p.getByIndices("input_indices")});`,""]})},Ao=(s,u)=>{Hn(s.inputs),zn(s,"ReduceProd",u,(p,m)=>[`var value = ${m.type.storage}(1);`,"",`value *= ${p.getByIndices("input_indices")};`,""])},aa=(s,u)=>{Hn(s.inputs),zn(s,"ReduceSum",u,(p,m)=>[`var value = ${m.type.storage}(0);`,"",`value += ${p.getByIndices("input_indices")};`,""])},As=(s,u)=>{Hn(s.inputs),zn(s,"ReduceSumSquare",u,(p,m)=>[`var t = ${m.type.value}(0); var value = ${m.type.value}(0);`,"",`t = ${p.getByIndices("input_indices")}; value += t * t;`,""])},Fn=(s,u,p)=>{if(u.length===0)return p;let m=1,y=1;for(let T=0;T<u.length;T++)u.indexOf(T)===-1?m*=s[T]:y*=s[T];return y<32&&m>1024},oa=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?ia(s,u):Yi(s,u)},la=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?Eo(s,u):Xi(s,u)},Io=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?ra(s,u):Ji(s,u)},Ro=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?sn(s,u):Qi(s,u)},ua=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?sa(s,u):Zi(s,u)},Yn=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?Co(s,u):ea(s,u)},M=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?Ao(s,u):ta(s,u)},$o=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?aa(s,u):na(s,u)},Is=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?As(s,u):Ss(s,u)},xo=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?So(s,u):wo(s,u)}}),t,i,l,h,
|
|
309
|
+
`)}`,`var value = ${p.getByIndices("input_indices")};`,`value = min(value, ${p.getByIndices("input_indices")});`,""]})},Ao=(s,u)=>{Hn(s.inputs),zn(s,"ReduceProd",u,(p,m)=>[`var value = ${m.type.storage}(1);`,"",`value *= ${p.getByIndices("input_indices")};`,""])},aa=(s,u)=>{Hn(s.inputs),zn(s,"ReduceSum",u,(p,m)=>[`var value = ${m.type.storage}(0);`,"",`value += ${p.getByIndices("input_indices")};`,""])},As=(s,u)=>{Hn(s.inputs),zn(s,"ReduceSumSquare",u,(p,m)=>[`var t = ${m.type.value}(0); var value = ${m.type.value}(0);`,"",`t = ${p.getByIndices("input_indices")}; value += t * t;`,""])},Fn=(s,u,p)=>{if(u.length===0)return p;let m=1,y=1;for(let T=0;T<u.length;T++)u.indexOf(T)===-1?m*=s[T]:y*=s[T];return y<32&&m>1024},oa=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?ia(s,u):Yi(s,u)},la=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?Eo(s,u):Xi(s,u)},Io=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?ra(s,u):Ji(s,u)},Ro=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?sn(s,u):Qi(s,u)},ua=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?sa(s,u):Zi(s,u)},Yn=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?Co(s,u):ea(s,u)},M=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?Ao(s,u):ta(s,u)},$o=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?aa(s,u):na(s,u)},Is=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?As(s,u):Ss(s,u)},xo=(s,u)=>{Fn(s.inputs[0].dims,u.axes,u.noopWithEmptyAxes)?So(s,u):wo(s,u)}}),t,i,l,h,f=d(()=>{rt(),Ft(),ri(),t=s=>{if(!s||s.length===0||s.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(s[0].dataType!==1)throw new Error("Invalid input type.")},i=(s,u)=>{t(s.inputs);let p=(m,y,T)=>{let b=[];for(let w=0;w<m.rank;w++)(T.indexOf(w)>=0||T.length===0)&&b.push(`input_indices[${w}] = 0;`);return[`${b.join(`
|
|
310
310
|
`)}`,`var value = ${m.getByIndices("input_indices")};
|
|
311
311
|
var best_index : i32 = 0;`,`if (${m.getByIndices("input_indices")} ${u.selectLastIndex>0?"<=":"<"} value) {
|
|
312
312
|
value = ${m.getByIndices("input_indices")};
|
|
@@ -2940,7 +2940,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2940
2940
|
${s.mainStart()}
|
|
2941
2941
|
${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
2942
2942
|
${C}
|
|
2943
|
-
}`},zT=s=>{let u=s[1].dims,p=s[2].dims,m=s[0].dims,y=s[1].dataType,T=!(ne.areEqual(u,p)&&ne.areEqual(p,m)),b=u,w=ne.size(u);if(T){let C=_s.calcShape(_s.calcShape(u,p,!1),m,!1);if(!C)throw new Error("Can't perform where op on the given tensors");b=C,w=ne.size(b)}let E=Math.ceil(w/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:C=>HT(C,s,b,T,y),getRunData:()=>({outputs:[{dims:b,dataType:y}],dispatchGroup:{x:Math.ceil(w/64/4)},programUniforms:[{type:12,data:E},...Qe(m,u,p,b)]})}},FT=s=>{s.compute(zT(s.inputs))}}),BT,nR=d(()=>{
|
|
2943
|
+
}`},zT=s=>{let u=s[1].dims,p=s[2].dims,m=s[0].dims,y=s[1].dataType,T=!(ne.areEqual(u,p)&&ne.areEqual(p,m)),b=u,w=ne.size(u);if(T){let C=_s.calcShape(_s.calcShape(u,p,!1),m,!1);if(!C)throw new Error("Can't perform where op on the given tensors");b=C,w=ne.size(b)}let E=Math.ceil(w/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:C=>HT(C,s,b,T,y),getRunData:()=>({outputs:[{dims:b,dataType:y}],dispatchGroup:{x:Math.ceil(w/64/4)},programUniforms:[{type:12,data:E},...Qe(m,u,p,b)]})}},FT=s=>{s.compute(zT(s.inputs))}}),BT,nR=d(()=>{f(),ts(),gI(),yI(),vI(),TI(),bI(),AI(),RI(),$I(),xI(),OI(),kI(),DI(),NI(),MI(),UI(),PI(),LI(),qI(),HI(),zI(),FI(),BI(),VI(),tv(),jI(),GI(),WI(),KI(),YI(),ri(),XI(),dv(),JI(),QI(),ZI(),lv(),eR(),pr(),Jd(),tR(),BT=new Map([["Abs",[Sm]],["Acos",[Em]],["Acosh",[Cm]],["Add",[hg]],["ArgMax",[l,h]],["ArgMin",[i,h]],["Asin",[Am]],["Asinh",[Im]],["Atan",[Rm]],["Atanh",[$m]],["Attention",[Pr]],["AveragePool",[zv,Hv]],["BatchNormalization",[ym]],["BiasAdd",[bm]],["BiasSplitGelu",[ug]],["Cast",[Om,xm]],["Ceil",[Nm]],["Clip",[Dm]],["Concat",[Ag,Ig]],["Conv",[ch,lh]],["ConvTranspose",[ey,Jg]],["Cos",[Mm]],["Cosh",[Um]],["CumSum",[ny,ry]],["DepthToSpace",[oy,ly]],["DequantizeLinear",[Xv,Jv]],["Div",[pg]],["Einsum",[_y,fy]],["Elu",[Pm,Al]],["Equal",[_g]],["Erf",[Lm]],["Exp",[qm]],["Expand",[vy]],["FastGelu",[by]],["Floor",[Hm]],["FusedConv",[ch,lh]],["Gather",[Cy,Ey]],["GatherElements",[Uy,My]],["GatherBlockQuantized",[Oy,ky]],["GatherND",[Iy,Ry]],["Gelu",[zm]],["Gemm",[Hy,qy]],["GlobalAveragePool",[Bv,Fv]],["GlobalMaxPool",[Wv,Gv]],["Greater",[yg]],["GreaterOrEqual",[Tg]],["GridSample",[Yy,Xy]],["GroupQueryAttention",[fv]],["HardSigmoid",[Ym,Km]],["InstanceNormalization",[yv]],["LayerNormalization",[bv]],["LeakyRelu",[Fm,Al]],["Less",[vg]],["LessOrEqual",[bg]],["Log",[rg]],["MatMul",[Sv]],["MatMulNBits",[Iv,Rv]],["MaxPool",[Vv,jv]],["Mul",[fg]],["MultiHeadAttention",[ev,Qy]],["Neg",[Vm]],["Not",[Bm]],["Pad",[Pv]],["Pow",[mg]],["QuickGelu",[ag,Al]],["Range",[eT]],["Reciprocal",[jm]],["ReduceMin",[Yn]],["ReduceMean",[oa]],["ReduceMax",[ua]],["ReduceSum",[$o]],["ReduceProd",[M]],["ReduceL1",[la]],["ReduceL2",[Io]],["ReduceLogSum",[xo]],["ReduceLogSumExp",[Ro]],["ReduceSumSquare",[Is]],["Relu",[Gm]],["Resize",[bT,wT]],["RotaryEmbedding",[cv]],["ScatterND",[sT,rT]],["Sigmoid",[Wm]],["Sin",[Xm]],["Sinh",[Jm]],["Slice",[xT,OT]],["SkipLayerNormalization",[CT]],["Split",[av,ov]],["Sqrt",[Qm]],["Softmax",[NT,MT]],["Sub",[gg]],["Tan",[Zm]],["Tanh",[eg]],["ThresholdedRelu",[ng,Al]],["Tile",[qT]],["Transpose",[ji,Ts]],["Where",[FT]]])}),VT,rR=d(()=>{_n(),Sr(),at(),VT=class{constructor(s){this.backend=s,this.repo=new Map,this.attributesBound=!1}getArtifact(s){return this.repo.get(s)}setArtifact(s,u){this.repo.set(s,u)}run(s,u,p,m,y){mt(s.programInfo.name);let T=this.backend.device,b=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let w=[];for(let C of u)w.push({binding:w.length,resource:{buffer:C.buffer}});for(let C of p)w.push({binding:w.length,resource:{buffer:C.buffer}});y&&w.push({binding:w.length,resource:y});let E=T.createBindGroup({layout:s.computePipeline.getBindGroupLayout(0),entries:w,label:s.programInfo.name});if(this.backend.sessionStatus==="capturing"){let C={kernelId:this.backend.currentKernelId,computePipeline:s.computePipeline,bindGroup:E,dispatchGroup:m};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(C)}b.setPipeline(s.computePipeline),b.setBindGroup(0,E),b.dispatchWorkgroups(...m),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Le(s.programInfo.name)}dispose(){}build(s,u){mt(s.name);let p=this.backend.device,m=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(C=>{p.features.has(C.feature)&&m.push(`enable ${C.extension};`)});let y=_o(u,this.backend.device.limits),T=s.getShaderSource(y),b=`${m.join(`
|
|
2944
2944
|
`)}
|
|
2945
2945
|
${y.additionalImplementations}
|
|
2946
2946
|
${T}`,w=p.createShaderModule({code:b,label:s.name});vt("verbose",()=>`[WebGPU] ${s.name} shader code: ${b}`);let E=p.createComputePipeline({compute:{module:w,entryPoint:"main"},layout:"auto",label:s.name});return Le(s.name),{programInfo:s,computePipeline:E,uniformVariablesInfo:y.variablesInfo}}normalizeDispatchGroupSize(s){let u=typeof s=="number"?s:s.x,p=typeof s=="number"?1:s.y||1,m=typeof s=="number"?1:s.z||1,y=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(u<=y&&p<=y&&m<=y)return[u,p,m];let T=u*p*m,b=Math.ceil(Math.sqrt(T));if(b>y){if(b=Math.ceil(Math.cbrt(T)),b>y)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[b,b,b]}else return[b,b,1]}}}),jT={};A(jT,{WebGpuBackend:()=>YT});var GT,WT,KT,YT,sR=d(()=>{_n(),rt(),Sr(),Ui(),El(),nR(),rR(),GT=(s,u)=>{if(u.length!==s.length)throw new Error(`inputDependencies length ${u.length} is not equal to inputTensors length ${s.length}.`);let p=[];for(let m=0;m<s.length;++m){let y=s[m].dataType;switch(u[m]){case"none":{p.push("");break}case"type":{p.push(`${y}`);break}case"rank":{let T=s[m].dims.length;p.push(`${y};${T}`);break}case"dims":{let T=s[m].dims.join(",");p.push(`${y};${T}`);break}default:throw new Error(`unsupported input dependency: ${u[m]}`)}}return p.join("|")},WT=(s,u,p)=>{let m=s.name;return s.shaderCache?.hint&&(m+="["+s.shaderCache.hint+"]"),m+=":"+p+`:${GT(u,s.shaderCache?.inputDependencies??new Array(u.length).fill("dims"))}`,m},KT=class{constructor(s){s&&(this.architecture=s.architecture,this.vendor=s.vendor)}isArchitecture(s){return this.architecture===s}isVendor(s){return this.vendor===s}},YT=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let s=this.kernelCustomData.get(this.currentKernelId);return s||(s={},this.kernelCustomData.set(this.currentKernelId,s)),s}async initialize(s,u){this.env=s;let p=[],m={requiredLimits:{maxComputeWorkgroupStorageSize:u.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:u.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:u.limits.maxStorageBufferBindingSize,maxBufferSize:u.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:u.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:u.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:u.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:u.limits.maxComputeWorkgroupSizeZ},requiredFeatures:p},y=T=>u.features.has(T)&&p.push(T)&&!0;y("chromium-experimental-timestamp-query-inside-passes")||y("timestamp-query"),y("shader-f16"),y("subgroups"),this.device=await u.requestDevice(m),this.adapterInfo=new KT(u.info||await u.requestAdapterInfo()),this.gpuDataManager=ys(this),this.programManager=new VT(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Zs(s.logLevel,!!s.debug),this.device.onuncapturederror=T=>{T.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${T.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:u,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let s=this.getCommandEncoder(),u={};this.queryType==="at-passes"&&(u.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=s.beginComputePass(u)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;mt(),this.endComputePass();let s;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),s=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(s,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,s,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&s.mapAsync(GPUMapMode.READ).then(()=>{let u=new BigUint64Array(s.getMappedRange()),p=this.pendingQueries.get(s);for(let m=0;m<u.length/2;m++){let y=p[m],T=y.kernelId,b=this.kernels.get(T),w=b.kernelType,E=b.kernelName,C=y.programName,$=y.inputTensorViews,x=y.outputTensorViews,O=u[m*2],k=u[m*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=O);let D=Number(O-this.queryTimeBase),P=Number(k-this.queryTimeBase);if(!Number.isSafeInteger(D)||!Number.isSafeInteger(P))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:$.map(F=>({dims:F.dims,dataType:Zn(F.dataType)})),outputsMetadata:x.map(F=>({dims:F.dims,dataType:Zn(F.dataType)})),kernelId:T,kernelType:w,kernelName:E,programName:C,startTime:D,endTime:P});else{let F="";$.forEach((U,V)=>{F+=`input[${V}]: [${U.dims}] | ${Zn(U.dataType)}, `});let L="";x.forEach((U,V)=>{L+=`output[${V}]: [${U.dims}] | ${Zn(U.dataType)}, `}),console.log(`[profiling] kernel "${T}|${w}|${E}|${C}" ${F}${L}start time: ${D} ns, execution time: ${P-D} ns`)}ut("GPU",`${C}::${O}::${k}`)}s.unmap(),this.pendingQueries.delete(s)}),Le()}run(s,u,p,m,y,T){mt(s.name);let b=[];for(let U=0;U<u.length;++U){let V=u[U].data;if(V===0)continue;let B=this.gpuDataManager.get(V);if(!B)throw new Error(`no GPU data for input: ${V}`);b.push(B)}let{outputs:w,dispatchGroup:E,programUniforms:C}=s.getRunData(u),$=p.length===0?w.map((U,V)=>V):p;if($.length!==w.length)throw new Error(`Output size ${$.length} must be equal to ${w.length}.`);let x=[],O=[];for(let U=0;U<w.length;++U){if(!Number.isInteger($[U])||$[U]<-3||$[U]>=T)throw new Error(`Invalid output index: ${$[U]}`);if($[U]===-3)continue;let V=$[U]===-1,B=$[U]===-2,Y=V||B?y(w[U].dataType,w[U].dims):m($[U],w[U].dataType,w[U].dims);if(x.push(Y),Y.data===0)continue;let te=this.gpuDataManager.get(Y.data);if(!te)throw new Error(`no GPU data for output: ${Y.data}`);if(V&&this.temporaryData.push(te),B){let Z=this.kernelPersistentData.get(this.currentKernelId);Z||(Z=[],this.kernelPersistentData.set(this.currentKernelId,Z)),Z.push(te)}O.push(te)}if(b.length!==u.length||O.length!==x.length){if(O.length===0)return Le(s.name),x;throw new Error(`Program ${s.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let k;if(C){let U=0,V=[];C.forEach(Z=>{let pe=typeof Z.data=="number"?[Z.data]:Z.data;if(pe.length===0)return;let xe=Z.type===10?2:4,je,lt;Z.type===10?(lt=pe.length>4?16:pe.length>2?8:pe.length*xe,je=pe.length>4?16:xe*pe.length):(lt=pe.length<=2?pe.length*xe:16,je=16),U=Math.ceil(U/lt)*lt,V.push(U);let tt=Z.type===10?8:4;U+=pe.length>4?Math.ceil(pe.length/tt)*je:pe.length*xe});let B=16;U=Math.ceil(U/B)*B;let Y=new ArrayBuffer(U);C.forEach((Z,pe)=>{let xe=V[pe],je=typeof Z.data=="number"?[Z.data]:Z.data;if(Z.type===6)new Int32Array(Y,xe,je.length).set(je);else if(Z.type===12)new Uint32Array(Y,xe,je.length).set(je);else if(Z.type===10)new Uint16Array(Y,xe,je.length).set(je);else if(Z.type===1)new Float32Array(Y,xe,je.length).set(je);else throw new Error(`Unsupported uniform type: ${Zn(Z.type)}`)});let te=this.gpuDataManager.create(U,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(te.buffer,0,Y,0,U),this.gpuDataManager.release(te.id),k={offset:0,size:U,buffer:te.buffer}}let D=this.programManager.normalizeDispatchGroupSize(E),P=D[1]===1&&D[2]===1,F=WT(s,u,P),L=this.programManager.getArtifact(F);if(L||(L=this.programManager.build(s,D),this.programManager.setArtifact(F,L),vt("info",()=>`[artifact] key: ${F}, programName: ${s.name}`)),C&&L.uniformVariablesInfo){if(C.length!==L.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${L.uniformVariablesInfo.length}, got ${C.length} in program "${L.programInfo.name}".`);for(let U=0;U<C.length;U++){let V=C[U],B=V.type,Y=typeof V.data=="number"?1:V.data.length,[te,Z]=L.uniformVariablesInfo[U];if(B!==te||Y!==Z)throw new Error(`Uniform variable ${U} mismatch: expect type ${te} with size ${Z}, got type ${B} with size ${Y} in program "${L.programInfo.name}".`)}}if(vt("info",()=>`[ProgramManager] run "${s.name}" (key=${F}) with ${D[0]}x${D[1]}x${D[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let U={kernelId:this.currentKernelId,programName:L.programInfo.name,inputTensorViews:u,outputTensorViews:x};this.pendingKernels.push(U),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(U)}return this.programManager.run(L,b,O,D,k),Le(s.name),x}upload(s,u){this.gpuDataManager.upload(s,u)}memcpy(s,u){this.gpuDataManager.memcpy(s,u)}async download(s,u){await this.gpuDataManager.download(s,u)}alloc(s){return this.gpuDataManager.create(s).id}free(s){return this.gpuDataManager.release(s)}createKernel(s,u,p,m){let y=BT.get(s);if(!y)throw new Error(`kernel not implemented: ${s}`);let T={kernelType:s,kernelName:m,kernelEntry:y[0],attributes:[y[1],p]};this.kernels.set(u,T)}releaseKernel(s){let u=this.kernelPersistentData.get(s);if(u){for(let p of u)this.gpuDataManager.release(p.id);this.kernelPersistentData.delete(s)}this.kernelCustomData.delete(s),this.kernels.delete(s)}computeKernel(s,u,p){let m=this.kernels.get(s);if(!m)throw new Error(`kernel not created: ${s}`);let y=m.kernelType,T=m.kernelName,b=m.kernelEntry,w=m.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${y}] ${T}" is not allowed to be called recursively`);this.currentKernelId=s,w[0]&&(w[1]=w[0](w[1]),w[0]=void 0),vt("info",()=>`[WebGPU] Start to run kernel "[${y}] ${T}"...`);let E=this.env.debug;this.temporaryData=[];try{return E&&this.device.pushErrorScope("validation"),b(u,w[1]),0}catch(C){return p.push(Promise.resolve(`[WebGPU] Kernel "[${y}] ${T}" failed. ${C}`)),1}finally{E&&p.push(this.device.popErrorScope().then(C=>C?`GPU validation error for kernel "[${y}] ${T}": ${C.message}`:null));for(let C of this.temporaryData)this.gpuDataManager.release(C.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(s,u,p,m){let y=this.sessionExternalDataMapping.get(s);y||(y=new Map,this.sessionExternalDataMapping.set(s,y));let T=y.get(u),b=this.gpuDataManager.registerExternalBuffer(p,m,T);return y.set(u,[b,p]),b}unregisterBuffers(s){let u=this.sessionExternalDataMapping.get(s);u&&(u.forEach(p=>this.gpuDataManager.unregisterExternalBuffer(p[0])),this.sessionExternalDataMapping.delete(s))}getBuffer(s){let u=this.gpuDataManager.get(s);if(!u)throw new Error(`no GPU data for buffer: ${s}`);return u.buffer}createDownloader(s,u,p){return async()=>{let m=await Ma(this,s,u);return vn(m.buffer,p)}}writeTimestamp(s){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,s)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){vt("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){vt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){vt("info","replay"),this.sessionStatus="replaying";let s=this.capturedCommandList.get(this.currentSessionId),u=this.capturedPendingKernels.get(this.currentSessionId),p=s.length;this.pendingKernels=[];for(let m=0;m<p;m++){let y=this.getComputePassEncoder(),T=s[m];this.writeTimestamp(this.pendingDispatchNumber*2),y.setPipeline(T.computePipeline),y.setBindGroup(0,T.bindGroup),y.dispatchWorkgroups(...T.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(u[m]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(s){this.unregisterBuffers(s),this.capturedCommandList.has(s)&&this.capturedCommandList.delete(s),this.capturedPendingKernels.has(s)&&this.capturedPendingKernels.delete(s),this.gpuDataManager.onReleaseSession(s)}onRunStart(s){this.currentSessionId=s,this.setQueryType()}}}),XT={};A(XT,{init:()=>QT});var sc,JT,QT,iR=d(()=>{rt(),Sr(),ct(),Na(),sc=class vb{constructor(u,p,m,y){this.module=u,this.dataType=p,this.data=m,this.dims=y}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let u=ne.size(this.dims);return u===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,u)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let u=ne.size(this.dims);return u===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,u)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let u=ne.size(this.dims);return u===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,u)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let u=ne.size(this.dims);return u===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,u)}reshape(u){if(ne.size(u)!==ne.size(this.dims))throw new Error("Invalid new shape");return new vb(this.module,this.dataType,this.data,u)}},JT=class{constructor(s,u,p){this.module=s,this.backend=u,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=u.adapterInfo;let m=s.PTR_SIZE,y=p/s.PTR_SIZE,T=m===4?"i32":"i64";this.opKernelContext=Number(s.getValue(m*y++,T));let b=Number(s.getValue(m*y++,T));this.outputCount=Number(s.getValue(m*y++,T)),this.customDataOffset=Number(s.getValue(m*y++,"*")),this.customDataSize=Number(s.getValue(m*y++,T));let w=[];for(let E=0;E<b;E++){let C=Number(s.getValue(m*y++,T)),$=Number(s.getValue(m*y++,"*")),x=Number(s.getValue(m*y++,T)),O=[];for(let k=0;k<x;k++)O.push(Number(s.getValue(m*y++,T)));w.push(new sc(s,C,$,O))}this.inputs=w}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(s,u){let p=u?.inputs?.map(b=>typeof b=="number"?this.inputs[b]:b)??this.inputs,m=u?.outputs??[],y=(b,w,E)=>new sc(this.module,w,this.output(b,E),E),T=(b,w)=>{let E=wr(b,w);if(!E)throw new Error(`Unsupported data type: ${b}`);let C=E>0?this.backend.gpuDataManager.create(E).id:0;return new sc(this.module,b,C,w)};return this.backend.run(s,p,m,y,T,this.outputCount)}output(s,u){let p=this.module.stackSave();try{let m=this.module.PTR_SIZE,y=m===4?"i32":"i64",T=this.module.stackAlloc((1+u.length)*m);this.module.setValue(T,u.length,y);for(let b=0;b<u.length;b++)this.module.setValue(T+m*(b+1),u[b],y);return this.module._JsepOutput(this.opKernelContext,s,T)}catch(m){throw new Error(`Failed to generate kernel's output[${s}] with dims [${u}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${m}`)}finally{this.module.stackRestore(p)}}},QT=async(s,u,p,m)=>{let y=u.jsepInit;if(!y)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(s==="webgpu"){let T=(sR(),R(jT)).WebGpuBackend,b=new T;await b.initialize(p,m),y("webgpu",[b,w=>b.alloc(Number(w)),w=>b.free(w),(w,E,C,$=!1)=>{if($)vt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(w)}, dst=${Number(E)}, size=${Number(C)}`),b.memcpy(Number(w),Number(E));else{vt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(w)}, gpuDataId=${Number(E)}, size=${Number(C)}`);let x=u.HEAPU8.subarray(Number(w>>>0),Number(w>>>0)+Number(C));b.upload(Number(E),x)}},async(w,E,C)=>{vt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${w}, dataOffset=${E}, size=${C}`),await b.download(Number(w),()=>u.HEAPU8.subarray(Number(E)>>>0,Number(E+C)>>>0))},(w,E,C)=>b.createKernel(w,Number(E),C,u.UTF8ToString(u._JsepGetNodeName(Number(E)))),w=>b.releaseKernel(w),(w,E,C,$)=>{vt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${C}, kernel=${w}, contextDataOffset=${E}`);let x=new JT(u,b,Number(E));return b.computeKernel(Number(w),x,$)},()=>b.captureBegin(),()=>b.captureEnd(),()=>b.replay()])}else{let T=new zi(p);y("webnn",[T,()=>T.reserveTensorId(),b=>T.releaseTensorId(b),async(b,w,E,C,$)=>T.ensureTensor(b,w,E,C,$),(b,w)=>{T.uploadTensor(b,w)},async(b,w)=>T.downloadTensor(b,w),(b,w)=>T.registerMLContext(b,w),!!p.trace])}}}),ZT,kh,Dh,ca,eb,Nh,ic,Mh,Uh,Ph,Lh,qh,Hh,tb=d(()=>{_n(),vr(),Ra(),rt(),gr(),yr(),xi(),ZT=(s,u)=>{$t()._OrtInit(s,u)!==0&&Et("Can't initialize onnxruntime.")},kh=async s=>{ZT(s.wasm.numThreads,ps(s.logLevel))},Dh=async(s,u)=>{$t().asyncInit?.();let p=s.webgpu.adapter;if(u==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(p){if(typeof p.limits!="object"||typeof p.features!="object"||typeof p.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let m=s.webgpu.powerPreference;if(m!==void 0&&m!=="low-power"&&m!=="high-performance")throw new Error(`Invalid powerPreference setting: "${m}"`);let y=s.webgpu.forceFallbackAdapter;if(y!==void 0&&typeof y!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${y}"`);if(p=await navigator.gpu.requestAdapter({powerPreference:m,forceFallbackAdapter:y}),!p)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(u==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let m=(iR(),R(XT)).init;u==="webgpu"&&await m("webgpu",$t(),s,p),u==="webnn"&&await m("webnn",$t(),s)}},ca=new Map,eb=s=>{let u=$t(),p=u.stackSave();try{let m=u.PTR_SIZE,y=u.stackAlloc(2*m);u._OrtGetInputOutputCount(s,y,y+m)!==0&&Et("Can't get session input/output count.");let T=m===4?"i32":"i64";return[Number(u.getValue(y,T)),Number(u.getValue(y+m,T))]}finally{u.stackRestore(p)}},Nh=(s,u)=>{let p=$t(),m=p.stackSave(),y=0;try{let T=p.PTR_SIZE,b=p.stackAlloc(2*T);p._OrtGetInputOutputMetadata(s,u,b,b+T)!==0&&Et("Can't get session input/output metadata.");let w=Number(p.getValue(b,"*"));y=Number(p.getValue(b+T,"*"));let E=p.HEAP32[y/4];if(E===0)return[w,0];let C=p.HEAPU32[y/4+1],$=[];for(let x=0;x<C;x++){let O=Number(p.getValue(y+8+x*T,"*"));$.push(O!==0?p.UTF8ToString(O):Number(p.getValue(y+8+(x+C)*T,"*")))}return[w,E,$]}finally{p.stackRestore(m),y!==0&&p._OrtFree(y)}},ic=s=>{let u=$t(),p=u._malloc(s.byteLength);if(p===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${s.byteLength}.`);return u.HEAPU8.set(s,p),[p,s.byteLength]},Mh=async(s,u)=>{let p,m,y=$t();Array.isArray(s)?[p,m]=s:s.buffer===y.HEAPU8.buffer?[p,m]=[s.byteOffset,s.byteLength]:[p,m]=ic(s);let T=0,b=0,w=0,E=[],C=[],$=[];try{if([b,E]=await $i(u),u?.externalData&&y.mountExternalData){let B=[];for(let Y of u.externalData){let te=typeof Y=="string"?Y:Y.path;B.push(Qs(typeof Y=="string"?Y:Y.data).then(Z=>{y.mountExternalData(te,Z)}))}await Promise.all(B)}for(let B of u?.executionProviders??[])if((typeof B=="string"?B:B.name)==="webnn"){if(y.shouldTransferToMLTensor=!1,typeof B!="string"){let Y=B,te=Y?.context,Z=Y?.gpuDevice,pe=Y?.deviceType,xe=Y?.powerPreference;te?y.currentContext=te:Z?y.currentContext=await y.webnnCreateMLContext(Z):y.currentContext=await y.webnnCreateMLContext({deviceType:pe,powerPreference:xe})}else y.currentContext=await y.webnnCreateMLContext();break}T=await y._OrtCreateSession(p,m,b),y.webgpuOnCreateSession?.(T),T===0&&Et("Can't create a session."),y.jsepOnCreateSession?.(),y.currentContext&&(y.webnnRegisterMLContext(T,y.currentContext),y.currentContext=void 0,y.shouldTransferToMLTensor=!0);let[x,O]=eb(T),k=!!u?.enableGraphCapture,D=[],P=[],F=[],L=[],U=[];for(let B=0;B<x;B++){let[Y,te,Z]=Nh(T,B);Y===0&&Et("Can't get an input name."),C.push(Y);let pe=y.UTF8ToString(Y);D.push(pe),F.push(te===0?{name:pe,isTensor:!1}:{name:pe,isTensor:!0,type:Zn(te),shape:Z})}for(let B=0;B<O;B++){let[Y,te,Z]=Nh(T,B+x);Y===0&&Et("Can't get an output name."),$.push(Y);let pe=y.UTF8ToString(Y);P.push(pe),L.push(te===0?{name:pe,isTensor:!1}:{name:pe,isTensor:!0,type:Zn(te),shape:Z});{if(k&&u?.preferredOutputLocation===void 0){U.push("gpu-buffer");continue}let xe=typeof u?.preferredOutputLocation=="string"?u.preferredOutputLocation:u?.preferredOutputLocation?.[pe]??"cpu",je=y.webnnIsGraphOutput;if(xe==="cpu"&&je&&je(T,pe)){U.push("ml-tensor-cpu-output");continue}if(xe!=="cpu"&&xe!=="cpu-pinned"&&xe!=="gpu-buffer"&&xe!=="ml-tensor")throw new Error(`Not supported preferred output location: ${xe}.`);if(k&&xe!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${xe}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);U.push(xe)}}let V=null;return U.some(B=>B==="gpu-buffer"||B==="ml-tensor"||B==="ml-tensor-cpu-output")&&(w=y._OrtCreateBinding(T),w===0&&Et("Can't create IO binding."),V={handle:w,outputPreferredLocations:U,outputPreferredLocationsEncoded:U.map(B=>B==="ml-tensor-cpu-output"?"ml-tensor":B).map(B=>Js(B))}),ca.set(T,[T,C,$,V,k,!1]),[T,D,P,F,L]}catch(x){throw C.forEach(O=>y._OrtFree(O)),$.forEach(O=>y._OrtFree(O)),w!==0&&y._OrtReleaseBinding(w)!==0&&Et("Can't release IO binding."),T!==0&&y._OrtReleaseSession(T)!==0&&Et("Can't release session."),x}finally{y._free(p),b!==0&&y._OrtReleaseSessionOptions(b)!==0&&Et("Can't release session options."),E.forEach(x=>y._free(x)),y.unmountExternalData?.()}},Uh=s=>{let u=$t(),p=ca.get(s);if(!p)throw new Error(`cannot release session. invalid session id: ${s}`);let[m,y,T,b,w]=p;b&&(w&&u._OrtClearBoundOutputs(b.handle)!==0&&Et("Can't clear bound outputs."),u._OrtReleaseBinding(b.handle)!==0&&Et("Can't release IO binding.")),u.jsepOnReleaseSession?.(s),u.webnnOnReleaseSession?.(s),u.webgpuOnReleaseSession?.(s),y.forEach(E=>u._OrtFree(E)),T.forEach(E=>u._OrtFree(E)),u._OrtReleaseSession(m)!==0&&Et("Can't release session."),ca.delete(s)},Ph=async(s,u,p,m,y,T,b=!1)=>{if(!s){u.push(0);return}let w=$t(),E=w.PTR_SIZE,C=s[0],$=s[1],x=s[3],O=x,k,D;if(C==="string"&&(x==="gpu-buffer"||x==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(b&&x!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${T} when enableGraphCapture is true.`);if(x==="gpu-buffer"){let L=s[2].gpuBuffer;D=wr(br(C),$);{let U=w.jsepRegisterBuffer;if(!U)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');k=U(m,T,L,D)}}else if(x==="ml-tensor"){let L=s[2].mlTensor;D=wr(br(C),$);let U=w.webnnRegisterMLTensor;if(!U)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');k=U(m,L,br(C),$)}else{let L=s[2];if(Array.isArray(L)){D=E*L.length,k=w._malloc(D),p.push(k);for(let U=0;U<L.length;U++){if(typeof L[U]!="string")throw new TypeError(`tensor data at index ${U} is not a string`);w.setValue(k+U*E,yn(L[U],p),"*")}}else{let U=w.webnnIsGraphInput,V=w.webnnIsGraphOutput;if(C!=="string"&&U&&V){let B=w.UTF8ToString(y);if(U(m,B)||V(m,B)){let Y=br(C);D=wr(Y,$),O="ml-tensor";let te=w.webnnCreateTemporaryTensor,Z=w.webnnUploadTensor;if(!te||!Z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let pe=await te(m,Y,$);Z(pe,new Uint8Array(L.buffer,L.byteOffset,L.byteLength)),k=pe}else D=L.byteLength,k=w._malloc(D),p.push(k),w.HEAPU8.set(new Uint8Array(L.buffer,L.byteOffset,D),k)}else D=L.byteLength,k=w._malloc(D),p.push(k),w.HEAPU8.set(new Uint8Array(L.buffer,L.byteOffset,D),k)}}let P=w.stackSave(),F=w.stackAlloc(4*$.length);try{$.forEach((U,V)=>w.setValue(F+V*E,U,E===4?"i32":"i64"));let L=w._OrtCreateTensor(br(C),k,D,F,$.length,Js(O));L===0&&Et(`Can't create tensor for input/output. session=${m}, index=${T}.`),u.push(L)}finally{w.stackRestore(P)}},Lh=async(s,u,p,m,y,T)=>{let b=$t(),w=b.PTR_SIZE,E=ca.get(s);if(!E)throw new Error(`cannot run inference. invalid session id: ${s}`);let C=E[0],$=E[1],x=E[2],O=E[3],k=E[4],D=E[5],P=u.length,F=m.length,L=0,U=[],V=[],B=[],Y=[],te=b.stackSave(),Z=b.stackAlloc(P*w),pe=b.stackAlloc(P*w),xe=b.stackAlloc(F*w),je=b.stackAlloc(F*w);try{[L,U]=Ai(T),Pe("wasm prepareInputOutputTensor");for(let Ye=0;Ye<P;Ye++)await Ph(p[Ye],V,Y,s,$[u[Ye]],u[Ye],k);for(let Ye=0;Ye<F;Ye++)await Ph(y[Ye],B,Y,s,x[m[Ye]],P+m[Ye],k);Ze("wasm prepareInputOutputTensor");for(let Ye=0;Ye<P;Ye++)b.setValue(Z+Ye*w,V[Ye],"*"),b.setValue(pe+Ye*w,$[u[Ye]],"*");for(let Ye=0;Ye<F;Ye++)b.setValue(xe+Ye*w,B[Ye],"*"),b.setValue(je+Ye*w,x[m[Ye]],"*");if(O&&!D){let{handle:Ye,outputPreferredLocations:yt,outputPreferredLocationsEncoded:ot}=O;if($.length!==P)throw new Error(`input count from feeds (${P}) is expected to be always equal to model's input count (${$.length}).`);Pe("wasm bindInputsOutputs");for(let et=0;et<P;et++){let Ot=u[et];await b._OrtBindInput(Ye,$[Ot],V[et])!==0&&Et(`Can't bind input[${et}] for session=${s}.`)}for(let et=0;et<F;et++){let Ot=m[et];y[et]?.[3]?b._OrtBindOutput(Ye,x[Ot],B[et],0)!==0&&Et(`Can't bind pre-allocated output[${et}] for session=${s}.`):b._OrtBindOutput(Ye,x[Ot],0,ot[Ot])!==0&&Et(`Can't bind output[${et}] to ${yt[et]} for session=${s}.`)}Ze("wasm bindInputsOutputs"),ca.set(s,[C,$,x,O,k,!0])}b.jsepOnRunStart?.(C),b.webnnOnRunStart?.(C);let lt;O?lt=await b._OrtRunWithBinding(C,O.handle,F,xe,L):lt=await b._OrtRun(C,pe,Z,P,je,F,xe,L),lt!==0&&Et("failed to call OrtRun().");let tt=[],pt=[];Pe("wasm ProcessOutputTensor");for(let Ye=0;Ye<F;Ye++){let yt=Number(b.getValue(xe+Ye*w,"*"));if(yt===B[Ye]){tt.push(y[Ye]);continue}let ot=b.stackSave(),et=b.stackAlloc(4*w),Ot=!1,nt,Bt=0;try{b._OrtGetTensorData(yt,et,et+w,et+2*w,et+3*w)!==0&&Et(`Can't access output tensor data on index ${Ye}.`);let ke=w===4?"i32":"i64",He=Number(b.getValue(et,ke));Bt=b.getValue(et+w,"*");let ft=b.getValue(et+w*2,"*"),Mt=Number(b.getValue(et+w*3,ke)),En=[];for(let Cn=0;Cn<Mt;Cn++)En.push(Number(b.getValue(ft+Cn*w,ke)));b._OrtFree(ft)!==0&&Et("Can't free memory for tensor dims.");let $s=En.reduce((Cn,cn)=>Cn*cn,1);nt=Zn(He);let Ml=O?.outputPreferredLocations[m[Ye]];if(nt==="string"){if(Ml==="gpu-buffer"||Ml==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Cn=[];for(let cn=0;cn<$s;cn++){let ii=b.getValue(Bt+cn*w,"*"),cR=b.getValue(Bt+(cn+1)*w,"*"),dR=cn===$s-1?void 0:cR-ii;Cn.push(b.UTF8ToString(ii,dR))}tt.push([nt,En,Cn,"cpu"])}else if(Ml==="gpu-buffer"&&$s>0){let Cn=b.jsepGetBuffer;if(!Cn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let cn=Cn(Bt),ii=wr(He,$s);if(ii===void 0||!Ys(nt))throw new Error(`Unsupported data type: ${nt}`);Ot=!0,tt.push([nt,En,{gpuBuffer:cn,download:b.jsepCreateDownloader(cn,ii,nt),dispose:()=>{b._OrtReleaseTensor(yt)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(Ml==="ml-tensor"&&$s>0){let Cn=b.webnnEnsureTensor,cn=b.webnnIsGraphInputOutputTypeSupported;if(!Cn||!cn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(wr(He,$s)===void 0||!Xs(nt))throw new Error(`Unsupported data type: ${nt}`);if(!cn(s,nt,!1))throw new Error(`preferredLocation "ml-tensor" for ${nt} output is not supported by current WebNN Context.`);let ii=await Cn(s,Bt,He,En,!1);Ot=!0,tt.push([nt,En,{mlTensor:ii,download:b.webnnCreateMLTensorDownloader(Bt,nt),dispose:()=>{b.webnnReleaseTensorId(Bt),b._OrtReleaseTensor(yt)}},"ml-tensor"])}else if(Ml==="ml-tensor-cpu-output"&&$s>0){let Cn=b.webnnCreateMLTensorDownloader(Bt,nt)(),cn=tt.length;Ot=!0,pt.push((async()=>{let ii=[cn,await Cn];return b.webnnReleaseTensorId(Bt),b._OrtReleaseTensor(yt),ii})()),tt.push([nt,En,[],"cpu"])}else{let Cn=Or(nt),cn=new Cn($s);new Uint8Array(cn.buffer,cn.byteOffset,cn.byteLength).set(b.HEAPU8.subarray(Bt,Bt+cn.byteLength)),tt.push([nt,En,cn,"cpu"])}}finally{b.stackRestore(ot),nt==="string"&&Bt&&b._free(Bt),Ot||b._OrtReleaseTensor(yt)}}O&&!k&&(b._OrtClearBoundOutputs(O.handle)!==0&&Et("Can't clear bound outputs."),ca.set(s,[C,$,x,O,k,!1]));for(let[Ye,yt]of await Promise.all(pt))tt[Ye][2]=yt;return Ze("wasm ProcessOutputTensor"),tt}finally{b.webnnOnRunEnd?.(C),b.stackRestore(te),V.forEach(lt=>b._OrtReleaseTensor(lt)),B.forEach(lt=>b._OrtReleaseTensor(lt)),Y.forEach(lt=>b._free(lt)),L!==0&&b._OrtReleaseRunOptions(L),U.forEach(lt=>b._free(lt))}},qh=s=>{let u=$t(),p=ca.get(s);if(!p)throw new Error("invalid session id");let m=p[0],y=u._OrtEndProfiling(m);y===0&&Et("Can't get an profile file name."),u._OrtFree(y)},Hh=s=>{let u=[];for(let p of s){let m=p[2];!Array.isArray(m)&&"buffer"in m&&u.push(m.buffer)}return u}}),da,Lr,ko,Dl,Nl,ac,zh,oc,Ba,Va,nb,rb,sb,ib,ab,ob,lb,ub,cb=d(()=>{_n(),tb(),gr(),Ks(),da=()=>!!Q.wasm.proxy&&typeof document<"u",ko=!1,Dl=!1,Nl=!1,oc=new Map,Ba=(s,u)=>{let p=oc.get(s);p?p.push(u):oc.set(s,[u])},Va=()=>{if(ko||!Dl||Nl||!Lr)throw new Error("worker not ready")},nb=s=>{switch(s.data.type){case"init-wasm":ko=!1,s.data.err?(Nl=!0,zh[1](s.data.err)):(Dl=!0,zh[0]()),ac&&(URL.revokeObjectURL(ac),ac=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let u=oc.get(s.data.type);s.data.err?u.shift()[1](s.data.err):u.shift()[0](s.data.out);break}}},rb=async()=>{if(!Dl){if(ko)throw new Error("multiple calls to 'initWasm()' detected.");if(Nl)throw new Error("previous call to 'initWasm()' failed.");if(ko=!0,da())return new Promise((s,u)=>{Lr?.terminate(),wi().then(([p,m])=>{try{Lr=m,Lr.onerror=T=>u(T),Lr.onmessage=nb,zh=[s,u];let y={type:"init-wasm",in:Q};if(!y.in.wasm.wasmPaths&&p){let T=Vs();T&&(y.in.wasm.wasmPaths=T)}Lr.postMessage(y),ac=p}catch(y){u(y)}},u)});try{await Ia(Q.wasm),await kh(Q),Dl=!0}catch(s){throw Nl=!0,s}finally{ko=!1}}},sb=async s=>{if(da())return Va(),new Promise((u,p)=>{Ba("init-ep",[u,p]);let m={type:"init-ep",in:{epName:s,env:Q}};Lr.postMessage(m)});await Dh(Q,s)},ib=async s=>da()?(Va(),new Promise((u,p)=>{Ba("copy-from",[u,p]);let m={type:"copy-from",in:{buffer:s}};Lr.postMessage(m,[s.buffer])})):ic(s),ab=async(s,u)=>{if(da()){if(u?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Va(),new Promise((p,m)=>{Ba("create",[p,m]);let y={type:"create",in:{model:s,options:{...u}}},T=[];s instanceof Uint8Array&&T.push(s.buffer),Lr.postMessage(y,T)})}else return Mh(s,u)},ob=async s=>{if(da())return Va(),new Promise((u,p)=>{Ba("release",[u,p]);let m={type:"release",in:s};Lr.postMessage(m)});Uh(s)},lb=async(s,u,p,m,y,T)=>{if(da()){if(p.some(b=>b[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(y.some(b=>b))throw new Error("pre-allocated output tensor is not supported for proxy.");return Va(),new Promise((b,w)=>{Ba("run",[b,w]);let E=p,C={type:"run",in:{sessionId:s,inputIndices:u,inputs:E,outputIndices:m,options:T}};Lr.postMessage(C,Hh(E))})}else return Lh(s,u,p,m,y,T)},ub=async s=>{if(da())return Va(),new Promise((u,p)=>{Ba("end-profiling",[u,p]);let m={type:"end-profiling",in:s};Lr.postMessage(m)});qh(s)}}),Fh,db,hb,aR=d(()=>{_n(),cb(),rt(),Gr(),xi(),Fh=(s,u)=>{switch(s.location){case"cpu":return[s.type,s.dims,s.data,"cpu"];case"gpu-buffer":return[s.type,s.dims,{gpuBuffer:s.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[s.type,s.dims,{mlTensor:s.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${s.location} for ${u()}`)}},db=s=>{switch(s[3]){case"cpu":return new Xe(s[0],s[2],s[1]);case"gpu-buffer":{let u=s[0];if(!Ys(u))throw new Error(`not supported data type: ${u} for deserializing GPU tensor`);let{gpuBuffer:p,download:m,dispose:y}=s[2];return Xe.fromGpuBuffer(p,{dataType:u,dims:s[1],download:m,dispose:y})}case"ml-tensor":{let u=s[0];if(!Xs(u))throw new Error(`not supported data type: ${u} for deserializing MLTensor tensor`);let{mlTensor:p,download:m,dispose:y}=s[2];return Xe.fromMLTensor(p,{dataType:u,dims:s[1],download:m,dispose:y})}default:throw new Error(`invalid data location: ${s[3]}`)}},hb=class{async fetchModelAndCopyToWasmMemory(s){return ib(await Qs(s))}async loadModel(s,u){mt();let p;typeof s=="string"?p=await this.fetchModelAndCopyToWasmMemory(s):p=s,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ab(p,u),Le()}async dispose(){return ob(this.sessionId)}async run(s,u,p){mt();let m=[],y=[];Object.entries(s).forEach(x=>{let O=x[0],k=x[1],D=this.inputNames.indexOf(O);if(D===-1)throw new Error(`invalid input '${O}'`);m.push(k),y.push(D)});let T=[],b=[];Object.entries(u).forEach(x=>{let O=x[0],k=x[1],D=this.outputNames.indexOf(O);if(D===-1)throw new Error(`invalid output '${O}'`);T.push(k),b.push(D)});let w=m.map((x,O)=>Fh(x,()=>`input "${this.inputNames[y[O]]}"`)),E=T.map((x,O)=>x?Fh(x,()=>`output "${this.outputNames[b[O]]}"`):null),C=await lb(this.sessionId,y,w,b,E,p),$={};for(let x=0;x<C.length;x++)$[this.outputNames[b[x]]]=T[x]??db(C[x]);return Le(),$}startProfiling(){}endProfiling(){ub(this.sessionId)}}}),pb={};A(pb,{OnnxruntimeWebAssemblyBackend:()=>Vh,initializeFlags:()=>Bh,wasmBackend:()=>_b});var Bh,Vh,_b,oR=d(()=>{_n(),cb(),aR(),Bh=()=>{(typeof Q.wasm.initTimeout!="number"||Q.wasm.initTimeout<0)&&(Q.wasm.initTimeout=0);let s=Q.wasm.simd;if(typeof s!="boolean"&&s!==void 0&&s!=="fixed"&&s!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${s}". Reset it to \`false\` and ignore SIMD feature checking.`),Q.wasm.simd=!1),typeof Q.wasm.proxy!="boolean"&&(Q.wasm.proxy=!1),typeof Q.wasm.trace!="boolean"&&(Q.wasm.trace=!1),typeof Q.wasm.numThreads!="number"||!Number.isInteger(Q.wasm.numThreads)||Q.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Q.wasm.numThreads=1;else{let u=typeof navigator>"u"?g("node:os").cpus().length:navigator.hardwareConcurrency;Q.wasm.numThreads=Math.min(4,Math.ceil((u||1)/2))}},Vh=class{async init(s){Bh(),await rb(),await sb(s)}async createInferenceSessionHandler(s,u){let p=new hb;return await p.loadModel(s,u),p}},_b=new Vh}),fb={};A(fb,{InferenceSession:()=>Dt,TRACE:()=>ut,TRACE_EVENT_BEGIN:()=>Pe,TRACE_EVENT_END:()=>Ze,TRACE_FUNC_BEGIN:()=>mt,TRACE_FUNC_END:()=>Le,Tensor:()=>Xe,default:()=>uR,env:()=>Q,registerBackend:()=>W}),_n(),_n(),_n();var lR="1.23.2",uR=ar;{let s=(oR(),R(pb)).wasmBackend;W("webgpu",s,5),W("webnn",s,5),W("cpu",s,10),W("wasm",s,10)}return Object.defineProperty(Q.versions,"web",{value:lR,enumerable:!0}),R(fb)})();/**
|
|
@@ -2988,5 +2988,5 @@ ${T}`,w=p.createShaderModule({code:b,label:s.name});vt("verbose",()=>`[WebGPU] $
|
|
|
2988
2988
|
* See the License for the specific language governing permissions and
|
|
2989
2989
|
* limitations under the License.
|
|
2990
2990
|
* =============================================================================
|
|
2991
|
-
*/o.exports=r})(zf);var Ff=zf.exports,zd={},Bf={};Object.defineProperty(Bf,"__esModule",{value:!0});var Wu={},Vf;Object.defineProperty(Wu,"__esModule",{value:!0}),Wu.SileroLegacy=void 0;const jf=ao;class Fd{constructor(n,r,a,c,e){this.ortInstance=n,this._session=r,this._h=a,this._c=c,this._sr=e,this.reset_state=()=>{const f=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",f,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",f,[2,1,64])},this.process=async f=>{const d={input:new this.ortInstance.Tensor("float32",f,[1,f.length]),h:this._h,c:this._c,sr:this._sr},A=await this._session.run(d);this._h=A.hn,this._c=A.cn;const[S]=A.output?.data;return{notSpeech:1-S,isSpeech:S}}}}Wu.SileroLegacy=Fd,Vf=Fd,Fd.new=async(o,n)=>{jf.log.debug("initializing vad");const r=await n(),a=await o.InferenceSession.create(r),c=new o.Tensor("int64",[16000n]),e=Array(2*64).fill(0),f=new o.Tensor("float32",e,[2,1,64]),g=new o.Tensor("float32",e,[2,1,64]);return jf.log.debug("vad is initialized"),new Vf(o,a,f,g,c)};var Ku={},Gf;Object.defineProperty(Ku,"__esModule",{value:!0}),Ku.SileroV5=void 0;const Wf=ao;function Kf(o){const n=Array(256).fill(0);return new o.Tensor("float32",n,[2,1,128])}class Bd{constructor(n,r,a,c){this._session=n,this._state=r,this._sr=a,this.ortInstance=c,this.reset_state=()=>{this._state=Kf(this.ortInstance)},this.process=async e=>{const g={input:new this.ortInstance.Tensor("float32",e,[1,e.length]),state:this._state,sr:this._sr},d=await this._session.run(g);this._state=d.stateN;const[A]=d.output?.data;return{notSpeech:1-A,isSpeech:A}}}}Ku.SileroV5=Bd,Gf=Bd,Bd.new=async(o,n)=>{Wf.log.debug("Loading VAD...");const r=await n(),a=await o.InferenceSession.create(r),c=new o.Tensor("int64",[16000n]),e=Kf(o);return Wf.log.debug("...finished loading VAD"),new Gf(a,e,c,o)},function(o){var n=Gn&&Gn.__createBinding||(Object.create?function(e,f,g,d){d===void 0&&(d=g);var A=Object.getOwnPropertyDescriptor(f,g);(!A||("get"in A?!f.__esModule:A.writable||A.configurable))&&(A={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(e,d,A)}:function(e,f,g,d){d===void 0&&(d=g),e[d]=f[g]}),r=Gn&&Gn.__exportStar||function(e,f){for(var g in e)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&n(f,e,g)};Object.defineProperty(o,"__esModule",{value:!0}),o.SileroV5=o.SileroLegacy=void 0,r(Bf,o);var a=Wu;Object.defineProperty(o,"SileroLegacy",{enumerable:!0,get:function(){return a.SileroLegacy}});var c=Ku;Object.defineProperty(o,"SileroV5",{enumerable:!0,get:function(){return c.SileroV5}})}(zd);var wl={};Object.defineProperty(wl,"__esModule",{value:!0}),wl.Resampler=void 0;const sI=ao;class iI{constructor(n){this.options=n,this.process=r=>{const a=[];for(const c of r)for(this.inputBuffer.push(c);this.hasEnoughDataForFrame();){const e=this.generateOutputFrame();a.push(e)}return a},n.nativeSampleRate<16e3&&sI.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(n){for(const r of n)for(this.inputBuffer.push(r);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const n=new Float32Array(this.options.targetFrameSize);let r=0,a=0;for(;r<this.options.targetFrameSize;){let c=0,e=0;for(;a<Math.min(this.inputBuffer.length,(r+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const f=this.inputBuffer[a];f!==void 0&&(c+=f,e++),a++}n[r]=c/e,r++}return this.inputBuffer=this.inputBuffer.slice(a),n}}wl.Resampler=iI,function(o){var n=Gn&&Gn.__createBinding||(Object.create?function(N,H,W,G){G===void 0&&(G=W);var K=Object.getOwnPropertyDescriptor(H,W);(!K||("get"in K?!H.__esModule:K.writable||K.configurable))&&(K={enumerable:!0,get:function(){return H[W]}}),Object.defineProperty(N,G,K)}:function(N,H,W,G){G===void 0&&(G=W),N[G]=H[W]}),r=Gn&&Gn.__setModuleDefault||(Object.create?function(N,H){Object.defineProperty(N,"default",{enumerable:!0,value:H})}:function(N,H){N.default=H}),a=Gn&&Gn.__importStar||function(N){if(N&&N.__esModule)return N;var H={};if(N!=null)for(var W in N)W!=="default"&&Object.prototype.hasOwnProperty.call(N,W)&&n(H,N,W);return r(H,N),H};Object.defineProperty(o,"__esModule",{value:!0}),o.NonRealTimeVAD=o.defaultNonRealTimeVADOptions=void 0;const c=a(Ff),e=Tl,f=io,g=us,d=Ea,A=zd,S=wl;o.defaultNonRealTimeVADOptions={...g.defaultFrameProcessorOptions,modelURL:e.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:f.defaultModelFetcher};class R{static async new(H={}){const W={...o.defaultNonRealTimeVADOptions,...H};(0,g.validateOptions)(W),W.ortConfig!==void 0&&W.ortConfig(c);const G=()=>W.modelFetcher(W.modelURL),K=await A.SileroLegacy.new(c,G),ae=new g.FrameProcessor(K.process,K.reset_state,{positiveSpeechThreshold:W.positiveSpeechThreshold,negativeSpeechThreshold:W.negativeSpeechThreshold,redemptionMs:W.redemptionMs,preSpeechPadMs:W.preSpeechPadMs,minSpeechMs:W.minSpeechMs,submitUserSpeechOnPause:W.submitUserSpeechOnPause},1536/16);return ae.resume(),new this(G,c,W,ae)}constructor(H,W,G,K){this.modelFetcher=H,this.ort=W,this.options=G,this.frameProcessor=K,this.frameSamples=1536}async*run(H,W){const G={nativeSampleRate:W,targetSampleRate:16e3,targetFrameSize:this.frameSamples},K=new S.Resampler(G);let ae=0,ee=0,De=0;for await(const re of K.stream(H)){const be=[];await this.frameProcessor.process(re,Ne=>{be.push(Ne)});for(const Ne of be)switch(Ne.msg){case d.Message.SpeechStart:ae=De*this.frameSamples/16;break;case d.Message.SpeechEnd:ee=(De+1)*this.frameSamples/16,yield{audio:Ne.audio,start:ae,end:ee};break}De++}const X=[];this.frameProcessor.endSegment(re=>{X.push(re)});for(const re of X)switch(re.msg){case d.Message.SpeechEnd:yield{audio:re.audio,start:ae,end:De*this.frameSamples/16}}}}o.NonRealTimeVAD=R}(Hf);var cs={};Object.defineProperty(cs,"__esModule",{value:!0}),cs.audioFileToArray=cs.encodeWAV=cs.arrayBufferToBase64=cs.minFramesForTargetMS=void 0;function aI(o,n,r=16e3){return Math.ceil(o*r/1e3/n)}cs.minFramesForTargetMS=aI;function oI(o){const n=new Uint8Array(o),r=n.byteLength,a=new Array(r);for(var c=0;c<r;c++){const e=n[c];if(e===void 0)break;a[c]=String.fromCharCode(e)}return btoa(a.join(""))}cs.arrayBufferToBase64=oI;function lI(o,n=3,r=16e3,a=1,c=32){var e=c/8,f=a*e,g=new ArrayBuffer(44+o.length*e),d=new DataView(g);return Yu(d,0,"RIFF"),d.setUint32(4,36+o.length*e,!0),Yu(d,8,"WAVE"),Yu(d,12,"fmt "),d.setUint32(16,16,!0),d.setUint16(20,n,!0),d.setUint16(22,a,!0),d.setUint32(24,r,!0),d.setUint32(28,r*f,!0),d.setUint16(32,f,!0),d.setUint16(34,c,!0),Yu(d,36,"data"),d.setUint32(40,o.length*e,!0),n===1?cI(d,44,o):uI(d,44,o),g}cs.encodeWAV=lI;function uI(o,n,r){for(var a=0;a<r.length;a++,n+=4)o.setFloat32(n,r[a],!0)}function cI(o,n,r){for(var a=0;a<r.length;a++,n+=2){var c=Math.max(-1,Math.min(1,r[a]));o.setInt16(n,c<0?c*32768:c*32767,!0)}}function Yu(o,n,r){for(var a=0;a<r.length;a++)o.setUint8(n+a,r.charCodeAt(a))}async function dI(o){const n=new OfflineAudioContext(1,1,44100),r=new FileReader;let a=null;if(await new Promise(f=>{r.addEventListener("loadend",g=>{const d=r.result;n.decodeAudioData(d,A=>{a=A,n.startRendering().then(S=>{console.log("Rendering completed successfully"),f()}).catch(S=>{console.error(`Rendering failed: ${S}`)})},A=>{console.log(`Error with decoding audio data: ${A}`)})}),r.readAsArrayBuffer(o)}),a===null)throw Error("some shit");let c=a,e=new Float32Array(c.length);for(let f=0;f<c.length;f++)for(let g=0;g<c.numberOfChannels;g++)e[f]+=c.getChannelData(g)[f];return{audio:e,sampleRate:c.sampleRate}}cs.audioFileToArray=dI;var Yf={};(function(o){var n=Gn&&Gn.__createBinding||(Object.create?function(ae,ee,De,X){X===void 0&&(X=De);var re=Object.getOwnPropertyDescriptor(ee,De);(!re||("get"in re?!ee.__esModule:re.writable||re.configurable))&&(re={enumerable:!0,get:function(){return ee[De]}}),Object.defineProperty(ae,X,re)}:function(ae,ee,De,X){X===void 0&&(X=De),ae[X]=ee[De]}),r=Gn&&Gn.__setModuleDefault||(Object.create?function(ae,ee){Object.defineProperty(ae,"default",{enumerable:!0,value:ee})}:function(ae,ee){ae.default=ee}),a=Gn&&Gn.__importStar||function(ae){if(ae&&ae.__esModule)return ae;var ee={};if(ae!=null)for(var De in ae)De!=="default"&&Object.prototype.hasOwnProperty.call(ae,De)&&n(ee,ae,De);return r(ee,ae),ee};Object.defineProperty(o,"__esModule",{value:!0}),o.AudioNodeVAD=o.MicVAD=o.getDefaultRealTimeVADOptions=o.ort=o.DEFAULT_MODEL=void 0;const c=a(Ff),e=io,f=us,g=ao,d=Ea,A=zd,S=wl;o.DEFAULT_MODEL="legacy",o.ort=c;const R="vad.worklet.bundle.min.js",N="silero_vad_v5.onnx",H="silero_vad_legacy.onnx",W=ae=>({...f.defaultFrameProcessorOptions,onFrameProcessed:(ee,De)=>{},onVADMisfire:()=>{g.log.debug("VAD misfire")},onSpeechStart:()=>{g.log.debug("Detected speech start")},onSpeechEnd:()=>{g.log.debug("Detected speech end")},onSpeechRealStart:()=>{g.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:ae,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async ee=>{ee.getTracks().forEach(De=>{De.stop()})},resumeStream:async ee=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:ee=>{ee.env.logLevel="error"},startOnLoad:!0});o.getDefaultRealTimeVADOptions=W;class G{static async new(ee={}){const De={...(0,o.getDefaultRealTimeVADOptions)(ee.model??o.DEFAULT_MODEL),...ee};(0,f.validateOptions)(De);const X=new AudioContext,re=await K.new(X,De),be=new G(De,X,re);if(De.startOnLoad)try{await be.start()}catch(Ne){console.error("Error starting micVad",Ne)}return be}constructor(ee,De,X,re=!1){this.options=ee,this.audioContext=De,this.audioNodeVAD=X,this.listening=re,this.initialized=!1,this.pause=()=>{this.stream&&this.options.pauseStream(this.stream),this.audioNodeVAD.pause(),this.listening=!1},this.resume=async()=>{if(!this.stream){console.warn("Stream not initialized");return}this.stream=await this.options.resumeStream(this.stream),this.sourceNode&&this.sourceNode.disconnect(),this.sourceNode=new MediaStreamAudioSourceNode(this.audioContext,{mediaStream:this.stream}),this.audioNodeVAD.receive(this.sourceNode)},this.start=async()=>{this.initialized||(this.initialized=!0,this.stream=await this.options.getStream(),this.sourceNode=new MediaStreamAudioSourceNode(this.audioContext,{mediaStream:this.stream}),this.audioNodeVAD.receive(this.sourceNode)),this.stream?.active?(this.audioNodeVAD.start(),this.listening=!0):(await this.resume(),this.audioNodeVAD.start(),this.listening=!0)},this.destroy=()=>{this.listening&&this.pause(),this.stream?this.options.pauseStream(this.stream):console.warn("Stream not initialized"),this.sourceNode?this.sourceNode.disconnect():console.warn("Source node not initialized"),this.audioNodeVAD.destroy(),this.audioContext.close()},this.setOptions=be=>{this.audioNodeVAD.setFrameProcessorOptions(be)}}}o.MicVAD=G;class K{static async new(ee,De={}){const X={...(0,o.getDefaultRealTimeVADOptions)(De.model??o.DEFAULT_MODEL),...De};(0,f.validateOptions)(X),o.ort.env.wasm.wasmPaths=X.onnxWASMBasePath,X.ortConfig!==void 0&&X.ortConfig(o.ort);const re=X.model==="v5"?N:H,be=X.baseAssetPath+re,Ne=X.model==="v5"?A.SileroV5.new:A.SileroLegacy.new;let Q;try{Q=await Ne(o.ort,()=>(0,e.defaultModelFetcher)(be))}catch(ye){throw console.error(`Encountered an error while loading model file ${be}`),ye}const ce=X.model==="v5"?512:1536,me=ce/16,_e=new f.FrameProcessor(Q.process,Q.reset_state,{positiveSpeechThreshold:X.positiveSpeechThreshold,negativeSpeechThreshold:X.negativeSpeechThreshold,redemptionMs:X.redemptionMs,preSpeechPadMs:X.preSpeechPadMs,minSpeechMs:X.minSpeechMs,submitUserSpeechOnPause:X.submitUserSpeechOnPause},me),ue=new K(ee,X,_e,ce,me);return await ue.setupAudioNode(),ue}constructor(ee,De,X,re,be){this.ctx=ee,this.options=De,this.frameSamples=re,this.msPerFrame=be,this.pause=()=>{this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.start=()=>{this.frameProcessor.resume()},this.receive=Ne=>{Ne.connect(this.audioNode)},this.processFrame=async Ne=>{await this.frameProcessor.process(Ne,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ne=>{switch(Ne.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(Ne.probs,Ne.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(Ne.audio);break}},this.destroy=()=>{this.audioNode instanceof AudioWorkletNode&&this.audioNode.port.postMessage({message:d.Message.SpeechStop}),this.audioNode.disconnect(),this.gainNode?.disconnect()},this.setFrameProcessorOptions=Ne=>{this.frameProcessor.options={...this.frameProcessor.options,...Ne}},this.frameProcessor=X}async setupAudioNode(){if("audioWorklet"in this.ctx&&typeof AudioWorkletNode=="function")try{const re=this.options.baseAssetPath+R;await this.ctx.audioWorklet.addModule(re);const be=this.options.workletOptions??{};be.processorOptions={...be.processorOptions??{},frameSamples:this.frameSamples},this.audioNode=new AudioWorkletNode(this.ctx,"vad-helper-worklet",be),this.audioNode.port.onmessage=async Ne=>{switch(Ne.data?.message){case d.Message.AudioFrame:let Q=Ne.data.data;Q instanceof ArrayBuffer||(Q=new ArrayBuffer(Ne.data.data.byteLength),new Uint8Array(Q).set(new Uint8Array(Ne.data.data)));const ce=new Float32Array(Q);await this.processFrame(ce);break}};return}catch(re){console.log("AudioWorklet setup failed, falling back to ScriptProcessor",re)}this.resampler=new S.Resampler({nativeSampleRate:this.ctx.sampleRate,targetSampleRate:16e3,targetFrameSize:this.frameSamples??480});const De=4096;this.audioNode=this.ctx.createScriptProcessor(De,1,1),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=0;let X=!1;this.audioNode.onaudioprocess=async re=>{if(!X){X=!0;try{const be=re.inputBuffer.getChannelData(0);if(re.outputBuffer.getChannelData(0).fill(0),this.resampler){const Q=this.resampler.process(be);for(const ce of Q)await this.processFrame(ce)}}catch(be){console.error("Error processing audio:",be)}finally{X=!1}}},this.audioNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination)}}o.AudioNodeVAD=K})(Yf),function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.getDefaultRealTimeVADOptions=o.MicVAD=o.DEFAULT_MODEL=o.AudioNodeVAD=o.utils=o.NonRealTimeVAD=o.Message=o.FrameProcessor=o.defaultModelFetcher=o.baseAssetPath=void 0;var n=Tl;Object.defineProperty(o,"baseAssetPath",{enumerable:!0,get:function(){return n.baseAssetPath}});var r=io;Object.defineProperty(o,"defaultModelFetcher",{enumerable:!0,get:function(){return r.defaultModelFetcher}});var a=us;Object.defineProperty(o,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var c=Ea;Object.defineProperty(o,"Message",{enumerable:!0,get:function(){return c.Message}});var e=Hf;Object.defineProperty(o,"NonRealTimeVAD",{enumerable:!0,get:function(){return e.NonRealTimeVAD}});const f=cs;o.utils={audioFileToArray:f.audioFileToArray,minFramesForTargetMS:f.minFramesForTargetMS,arrayBufferToBase64:f.arrayBufferToBase64,encodeWAV:f.encodeWAV};var g=Yf;Object.defineProperty(o,"AudioNodeVAD",{enumerable:!0,get:function(){return g.AudioNodeVAD}}),Object.defineProperty(o,"DEFAULT_MODEL",{enumerable:!0,get:function(){return g.DEFAULT_MODEL}}),Object.defineProperty(o,"MicVAD",{enumerable:!0,get:function(){return g.MicVAD}}),Object.defineProperty(o,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return g.getDefaultRealTimeVADOptions}})}(Hd);const Xf=Tb({__proto__:null,default:eI(Hd)},[Hd]);let St;const Jf=At.ref(!1),Qf=At.ref(!1),Zf=At.ref(!1),em=At.ref({}),tm=At.ref({}),nm=At.ref(!1),rm=At.ref(void 0),Xu=At.ref({}),Vd=At.ref({}),Ju=At.ref([]),sm=At.ref("default"),im=At.ref("default"),am=At.ref(!1),om=At.ref(!1),lm=At.ref(!0),um=At.ref(!1),cm=At.ref(null),Sl=At.ref(void 0),dm=At.ref(!1),hm=At.ref(2),pm=At.ref(1),jd=At.ref({}),_m=At.ref({}),fm=At.ref({}),Gd=At.computed(()=>{const o={};return Object.entries(em.value).forEach(([n,r])=>{jd.value[n]?.isTransferred||(o[n]=r)}),o}),hI=At.computed(()=>{const o={},n=Object.values(Gd.value).map(r=>r.roomId);return Object.entries(Xu.value).forEach(([r,a])=>{n.includes(a.roomId)&&(o[r]=a)}),o}),pI=At.computed(()=>Ju.value.filter(o=>o.kind==="audioinput").map(o=>({deviceId:o.deviceId,kind:o.kind,groupId:o.groupId,label:o.label}))),_I=At.computed(()=>Ju.value.filter(o=>o.kind==="audiooutput").map(o=>({deviceId:o.deviceId,kind:o.kind,groupId:o.groupId,label:o.label}))),mm=At.computed(()=>Object.values(Gd.value).filter(o=>o.roomId===Sl.value));At.watch(mm,o=>{!o.length&&Sl.value&&(Sl.value=void 0)});const Wd={state:{isInitialized:Jf,isOpenSIPSReady:Qf,isOpenSIPSReconnecting:Zf,activeCalls:Gd,callsInActiveRoom:mm,activeMessages:tm,addCallToCurrentRoom:nm,callAddingInProgress:rm,activeRooms:hI,msrpHistory:Vd,availableMediaDevices:Ju,inputMediaDeviceList:pI,outputMediaDeviceList:_I,selectedOutputDevice:sm,selectedInputDevice:im,muteWhenJoin:am,isDND:om,isCallWaitingEnabled:lm,isMuted:um,originalStream:cm,currentActiveRoomId:Sl,callStatus:jd,callTime:_m,callMetrics:fm,autoAnswer:dm,microphoneInputLevel:hm,speakerVolume:pm},actions:{init(o,n,r={}){return new Promise((a,c)=>{try{const e={...r,session_timers:!1,uri:`sip:${o.username}@${o.domain}`,password:o.password};r.noiseReductionOptions?e.noiseReductionOptions={...r.noiseReductionOptions,vadModule:Xf}:e.noiseReductionOptions={mode:"disabled",vadModule:Xf},o.authorization_jwt&&(e.authorization_jwt=o.authorization_jwt);const f={};o.msrpDomain&&(f.msrpDomain=o.msrpDomain),o.msrpWs&&(f.msrpWs=o.msrpWs),St=new Z1({configuration:e,socketInterfaces:[`wss://${o.domain}`],sipDomain:`${o.domain}`,sipOptions:{session_timers:!1,extraHeaders:["X-Bar: bar"],pcConfig:{}},modules:o.modules,pnExtraHeaders:n,...f}),St.on("connection",g=>{nm.value=!1,Jf.value=!0,Qf.value=g,a(St)}).on("reconnecting",g=>{Zf.value=g}).on("changeActiveCalls",g=>{em.value={...g}}).on("changeActiveMessages",g=>{tm.value={...g}}).on("newMSRPMessage",g=>{const d=g.session._id,A=Vd.value[d]||[];A.push(g.message),Vd.value[d]=[...A]}).on("callAddingInProgressChanged",g=>{rm.value=g}).on("changeAvailableDeviceList",g=>{Ju.value=[...g]}).on("changeActiveInputMediaDevice",g=>{im.value=g}).on("changeActiveOutputMediaDevice",g=>{sm.value=g}).on("changeMuteWhenJoin",g=>{am.value=g}).on("changeIsCallWaiting",g=>{lm.value=g}).on("changeIsDND",g=>{om.value=g}).on("changeIsMuted",g=>{um.value=g}).on("changeActiveStream",g=>{cm.value=g}).on("currentActiveRoomChanged",g=>{Sl.value=g}).on("addRoom",({roomList:g})=>{Xu.value={...g}}).on("updateRoom",({roomList:g})=>{Xu.value={...g}}).on("removeRoom",({roomList:g})=>{Xu.value={...g}}).on("changeCallStatus",g=>{jd.value={...g}}).on("changeCallTime",g=>{_m.value={...g}}).on("changeCallMetrics",g=>{fm.value={...g}}).begin(),a(St)}catch(e){console.error(e),c()}})},unregister(){St?.unregister()},register(){St?.register()},disconnect(){St?.disconnect()},initCall(o,n=!1,r=!1){St?.audio.initCall(o,n,r)},answerCall(o){St?.audio.answerCall(o)},terminateCall(o){St?.audio.terminateCall(o)},mute(){St?.audio.mute()},unmute(){St?.audio.unmute()},transferCall(o,n){St?.audio.transferCall(o,n)},mergeCall(o){St?.audio.mergeCall(o)},mergeCallByIds(o,n){St?.audio.mergeCallByIds(o,n)},holdCall(o,n){St?.audio.holdCall(o,n)},unholdCall(o){St?.audio.unholdCall(o)},async moveCall(o,n){await St?.audio.moveCall(o,n)},muteCaller(o){St?.audio.muteCaller(o)},unmuteCaller(o){St?.audio.unmuteCaller(o)},setMuteWhenJoin(o){St?.audio.setMuteWhenJoin(o)},setDND(o){St?.audio.setDND(o)},setCallWaiting(o){St?.audio.setCallWaiting(o)},async setMicrophone(o){await St?.audio.setMicrophone(o)},async setSpeaker(o){await St?.audio.setSpeaker(o)},sendDTMF(o,n){St?.audio.sendDTMF(o,n)},async setActiveRoom(o){await St?.audio.setActiveRoom(o)},setMicrophoneSensitivity(o){hm.value=o,St?.audio.setMicrophoneSensitivity(o)},setSpeakerVolume(o){pm.value=o,St?.audio.setSpeakerVolume(o)},setAutoAnswer(o){dm.value=o,St?.audio.setAutoAnswer(o)},setMetricsConfig(o){St?.audio.setMetricsConfig(o)},setVADConfiguration(o){St?.audio.setVADConfiguration(o)},getNoiseReductionMode(){return St?.audio.getNoiseReductionMode()},msrpAnswer(o){St?.msrp.msrpAnswer(o)},messageTerminate(o){St?.msrp.messageTerminate(o)},sendMSRP(o,n){St?.msrp.sendMSRP(o,n)},initMSRP(o,n,r){St?.msrp.initMSRP(o,n,r)}}},gm=Symbol();function fI(){return At.provide(gm,Wd),Wd}function mI(){const o=At.inject(gm);if(!o)throw new Error("useVsipInject() is called without provider, please call useVsipProvide() first");return o}xs.useVsipInject=mI,xs.useVsipProvide=fI,xs.vsipAPI=Wd,Object.defineProperty(xs,Symbol.toStringTag,{value:"Module"})});
|
|
2991
|
+
*/o.exports=r})(zf);var Ff=zf.exports,zd={},Bf={};Object.defineProperty(Bf,"__esModule",{value:!0});var Wu={},Vf;Object.defineProperty(Wu,"__esModule",{value:!0}),Wu.SileroLegacy=void 0;const jf=ao;class Fd{constructor(n,r,a,c,e){this.ortInstance=n,this._session=r,this._h=a,this._c=c,this._sr=e,this.reset_state=()=>{const _=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",_,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",_,[2,1,64])},this.process=async _=>{const d={input:new this.ortInstance.Tensor("float32",_,[1,_.length]),h:this._h,c:this._c,sr:this._sr},A=await this._session.run(d);this._h=A.hn,this._c=A.cn;const[S]=A.output?.data;return{notSpeech:1-S,isSpeech:S}}}}Wu.SileroLegacy=Fd,Vf=Fd,Fd.new=async(o,n)=>{jf.log.debug("initializing vad");const r=await n(),a=await o.InferenceSession.create(r),c=new o.Tensor("int64",[16000n]),e=Array(2*64).fill(0),_=new o.Tensor("float32",e,[2,1,64]),g=new o.Tensor("float32",e,[2,1,64]);return jf.log.debug("vad is initialized"),new Vf(o,a,_,g,c)};var Ku={},Gf;Object.defineProperty(Ku,"__esModule",{value:!0}),Ku.SileroV5=void 0;const Wf=ao;function Kf(o){const n=Array(256).fill(0);return new o.Tensor("float32",n,[2,1,128])}class Bd{constructor(n,r,a,c){this._session=n,this._state=r,this._sr=a,this.ortInstance=c,this.reset_state=()=>{this._state=Kf(this.ortInstance)},this.process=async e=>{const g={input:new this.ortInstance.Tensor("float32",e,[1,e.length]),state:this._state,sr:this._sr},d=await this._session.run(g);this._state=d.stateN;const[A]=d.output?.data;return{notSpeech:1-A,isSpeech:A}}}}Ku.SileroV5=Bd,Gf=Bd,Bd.new=async(o,n)=>{Wf.log.debug("Loading VAD...");const r=await n(),a=await o.InferenceSession.create(r),c=new o.Tensor("int64",[16000n]),e=Kf(o);return Wf.log.debug("...finished loading VAD"),new Gf(a,e,c,o)},function(o){var n=Gn&&Gn.__createBinding||(Object.create?function(e,_,g,d){d===void 0&&(d=g);var A=Object.getOwnPropertyDescriptor(_,g);(!A||("get"in A?!_.__esModule:A.writable||A.configurable))&&(A={enumerable:!0,get:function(){return _[g]}}),Object.defineProperty(e,d,A)}:function(e,_,g,d){d===void 0&&(d=g),e[d]=_[g]}),r=Gn&&Gn.__exportStar||function(e,_){for(var g in e)g!=="default"&&!Object.prototype.hasOwnProperty.call(_,g)&&n(_,e,g)};Object.defineProperty(o,"__esModule",{value:!0}),o.SileroV5=o.SileroLegacy=void 0,r(Bf,o);var a=Wu;Object.defineProperty(o,"SileroLegacy",{enumerable:!0,get:function(){return a.SileroLegacy}});var c=Ku;Object.defineProperty(o,"SileroV5",{enumerable:!0,get:function(){return c.SileroV5}})}(zd);var wl={};Object.defineProperty(wl,"__esModule",{value:!0}),wl.Resampler=void 0;const sI=ao;class iI{constructor(n){this.options=n,this.process=r=>{const a=[];for(const c of r)for(this.inputBuffer.push(c);this.hasEnoughDataForFrame();){const e=this.generateOutputFrame();a.push(e)}return a},n.nativeSampleRate<16e3&&sI.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(n){for(const r of n)for(this.inputBuffer.push(r);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const n=new Float32Array(this.options.targetFrameSize);let r=0,a=0;for(;r<this.options.targetFrameSize;){let c=0,e=0;for(;a<Math.min(this.inputBuffer.length,(r+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const _=this.inputBuffer[a];_!==void 0&&(c+=_,e++),a++}n[r]=c/e,r++}return this.inputBuffer=this.inputBuffer.slice(a),n}}wl.Resampler=iI,function(o){var n=Gn&&Gn.__createBinding||(Object.create?function(N,H,W,G){G===void 0&&(G=W);var K=Object.getOwnPropertyDescriptor(H,W);(!K||("get"in K?!H.__esModule:K.writable||K.configurable))&&(K={enumerable:!0,get:function(){return H[W]}}),Object.defineProperty(N,G,K)}:function(N,H,W,G){G===void 0&&(G=W),N[G]=H[W]}),r=Gn&&Gn.__setModuleDefault||(Object.create?function(N,H){Object.defineProperty(N,"default",{enumerable:!0,value:H})}:function(N,H){N.default=H}),a=Gn&&Gn.__importStar||function(N){if(N&&N.__esModule)return N;var H={};if(N!=null)for(var W in N)W!=="default"&&Object.prototype.hasOwnProperty.call(N,W)&&n(H,N,W);return r(H,N),H};Object.defineProperty(o,"__esModule",{value:!0}),o.NonRealTimeVAD=o.defaultNonRealTimeVADOptions=void 0;const c=a(Ff),e=Tl,_=io,g=us,d=Ea,A=zd,S=wl;o.defaultNonRealTimeVADOptions={...g.defaultFrameProcessorOptions,modelURL:e.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:_.defaultModelFetcher};class R{static async new(H={}){const W={...o.defaultNonRealTimeVADOptions,...H};(0,g.validateOptions)(W),W.ortConfig!==void 0&&W.ortConfig(c);const G=()=>W.modelFetcher(W.modelURL),K=await A.SileroLegacy.new(c,G),ae=new g.FrameProcessor(K.process,K.reset_state,{positiveSpeechThreshold:W.positiveSpeechThreshold,negativeSpeechThreshold:W.negativeSpeechThreshold,redemptionMs:W.redemptionMs,preSpeechPadMs:W.preSpeechPadMs,minSpeechMs:W.minSpeechMs,submitUserSpeechOnPause:W.submitUserSpeechOnPause},1536/16);return ae.resume(),new this(G,c,W,ae)}constructor(H,W,G,K){this.modelFetcher=H,this.ort=W,this.options=G,this.frameProcessor=K,this.frameSamples=1536}async*run(H,W){const G={nativeSampleRate:W,targetSampleRate:16e3,targetFrameSize:this.frameSamples},K=new S.Resampler(G);let ae=0,ee=0,De=0;for await(const re of K.stream(H)){const be=[];await this.frameProcessor.process(re,Ne=>{be.push(Ne)});for(const Ne of be)switch(Ne.msg){case d.Message.SpeechStart:ae=De*this.frameSamples/16;break;case d.Message.SpeechEnd:ee=(De+1)*this.frameSamples/16,yield{audio:Ne.audio,start:ae,end:ee};break}De++}const X=[];this.frameProcessor.endSegment(re=>{X.push(re)});for(const re of X)switch(re.msg){case d.Message.SpeechEnd:yield{audio:re.audio,start:ae,end:De*this.frameSamples/16}}}}o.NonRealTimeVAD=R}(Hf);var cs={};Object.defineProperty(cs,"__esModule",{value:!0}),cs.audioFileToArray=cs.encodeWAV=cs.arrayBufferToBase64=cs.minFramesForTargetMS=void 0;function aI(o,n,r=16e3){return Math.ceil(o*r/1e3/n)}cs.minFramesForTargetMS=aI;function oI(o){const n=new Uint8Array(o),r=n.byteLength,a=new Array(r);for(var c=0;c<r;c++){const e=n[c];if(e===void 0)break;a[c]=String.fromCharCode(e)}return btoa(a.join(""))}cs.arrayBufferToBase64=oI;function lI(o,n=3,r=16e3,a=1,c=32){var e=c/8,_=a*e,g=new ArrayBuffer(44+o.length*e),d=new DataView(g);return Yu(d,0,"RIFF"),d.setUint32(4,36+o.length*e,!0),Yu(d,8,"WAVE"),Yu(d,12,"fmt "),d.setUint32(16,16,!0),d.setUint16(20,n,!0),d.setUint16(22,a,!0),d.setUint32(24,r,!0),d.setUint32(28,r*_,!0),d.setUint16(32,_,!0),d.setUint16(34,c,!0),Yu(d,36,"data"),d.setUint32(40,o.length*e,!0),n===1?cI(d,44,o):uI(d,44,o),g}cs.encodeWAV=lI;function uI(o,n,r){for(var a=0;a<r.length;a++,n+=4)o.setFloat32(n,r[a],!0)}function cI(o,n,r){for(var a=0;a<r.length;a++,n+=2){var c=Math.max(-1,Math.min(1,r[a]));o.setInt16(n,c<0?c*32768:c*32767,!0)}}function Yu(o,n,r){for(var a=0;a<r.length;a++)o.setUint8(n+a,r.charCodeAt(a))}async function dI(o){const n=new OfflineAudioContext(1,1,44100),r=new FileReader;let a=null;if(await new Promise(_=>{r.addEventListener("loadend",g=>{const d=r.result;n.decodeAudioData(d,A=>{a=A,n.startRendering().then(S=>{console.log("Rendering completed successfully"),_()}).catch(S=>{console.error(`Rendering failed: ${S}`)})},A=>{console.log(`Error with decoding audio data: ${A}`)})}),r.readAsArrayBuffer(o)}),a===null)throw Error("some shit");let c=a,e=new Float32Array(c.length);for(let _=0;_<c.length;_++)for(let g=0;g<c.numberOfChannels;g++)e[_]+=c.getChannelData(g)[_];return{audio:e,sampleRate:c.sampleRate}}cs.audioFileToArray=dI;var Yf={};(function(o){var n=Gn&&Gn.__createBinding||(Object.create?function(ae,ee,De,X){X===void 0&&(X=De);var re=Object.getOwnPropertyDescriptor(ee,De);(!re||("get"in re?!ee.__esModule:re.writable||re.configurable))&&(re={enumerable:!0,get:function(){return ee[De]}}),Object.defineProperty(ae,X,re)}:function(ae,ee,De,X){X===void 0&&(X=De),ae[X]=ee[De]}),r=Gn&&Gn.__setModuleDefault||(Object.create?function(ae,ee){Object.defineProperty(ae,"default",{enumerable:!0,value:ee})}:function(ae,ee){ae.default=ee}),a=Gn&&Gn.__importStar||function(ae){if(ae&&ae.__esModule)return ae;var ee={};if(ae!=null)for(var De in ae)De!=="default"&&Object.prototype.hasOwnProperty.call(ae,De)&&n(ee,ae,De);return r(ee,ae),ee};Object.defineProperty(o,"__esModule",{value:!0}),o.AudioNodeVAD=o.MicVAD=o.getDefaultRealTimeVADOptions=o.ort=o.DEFAULT_MODEL=void 0;const c=a(Ff),e=io,_=us,g=ao,d=Ea,A=zd,S=wl;o.DEFAULT_MODEL="legacy",o.ort=c;const R="vad.worklet.bundle.min.js",N="silero_vad_v5.onnx",H="silero_vad_legacy.onnx",W=ae=>({..._.defaultFrameProcessorOptions,onFrameProcessed:(ee,De)=>{},onVADMisfire:()=>{g.log.debug("VAD misfire")},onSpeechStart:()=>{g.log.debug("Detected speech start")},onSpeechEnd:()=>{g.log.debug("Detected speech end")},onSpeechRealStart:()=>{g.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:ae,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async ee=>{ee.getTracks().forEach(De=>{De.stop()})},resumeStream:async ee=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:ee=>{ee.env.logLevel="error"},startOnLoad:!0});o.getDefaultRealTimeVADOptions=W;class G{static async new(ee={}){const De={...(0,o.getDefaultRealTimeVADOptions)(ee.model??o.DEFAULT_MODEL),...ee};(0,_.validateOptions)(De);const X=new AudioContext,re=await K.new(X,De),be=new G(De,X,re);if(De.startOnLoad)try{await be.start()}catch(Ne){console.error("Error starting micVad",Ne)}return be}constructor(ee,De,X,re=!1){this.options=ee,this.audioContext=De,this.audioNodeVAD=X,this.listening=re,this.initialized=!1,this.pause=()=>{this.stream&&this.options.pauseStream(this.stream),this.audioNodeVAD.pause(),this.listening=!1},this.resume=async()=>{if(!this.stream){console.warn("Stream not initialized");return}this.stream=await this.options.resumeStream(this.stream),this.sourceNode&&this.sourceNode.disconnect(),this.sourceNode=new MediaStreamAudioSourceNode(this.audioContext,{mediaStream:this.stream}),this.audioNodeVAD.receive(this.sourceNode)},this.start=async()=>{this.initialized||(this.initialized=!0,this.stream=await this.options.getStream(),this.sourceNode=new MediaStreamAudioSourceNode(this.audioContext,{mediaStream:this.stream}),this.audioNodeVAD.receive(this.sourceNode)),this.stream?.active?(this.audioNodeVAD.start(),this.listening=!0):(await this.resume(),this.audioNodeVAD.start(),this.listening=!0)},this.destroy=()=>{this.listening&&this.pause(),this.stream?this.options.pauseStream(this.stream):console.warn("Stream not initialized"),this.sourceNode?this.sourceNode.disconnect():console.warn("Source node not initialized"),this.audioNodeVAD.destroy(),this.audioContext.close()},this.setOptions=be=>{this.audioNodeVAD.setFrameProcessorOptions(be)}}}o.MicVAD=G;class K{static async new(ee,De={}){const X={...(0,o.getDefaultRealTimeVADOptions)(De.model??o.DEFAULT_MODEL),...De};(0,_.validateOptions)(X),o.ort.env.wasm.wasmPaths=X.onnxWASMBasePath,X.ortConfig!==void 0&&X.ortConfig(o.ort);const re=X.model==="v5"?N:H,be=X.baseAssetPath+re,Ne=X.model==="v5"?A.SileroV5.new:A.SileroLegacy.new;let Q;try{Q=await Ne(o.ort,()=>(0,e.defaultModelFetcher)(be))}catch(ye){throw console.error(`Encountered an error while loading model file ${be}`),ye}const ce=X.model==="v5"?512:1536,me=ce/16,_e=new _.FrameProcessor(Q.process,Q.reset_state,{positiveSpeechThreshold:X.positiveSpeechThreshold,negativeSpeechThreshold:X.negativeSpeechThreshold,redemptionMs:X.redemptionMs,preSpeechPadMs:X.preSpeechPadMs,minSpeechMs:X.minSpeechMs,submitUserSpeechOnPause:X.submitUserSpeechOnPause},me),ue=new K(ee,X,_e,ce,me);return await ue.setupAudioNode(),ue}constructor(ee,De,X,re,be){this.ctx=ee,this.options=De,this.frameSamples=re,this.msPerFrame=be,this.pause=()=>{this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.start=()=>{this.frameProcessor.resume()},this.receive=Ne=>{Ne.connect(this.audioNode)},this.processFrame=async Ne=>{await this.frameProcessor.process(Ne,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ne=>{switch(Ne.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(Ne.probs,Ne.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(Ne.audio);break}},this.destroy=()=>{this.audioNode instanceof AudioWorkletNode&&this.audioNode.port.postMessage({message:d.Message.SpeechStop}),this.audioNode.disconnect(),this.gainNode?.disconnect()},this.setFrameProcessorOptions=Ne=>{this.frameProcessor.options={...this.frameProcessor.options,...Ne}},this.frameProcessor=X}async setupAudioNode(){if("audioWorklet"in this.ctx&&typeof AudioWorkletNode=="function")try{const re=this.options.baseAssetPath+R;await this.ctx.audioWorklet.addModule(re);const be=this.options.workletOptions??{};be.processorOptions={...be.processorOptions??{},frameSamples:this.frameSamples},this.audioNode=new AudioWorkletNode(this.ctx,"vad-helper-worklet",be),this.audioNode.port.onmessage=async Ne=>{switch(Ne.data?.message){case d.Message.AudioFrame:let Q=Ne.data.data;Q instanceof ArrayBuffer||(Q=new ArrayBuffer(Ne.data.data.byteLength),new Uint8Array(Q).set(new Uint8Array(Ne.data.data)));const ce=new Float32Array(Q);await this.processFrame(ce);break}};return}catch(re){console.log("AudioWorklet setup failed, falling back to ScriptProcessor",re)}this.resampler=new S.Resampler({nativeSampleRate:this.ctx.sampleRate,targetSampleRate:16e3,targetFrameSize:this.frameSamples??480});const De=4096;this.audioNode=this.ctx.createScriptProcessor(De,1,1),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=0;let X=!1;this.audioNode.onaudioprocess=async re=>{if(!X){X=!0;try{const be=re.inputBuffer.getChannelData(0);if(re.outputBuffer.getChannelData(0).fill(0),this.resampler){const Q=this.resampler.process(be);for(const ce of Q)await this.processFrame(ce)}}catch(be){console.error("Error processing audio:",be)}finally{X=!1}}},this.audioNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination)}}o.AudioNodeVAD=K})(Yf),function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.getDefaultRealTimeVADOptions=o.MicVAD=o.DEFAULT_MODEL=o.AudioNodeVAD=o.utils=o.NonRealTimeVAD=o.Message=o.FrameProcessor=o.defaultModelFetcher=o.baseAssetPath=void 0;var n=Tl;Object.defineProperty(o,"baseAssetPath",{enumerable:!0,get:function(){return n.baseAssetPath}});var r=io;Object.defineProperty(o,"defaultModelFetcher",{enumerable:!0,get:function(){return r.defaultModelFetcher}});var a=us;Object.defineProperty(o,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var c=Ea;Object.defineProperty(o,"Message",{enumerable:!0,get:function(){return c.Message}});var e=Hf;Object.defineProperty(o,"NonRealTimeVAD",{enumerable:!0,get:function(){return e.NonRealTimeVAD}});const _=cs;o.utils={audioFileToArray:_.audioFileToArray,minFramesForTargetMS:_.minFramesForTargetMS,arrayBufferToBase64:_.arrayBufferToBase64,encodeWAV:_.encodeWAV};var g=Yf;Object.defineProperty(o,"AudioNodeVAD",{enumerable:!0,get:function(){return g.AudioNodeVAD}}),Object.defineProperty(o,"DEFAULT_MODEL",{enumerable:!0,get:function(){return g.DEFAULT_MODEL}}),Object.defineProperty(o,"MicVAD",{enumerable:!0,get:function(){return g.MicVAD}}),Object.defineProperty(o,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return g.getDefaultRealTimeVADOptions}})}(Hd);const Xf=Tb({__proto__:null,default:eI(Hd)},[Hd]);let St;const Jf=At.ref(!1),Qf=At.ref(!1),Zf=At.ref(!1),em=At.ref({}),tm=At.ref({}),nm=At.ref(!1),rm=At.ref(void 0),Xu=At.ref({}),Vd=At.ref({}),Ju=At.ref([]),sm=At.ref("default"),im=At.ref("default"),am=At.ref(!1),om=At.ref(!1),lm=At.ref(!0),um=At.ref(!1),cm=At.ref(null),Sl=At.ref(void 0),dm=At.ref(!1),hm=At.ref(2),pm=At.ref(1),jd=At.ref({}),_m=At.ref({}),fm=At.ref({}),Gd=At.computed(()=>{const o={};return Object.entries(em.value).forEach(([n,r])=>{jd.value[n]?.isTransferred||(o[n]=r)}),o}),hI=At.computed(()=>{const o={},n=Object.values(Gd.value).map(r=>r.roomId);return Object.entries(Xu.value).forEach(([r,a])=>{n.includes(a.roomId)&&(o[r]=a)}),o}),pI=At.computed(()=>Ju.value.filter(o=>o.kind==="audioinput").map(o=>({deviceId:o.deviceId,kind:o.kind,groupId:o.groupId,label:o.label}))),_I=At.computed(()=>Ju.value.filter(o=>o.kind==="audiooutput").map(o=>({deviceId:o.deviceId,kind:o.kind,groupId:o.groupId,label:o.label}))),mm=At.computed(()=>Object.values(Gd.value).filter(o=>o.roomId===Sl.value));At.watch(mm,o=>{!o.length&&Sl.value&&(Sl.value=void 0)});const Wd={state:{isInitialized:Jf,isOpenSIPSReady:Qf,isOpenSIPSReconnecting:Zf,activeCalls:Gd,callsInActiveRoom:mm,activeMessages:tm,addCallToCurrentRoom:nm,callAddingInProgress:rm,activeRooms:hI,msrpHistory:Vd,availableMediaDevices:Ju,inputMediaDeviceList:pI,outputMediaDeviceList:_I,selectedOutputDevice:sm,selectedInputDevice:im,muteWhenJoin:am,isDND:om,isCallWaitingEnabled:lm,isMuted:um,originalStream:cm,currentActiveRoomId:Sl,callStatus:jd,callTime:_m,callMetrics:fm,autoAnswer:dm,microphoneInputLevel:hm,speakerVolume:pm},actions:{init(o,n,r={}){return new Promise((a,c)=>{try{const e={...r,session_timers:!1,uri:`sip:${o.username}@${o.domain}`,password:o.password};r.noiseReductionOptions?e.noiseReductionOptions={...r.noiseReductionOptions,vadModule:Xf}:e.noiseReductionOptions={mode:"disabled",vadModule:Xf},o.authorization_jwt&&(e.authorization_jwt=o.authorization_jwt);const _={};o.msrpDomain&&(_.msrpDomain=o.msrpDomain),o.msrpWs&&(_.msrpWs=o.msrpWs),St=new Z1({configuration:e,socketInterfaces:[`wss://${o.domain}`],sipDomain:`${o.domain}`,sipOptions:{session_timers:!1,extraHeaders:["X-Bar: bar"],pcConfig:{}},modules:o.modules,pnExtraHeaders:n,..._}),St.on("connection",g=>{nm.value=!1,Jf.value=!0,Qf.value=g,a(St)}).on("reconnecting",g=>{Zf.value=g}).on("changeActiveCalls",g=>{em.value={...g}}).on("changeActiveMessages",g=>{tm.value={...g}}).on("newMSRPMessage",g=>{const d=g.session._id,A=Vd.value[d]||[];A.push(g.message),Vd.value[d]=[...A]}).on("callAddingInProgressChanged",g=>{rm.value=g}).on("changeAvailableDeviceList",g=>{Ju.value=[...g]}).on("changeActiveInputMediaDevice",g=>{im.value=g}).on("changeActiveOutputMediaDevice",g=>{sm.value=g}).on("changeMuteWhenJoin",g=>{am.value=g}).on("changeIsCallWaiting",g=>{lm.value=g}).on("changeIsDND",g=>{om.value=g}).on("changeIsMuted",g=>{um.value=g}).on("changeActiveStream",g=>{cm.value=g}).on("currentActiveRoomChanged",g=>{Sl.value=g}).on("addRoom",({roomList:g})=>{Xu.value={...g}}).on("updateRoom",({roomList:g})=>{Xu.value={...g}}).on("removeRoom",({roomList:g})=>{Xu.value={...g}}).on("changeCallStatus",g=>{jd.value={...g}}).on("changeCallTime",g=>{_m.value={...g}}).on("changeCallMetrics",g=>{fm.value={...g}}).begin(),a(St)}catch(e){console.error(e),c()}})},unregister(){St?.unregister()},register(){St?.register()},disconnect(){St?.disconnect()},initCall(o,n=!1,r=!1){St?.audio.initCall(o,n,r)},answerCall(o){St?.audio.answerCall(o)},terminateCall(o){St?.audio.terminateCall(o)},mute(){St?.audio.mute()},unmute(){St?.audio.unmute()},transferCall(o,n){St?.audio.transferCall(o,n)},mergeCall(o){St?.audio.mergeCall(o)},mergeCallByIds(o,n){St?.audio.mergeCallByIds(o,n)},holdCall(o,n){St?.audio.holdCall(o,n)},unholdCall(o){St?.audio.unholdCall(o)},async moveCall(o,n){await St?.audio.moveCall(o,n)},muteCaller(o){St?.audio.muteCaller(o)},unmuteCaller(o){St?.audio.unmuteCaller(o)},setMuteWhenJoin(o){St?.audio.setMuteWhenJoin(o)},setDND(o){St?.audio.setDND(o)},setCallWaiting(o){St?.audio.setCallWaiting(o)},async setMicrophone(o){await St?.audio.setMicrophone(o)},async setSpeaker(o){await St?.audio.setSpeaker(o)},sendDTMF(o,n){St?.audio.sendDTMF(o,n)},async setActiveRoom(o){await St?.audio.setActiveRoom(o)},setMicrophoneSensitivity(o){hm.value=o,St?.audio.setMicrophoneSensitivity(o)},setSpeakerVolume(o){pm.value=o,St?.audio.setSpeakerVolume(o)},setAutoAnswer(o){dm.value=o,St?.audio.setAutoAnswer(o)},setMetricsConfig(o){St?.audio.setMetricsConfig(o)},setVADConfiguration(o){St?.audio.setVADConfiguration(o)},getNoiseReductionMode(){return St?.audio.getNoiseReductionMode()},msrpAnswer(o){St?.msrp.msrpAnswer(o)},messageTerminate(o){St?.msrp.messageTerminate(o)},sendMSRP(o,n){St?.msrp.sendMSRP(o,n)},initMSRP(o,n,r){St?.msrp.initMSRP(o,n,r)}}},gm=Symbol();function fI(){return At.provide(gm,Wd),Wd}function mI(){const o=At.inject(gm);if(!o)throw new Error("useVsipInject() is called without provider, please call useVsipProvide() first");return o}xs.useVsipInject=mI,xs.useVsipProvide=fI,xs.vsipAPI=Wd,Object.defineProperty(xs,Symbol.toStringTag,{value:"Module"})});
|
|
2992
2992
|
//# sourceMappingURL=super.umd.js.map
|