opensips-js-vue 0.1.15 → 0.1.16
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 +4 -2
- package/library/super.mjs +74 -65
- package/library/super.mjs.map +1 -1
- package/library/super.umd.js +34 -34
- package/library/super.umd.js.map +1 -1
- package/package.json +2 -2
package/library/super.umd.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(function(xs,Ct){typeof exports=="object"&&typeof module<"u"?Ct(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],Ct):(xs=typeof globalThis<"u"?globalThis:xs||self,Ct(xs["vsip-next"]={},xs.Vue))})(this,function(xs,Ct){"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 y=Function.bind.apply(a,_),d=new y;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 y=0;y<_.length;y++){var d=_[y];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(e,d.key,d)}}function r(e,_,y){return _&&n(e.prototype,_),y&&n(e,y),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(_,y,d){if(o(this,e),!_||!(_ instanceof a))throw new TypeError('missing or invalid "uri" parameter');this._uri=_,this._parameters={},this.display_name=y;for(var A in d)Object.prototype.hasOwnProperty.call(d,A)&&this.setParam(A,d[A])}return r(e,[{key:"setParam",value:function(_,y){_&&(this._parameters[_.toLowerCase()]=typeof y>"u"||y===null?null:y.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 y=this._parameters[_];return delete this._parameters[_],y}}},{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 y in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,y)&&(_+=";".concat(y),this._parameters[y]!==null&&(_+="=".concat(this._parameters[y])));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:St,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:Et,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,y=[];function d(t){e<_||(e>_&&(_=e,y=[]),y.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 y=Function.bind.apply(a,_),d=new y;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 y=0;y<_.length;y++){var d=_[y];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(e,d.key,d)}}function r(e,_,y){return _&&n(e.prototype,_),y&&n(e,y),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(_,y,d){if(o(this,e),!_||!(_ instanceof a))throw new TypeError('missing or invalid "uri" parameter');this._uri=_,this._parameters={},this.display_name=y;for(var A in d)Object.prototype.hasOwnProperty.call(d,A)&&this.setParam(A,d[A])}return r(e,[{key:"setParam",value:function(_,y){_&&(this._parameters[_.toLowerCase()]=typeof y>"u"||y===null?null:y.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 y=this._parameters[_];return delete this._parameters[_],y}}},{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 y in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,y)&&(_+=";".concat(y),this._parameters[y]!==null&&(_+="=".concat(this._parameters[y])));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,y=[];function d(t){e<_||(e>_&&(_=e,y=[]),y.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,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=St(),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 St(){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 Et(){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===`
|
|
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
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(y),xo,Is,ri.line,ri.column),-1}return M},toSource:function(){return this._source}};return n.SyntaxError=function(r,a,c,e,_){function y(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=y(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
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,y=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[y.headerize(S)]=Array.isArray(R)?R:[R]}},{key:"getHeader",value:function(S){if(S)return this._headers[y.headerize(S)]}},{key:"hasHeader",value:function(S){if(S)return this._headers.hasOwnProperty(y.headerize(S))&&!0||!1}},{key:"deleteHeader",value:function(S){if(S=y.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(y.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(y.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
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 y=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(y(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 y=c[o];if(y===void 0)return!1;if(typeof y=="function")Zh(y,this,n);else for(var d=y.length,A=op(y,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 y=new Error("Possible EventEmitter memory leak detected. "+_.length+" "+String(n)+" listeners added. Use emitter.setMaxListeners() to increase limit");y.name="MaxListenersExceededWarning",y.emitter=o,y.type=n,y.count=_.length,Gb(y)}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):y(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 y(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(y),...r.skips.map(y).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 y(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:y}=o.exports;y.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(y){return String(Number(y))===y?Number(y):y},r=function(y,d,A,S){if(S&&!A)d[S]=n(y[1]);else for(var R=0;R<A.length;R+=1)y[R+1]!=null&&(d[A[R]]=n(y[R+1]))},a=function(y,d,A){var S=y.name&&y.names;y.push&&!d[y.push]?d[y.push]=[]:S&&!d[y.name]&&(d[y.name]={});var R=y.push?{}:S?d[y.name]:d;r(A.match(y.reg),R,y.names,y.name),y.push&&d[y.push].push(R)},c=_p,e=RegExp.prototype.test.bind(/^([a-z])=(.*)/);o.parse=function(y){var d={},A=[],S=d;return y.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(y,d){var A=d.split(/=(.+)/,2);return A.length===2?y[A[0]]=n(A[1]):A.length===1&&d.length>1&&(y[A[0]]=void 0),y};o.parseParams=function(y){return y.split(/;\s?/).reduce(_,{})},o.parseFmtpConfig=o.parseParams,o.parsePayloads=function(y){return y.toString().split(" ").map(Number)},o.parseRemoteCandidates=function(y){for(var d=[],A=y.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(y){return y.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(_,{})})},o.parseSimulcastStreamList=function(y){return y.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(y){c.push(Mo(e,_,y))})})}),o.media.forEach(function(e){c.push(Mo("m",fc.m[0],e)),a.forEach(function(_){fc[_].forEach(function(y){y.name in e&&e[y.name]!=null?c.push(Mo(_,y,e)):y.push in e&&e[y.push]!=null&&e[y.push].forEach(function(d){c.push(Mo(_,y,d))})})})}),c.join(`\r
|
|
@@ -69,9 +69,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
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,_=!1,y;return{s:function(){r=o[Symbol.iterator]()},n:function(){var d=r.next();return e=d.done,d},e:function(d){_=!0,y=d},f:function(){try{!e&&r.return!=null&&r.return()}finally{if(_)throw y}}}}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 y=yu.optional[e](_);if(y!==void 0)o[e]=y;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 y=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;y===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 y,d;if(a.to_tag)y=this._findDialog(a.call_id,a.from_tag,a.to_tag),y?y.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;y=this._findDialog(A.call_id,A.from_tag,A.to_tag),y?(d=y.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,y=c+e,d=this._sessions[y],A=c+_,S=this._sessions[A];return d||S||null}},{key:"_findDialog",value:function(a,c,e){var _=a+c+e,y=this._dialogs[_];return y||(_=a+e+c,y=this._dialogs[_],y||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 y in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,y)&&(_.indexOf(y)!==-1?Object.defineProperty(this._configuration,y,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,y,{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:St,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:Et,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,y=[];function d(t){e<_||(e>_&&(_=e,y=[]),y.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,y;return{s:function(){r=o[Symbol.iterator]()},n:function(){var d=r.next();return e=d.done,d},e:function(d){_=!0,y=d},f:function(){try{!e&&r.return!=null&&r.return()}finally{if(_)throw y}}}}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 y=yu.optional[e](_);if(y!==void 0)o[e]=y;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 y=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;y===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 y,d;if(a.to_tag)y=this._findDialog(a.call_id,a.from_tag,a.to_tag),y?y.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;y=this._findDialog(A.call_id,A.from_tag,A.to_tag),y?(d=y.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,y=c+e,d=this._sessions[y],A=c+_,S=this._sessions[A];return d||S||null}},{key:"_findDialog",value:function(a,c,e){var _=a+c+e,y=this._dialogs[_];return y||(_=a+e+c,y=this._dialogs[_],y||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 y in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,y)&&(_.indexOf(y)!==-1?Object.defineProperty(this._configuration,y,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,y,{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,y=[];function d(t){e<_||(e>_&&(_=e,y=[]),y.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,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=St(),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 St(){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 Et(){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===`
|
|
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
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(y),xo,Is,ri.line,ri.column),-1}return M},toSource:function(){return this._source}};return n.SyntaxError=function(r,a,c,e,_){function y(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=y(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,_,y,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=y;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 y of this._headers[_])c.push(`${_}=${y}`);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(_,...y){for(const d of y)if(a(_[d]))return!1;return!0};const c=ln.createRandomToken=(_,y=32)=>{let d,A,S="";for(d=0;d<_;d++)A=Math.random()*y|0,S+=A.toString(y);return S};ln.newTag=()=>c(10),ln.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,_=>{const y=Math.random()*16|0;return(_==="x"?y:y&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=(_,y)=>{if(_){if(_ instanceof n)return _;if(typeof _=="string"){const d=_.split("@");let A,S;switch(d.length){case 1:if(!y)return;A=_,S=y;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 y={"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 y[A]&&(A=y[A]),A},ln.sipErrorCause=_=>{for(const y in o.SIP_ERROR_CAUSES)if(o.SIP_ERROR_CAUSES[y].indexOf(_)!==-1)return o.causes[y];return o.causes.SIP_FAILURE_CODE},ln.getRandomTestNetIP=()=>{function _(y,d){return Math.floor(Math.random()*(d-y+1)+y)}return`192.0.2.${_(1,254)}`},ln.calculateMD5=_=>{function y(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(y(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(y(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(y(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(y(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 y;if(_.getTracks){y=_.getTracks();for(const d of y)d.stop()}else{y=_.getAudioTracks();for(const d of y)d.stop();y=_.getVideoTracks();for(const d of y)d.stop()}}catch{(typeof _.stop=="function"||typeof _.stop=="object")&&_.stop()}},ln.cloneArray=_=>_&&_.slice()||[],ln.cloneObject=(_,y={})=>_&&Object.assign({},_)||y,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 y=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 $_(y,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
|
|
@@ -155,13 +155,13 @@ 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
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,y=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: ${_}`);_&&(y=y||oe.REASON_PHRASE[_]||"",e=`SIP ;cause=${_} ;text="${y}"`),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(_,y,a,c),this._failed("local",null,oe.causes.REJECTED);break;case dt.STATUS_WAITING_FOR_ACK:case dt.STATUS_CONFIRMED:if(y=n.reason_phrase||oe.REASON_PHRASE[_]||"",_&&(_<200||_>=700))throw new TypeError(`Invalid status_code: ${_}`);if(_&&a.push(`Reason: SIP ;cause=${_}; text="${y}"`),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 y=0;y<e.length;y++)_.push(e.charCodeAt(y).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 y=0;y<e.length;y++)_.push(e.charCodeAt(y).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 y=this._earlyDialogs[_];if(a)return y?!0:(y=new Ru(this,n,r,Ru.C.STATUS_EARLY),y.error?(console.log("failed 8"),this._failed("remote",n,oe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[_]=y,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,y)return y.update(n,r),this._dialog=y,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
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 y=c+2;for(;;){if(c=TA(o,y),c===-2){a=y+2;break}else if(c===-1){Hu.warn("parseMessage() | malformed message");return}if(_=bA(r,o,y,c),_!==!0){Hu.warn("parseMessage() |",_.error);return}y=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(),y=n.substring(e+1,a).trim();switch(_.toLowerCase()){case"via":case"v":o.addHeader("via",y),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",y),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",y),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=kd.parse(y,"Record_Route"),c===-1)c=void 0;else for(const d of c)o.addHeader("record-route",y.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",y),c=o.parseHeader("call-id"),c&&(o.call_id=y);break;case"contact":case"m":if(c=kd.parse(y,"Contact"),c===-1)c=void 0;else for(const d of c)o.addHeader("contact",y.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",y),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",y),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",y),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",y),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",y),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",y),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",y),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",y),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",y),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",y),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(_,y),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 y=_.getParam("expires");!y&&c.hasHeader("expires")&&(y=c.getHeader("expires")),y||(y=this._expires),y=Number(y),y<zu&&(y=zu);const d=y>64?y*1e3/2+Math.floor((y/2-32)*1e3*Math.random()):y*1e3-5e3;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,y=e.outbound||null;let d="<";return _?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),y&&(_?!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 y,d;if(n.to_tag)if(y=this._findDialog(n.call_id,n.from_tag,n.to_tag),y)y.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;y=this._findDialog(A.call_id,A.from_tag,A.to_tag),y?(d=y.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:y=>{e.gain.value=y?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 y=d=>{d?a(o[_]):e===o.length&&a(),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(y).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 y=d=>{d?a(_):e===o.length&&a(-1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(y).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 y=d=>{d?a(!0):e===o.length&&a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(y).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 y=d=>{d?e===o.length&&a(!0):a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(y).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 y=0;y<o.length;y++)y in o&&(e[y]=Promise.resolve(o[y]).then(d=>n.call(r||globalThis,d,y,o)).catch(c));const _=[];for(let y=0;y<e.length;y++)await e[y]&&_.push(await o[y]);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},_,y=typeof Symbol=="function"?Symbol:{},d=y.iterator||"@@iterator",A=y.asyncIterator||"@@asyncIterator",S=y.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 y(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 y(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",y=[],d=[],A=[];return n&&(c.length&&(e=Sf(c,e)),d=e.split("")),r&&(c.length&&(_=Sf(c,_)),A=_.split("")),y=[...d,...A,...a],n1(y,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 y=_[n][c];return y?y[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((_,y)=>_+y,0)/c.length;return e===0?null:c.map(_=>Math.abs(e-_)).reduce((_,y)=>_+y,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((_,y)=>_+y,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(y=>{const d=_[ie.AUDIO][y];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,y),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_in",y),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_in",y),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_in",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_in",!1,y),min:en(this._reports,ie.AUDIO,"delta_kbs_in",y),max:tn(this._reports,ie.AUDIO,"delta_kbs_in",y),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_in",y),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_in",!1,y),min:en(this._reports,ie.AUDIO,"delta_KBytes_in",y),max:tn(this._reports,ie.AUDIO,"delta_KBytes_in",y),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_in",y),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_in",!1,y),min:en(this._reports,ie.AUDIO,"mos_emodel_in",y),max:tn(this._reports,ie.AUDIO,"mos_emodel_in",y),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_in",y)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_in",!1,y),min:en(this._reports,ie.AUDIO,"mos_in",y),max:tn(this._reports,ie.AUDIO,"mos_in",y),volatility:Zt(this._reports,ie.AUDIO,"mos_in",y)},_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",y),W=Un(this._reports,ie.AUDIO,"total_packets_in",y),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[y].jitter=A,e[y].mos=N,e[y].traffic=R,e[y].bitrate=S,e[y].loss=G}else{const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_out",!1,y),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_out",y),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_out",y),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_out",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_out",!1,y),min:en(this._reports,ie.AUDIO,"delta_kbs_out",y),max:tn(this._reports,ie.AUDIO,"delta_kbs_out",y),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_out",y),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_out",!1,y),min:en(this._reports,ie.AUDIO,"delta_KBytes_out",y),max:tn(this._reports,ie.AUDIO,"delta_KBytes_out",y),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_out",y),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},N={avg:$f(this._reports,ie.AUDIO,y),min:en(this._reports,ie.AUDIO,"delta_rtt_ms_out",y),max:tn(this._reports,ie.AUDIO,"delta_rtt_ms_out",y),volatility:Zt(this._reports,ie.AUDIO,"delta_rtt_ms_out",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_out",y),W=Un(this._reports,ie.AUDIO,"total_packets_out",y),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,y),min:en(this._reports,ie.AUDIO,"mos_emodel_out",y),max:tn(this._reports,ie.AUDIO,"mos_emodel_out",y),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_out",y)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_out",!1,y),min:en(this._reports,ie.AUDIO,"mos_out",y),max:tn(this._reports,ie.AUDIO,"mos_out",y),volatility:Zt(this._reports,ie.AUDIO,"mos_out",y)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[y].jitter=A,e[y].rtt=N,e[y].traffic=R,e[y].bitrate=S,e[y].loss=G,e[y].mos=K}}),Object.keys(_[ie.VIDEO]).forEach(y=>{const d=_[ie.VIDEO][y];if(e[y]={type:ie.VIDEO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_in",!1,y),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_in",y),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_in",y),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_in",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_in",!1,y),min:en(this._reports,ie.VIDEO,"delta_kbs_in",y),max:tn(this._reports,ie.VIDEO,"delta_kbs_in",y),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_in",y),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_in",!1,y),min:en(this._reports,ie.VIDEO,"delta_KBytes_in",y),max:tn(this._reports,ie.VIDEO,"delta_KBytes_in",y),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_in",y),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N=Un(this._reports,ie.VIDEO,"total_packets_lost_in",y),H=Un(this._reports,ie.VIDEO,"total_packets_in",y),W={lost:N,avg:Math.round((N/(N+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[y].jitter=A,e[y].traffic=R,e[y].bitrate=S,e[y].loss=W}else{const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_out",!1,y),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_out",y),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_out",y),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_out",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_out",!1,y),min:en(this._reports,ie.VIDEO,"delta_kbs_out",y),max:tn(this._reports,ie.VIDEO,"delta_kbs_out",y),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_out",y),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_out",!1,y),min:en(this._reports,ie.VIDEO,"delta_KBytes_out",y),max:tn(this._reports,ie.VIDEO,"delta_KBytes_out",y),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_out",y),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={avg:$f(this._reports,ie.VIDEO,y),min:en(this._reports,ie.VIDEO,"delta_rtt_ms_out",y),max:tn(this._reports,ie.VIDEO,"delta_rtt_ms_out",y),volatility:Zt(this._reports,ie.VIDEO,"delta_rtt_ms_out",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.VIDEO,"total_packets_lost_out",y),W=Un(this._reports,ie.VIDEO,"total_packets_out",y),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[y].jitter=A,e[y].rtt=N,e[y].traffic=R,e[y].bitrate=S,e[y].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,y=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])-y,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),y=_-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?y*.008*1024/R*1e3:0;return{packetsSent:c,deltaPacketsSent:e,KBytesSent:_,deltaKBytesSent:y,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,y=c-r[n].total_packets_in,d=c!==r[n].total_packets_in?_*100/(_+y):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:y,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,y=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?y*.008*1024/S*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:c,delta_KBytes_received:_,delta_KBytes_sent:y,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],y=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:y}},{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],y=wn(_,n,Ht.INBOUND);y&&(y.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,y,d),S=Bu(o,ie.AUDIO,y),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,y),S=Df(o,ie.VIDEO,y,d),R=Bu(o,ie.VIDEO,y),N=o[ge.DECODER_IMPLEMENTATION]||null,H=o[ge.CODEC_ID]||null,W=Nf(o),G=A1(o,y,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],y=wn(_,n,Ht.OUTBOUND);y&&(y.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,y,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,y),N=Nf(o),H=C1(o),W=I1(o,y,d),G=Of(o,ie.VIDEO,y,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 y=n[ie.AUDIO][_];if(y.codec_id_in===o[ge.ID]||y.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=R1(o);o[ge.ID]===y.codec_id_in?e.push({ssrc:y.ssrc,type:Me.AUDIO,value:{codec_in:d}}):e.push({ssrc:y.ssrc,type:Me.AUDIO,value:{codec_out:d}})}}),Object.keys(n[ie.VIDEO]).forEach(_=>{const y=n[ie.VIDEO][_];if(y.codec_id_in===o[ge.ID]||y.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=$1(o);o[ge.ID]===y.codec_id_in?e.push({ssrc:y.ssrc,type:Me.VIDEO,value:{codec_in:d}}):e.push({ssrc:y.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],y=wn(_,n,Ht.OUTBOUND),d=wn(_,a,Ht.OUTBOUND);if(o[ge.KIND]===ie.AUDIO){const A=xf(o,ie.AUDIO,d,y),S=Bu(o,ie.AUDIO,y),R=kf(o,ie.AUDIO,y,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,y),S=Bu(o,ie.VIDEO,y),R=kf(o,ie.VIDEO,y,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),y=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=y&&y[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),y=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=y&&y[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=y&&y[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),y=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=y&&y[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),y&&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),y=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=y&&y[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=y&&y[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),y&&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 y=null;return n.forEach(d=>{!y&&d.timestamp&&(y=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=y,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(),y=this.analyze(_,null,null,null),d=Date.now();y.experimental.time_to_measure_ms=d-e,y.experimental.time_to_wait_ms=c,this._exporter.saveReferenceReport(y),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(y=>y.isRunning);for(const y of _){const d=await y.collectStats();d&&e.probes.push(d),Rt(jn,`got probe ${y.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(),y=Date.now();_.delta_time_consumed_to_measure_ms=y-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 y=0;const d=_.length;for(let S=0;S<d;S++)y+=_[S];const A=y/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((_,y)=>{try{_.disconnect(),a++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting source ${y}:`,d)}});let c=0;r.destinations.forEach((_,y)=>{try{_.disconnect(),c++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${y}:`,d)}});let e=0;r.gains.forEach((_,y)=>{try{_.disconnect(),e++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${y}:`,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})}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((_,y)=>{const d=setTimeout(()=>{y(new Error("Hold operation timeout"))},5e3),A=()=>{clearTimeout(d),c.putOnHoldTimestamp=r?Date.now():void 0,_()},S=R=>{clearTimeout(d),y(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(y=>y.roomId===c.roomId&&(r?n!==y._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()),y=e.createAnalyser();y.fftSize=1024;const d=new Float32Array(y.fftSize);_.connect(y);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(()=>{y.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 y=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]=y,y.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 y=!c;e.audioTag.muted=y,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 y=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(a[0],y);const d=y.getTracks();await _.replaceTrack(d[0]),this.muteReconfigure(e)}catch(y){console.error(y)}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(y=>y.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((y,d)=>{y&&y.connection&&y.connection.getReceivers().forEach((A,S)=>{var R,N,H;A.track.enabled=!y.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=`${y._id}-${W}`;A.track&&A.track.readyState==="live"&&_.set(G,A.track)})}),await this.setupActiveStream(),await XA.forEach(n,async(y,d)=>{if(!y||!y.connection)return;const A=c.createMediaStreamDestination();e.destinations.set(y._id,A);let S=0;if(_.forEach((H,W)=>{if(!W.startsWith(y._id))try{const G=c.createMediaStreamSource(new MediaStream([H])),K=c.createGain(),ae=`${y._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=`${y._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 ${y._id}`);const R=y.connection.getSenders()[0],N=A.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(y,A.stream),R&&N[0])try{await R.replaceTrack(N[0]),this.muteReconfigure(y)}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 y=c,d=this.hasAutoAnswerHeaders(n),A=y.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);y.roomId=e,y.localMuted=!1,y.autoAnswer=A,A?this.addCall(y,!1):this.addCall(y),this.addCallStatus(c.id),this.addRoom(_),A&&this.answerCall(y._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,_;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 y=this.getActiveCalls[r.id];y&&this.activeCallListRemove(y),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(_=this.initialStreamValue)==null||_.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,_;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 y=this.getActiveCalls[r.id];y&&this.activeCallListRemove(y),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(_=this.initialStreamValue)==null||_.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=_=>{Object.entries(_.audio).forEach(([A,S])=>{S.direction==="inbound"&&!c.includes(A)&&(c.push(A),e=A)});const y=_.audio[e];if(!y)return;const d=F1(y,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 y=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(A=>A.audioTag&&A.audioTag.id===r._id)&&kA(y,r,this.selectedOutputDevice,this.speakerVolume);const d=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!d),await this.setupVUMeter(y,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 _,y,d,A;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((y=(_=S.plugindata)==null?void 0:_.data)==null?void 0:y.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
|
|
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(),y=n.substring(e+1,a).trim();switch(_.toLowerCase()){case"via":case"v":o.addHeader("via",y),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",y),c=o.parseHeader("from"),c&&(o.from=c,o.from_tag=c.getParam("tag"));break;case"to":case"t":o.setHeader("to",y),c=o.parseHeader("to"),c&&(o.to=c,o.to_tag=c.getParam("tag"));break;case"record-route":if(c=kd.parse(y,"Record_Route"),c===-1)c=void 0;else for(const d of c)o.addHeader("record-route",y.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",y),c=o.parseHeader("call-id"),c&&(o.call_id=y);break;case"contact":case"m":if(c=kd.parse(y,"Contact"),c===-1)c=void 0;else for(const d of c)o.addHeader("contact",y.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",y),c=o.parseHeader("content-length");break;case"content-type":case"c":o.setHeader("content-type",y),c=o.parseHeader("content-type");break;case"cseq":o.setHeader("cseq",y),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",y),c=o.parseHeader("max-forwards");break;case"www-authenticate":o.setHeader("www-authenticate",y),c=o.parseHeader("www-authenticate");break;case"proxy-authenticate":o.setHeader("proxy-authenticate",y),c=o.parseHeader("proxy-authenticate");break;case"session-expires":case"x":o.setHeader("session-expires",y),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",y),c=o.parseHeader("refer-to"),c&&(o.refer_to=c);break;case"replaces":o.setHeader("replaces",y),c=o.parseHeader("replaces"),c&&(o.replaces=c);break;case"event":case"o":o.setHeader("event",y),c=o.parseHeader("event"),c&&(o.event=c);break;default:o.addHeader(_,y),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 y=_.getParam("expires");!y&&c.hasHeader("expires")&&(y=c.getHeader("expires")),y||(y=this._expires),y=Number(y),y<zu&&(y=zu);const d=y>64?y*1e3/2+Math.floor((y/2-32)*1e3*Math.random()):y*1e3-5e3;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,y=e.outbound||null;let d="<";return _?d+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":d+=this.pub_gruu||this.uri.toString(),y&&(_?!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 y,d;if(n.to_tag)if(y=this._findDialog(n.call_id,n.from_tag,n.to_tag),y)y.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;y=this._findDialog(A.call_id,A.from_tag,A.to_tag),y?(d=y.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:y=>{e.gain.value=y?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 y=d=>{d?a(o[_]):e===o.length&&a(),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(y).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 y=d=>{d?a(_):e===o.length&&a(-1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(y).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 y=d=>{d?a(!0):e===o.length&&a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(y).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 y=d=>{d?e===o.length&&a(!0):a(!1),e++};Promise.resolve(o[_]).then(d=>n.call(r||globalThis,d,_,o)).then(y).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 y=0;y<o.length;y++)y in o&&(e[y]=Promise.resolve(o[y]).then(d=>n.call(r||globalThis,d,y,o)).catch(c));const _=[];for(let y=0;y<e.length;y++)await e[y]&&_.push(await o[y]);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},_,y=typeof Symbol=="function"?Symbol:{},d=y.iterator||"@@iterator",A=y.asyncIterator||"@@asyncIterator",S=y.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 y(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 y(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",y=[],d=[],A=[];return n&&(c.length&&(e=Sf(c,e)),d=e.split("")),r&&(c.length&&(_=Sf(c,_)),A=_.split("")),y=[...d,...A,...a],n1(y,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 y=_[n][c];return y?y[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((_,y)=>_+y,0)/c.length;return e===0?null:c.map(_=>Math.abs(e-_)).reduce((_,y)=>_+y,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((_,y)=>_+y,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(y=>{const d=_[ie.AUDIO][y];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,y),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_in",y),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_in",y),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_in",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_in",!1,y),min:en(this._reports,ie.AUDIO,"delta_kbs_in",y),max:tn(this._reports,ie.AUDIO,"delta_kbs_in",y),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_in",y),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_in",!1,y),min:en(this._reports,ie.AUDIO,"delta_KBytes_in",y),max:tn(this._reports,ie.AUDIO,"delta_KBytes_in",y),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_in",y),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={emodel:{avg:nn(this._reports,ie.AUDIO,"mos_emodel_in",!1,y),min:en(this._reports,ie.AUDIO,"mos_emodel_in",y),max:tn(this._reports,ie.AUDIO,"mos_emodel_in",y),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_in",y)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_in",!1,y),min:en(this._reports,ie.AUDIO,"mos_in",y),max:tn(this._reports,ie.AUDIO,"mos_in",y),volatility:Zt(this._reports,ie.AUDIO,"mos_in",y)},_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",y),W=Un(this._reports,ie.AUDIO,"total_packets_in",y),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[y].jitter=A,e[y].mos=N,e[y].traffic=R,e[y].bitrate=S,e[y].loss=G}else{const A={avg:nn(this._reports,ie.AUDIO,"delta_jitter_ms_out",!1,y),min:en(this._reports,ie.AUDIO,"delta_jitter_ms_out",y),max:tn(this._reports,ie.AUDIO,"delta_jitter_ms_out",y),volatility:Zt(this._reports,ie.AUDIO,"delta_jitter_ms_out",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.AUDIO,"delta_kbs_out",!1,y),min:en(this._reports,ie.AUDIO,"delta_kbs_out",y),max:tn(this._reports,ie.AUDIO,"delta_kbs_out",y),volatility:Zt(this._reports,ie.AUDIO,"delta_kbs_out",y),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.AUDIO,"delta_KBytes_out",!1,y),min:en(this._reports,ie.AUDIO,"delta_KBytes_out",y),max:tn(this._reports,ie.AUDIO,"delta_KBytes_out",y),volatility:Zt(this._reports,ie.AUDIO,"delta_KBytes_out",y),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},N={avg:$f(this._reports,ie.AUDIO,y),min:en(this._reports,ie.AUDIO,"delta_rtt_ms_out",y),max:tn(this._reports,ie.AUDIO,"delta_rtt_ms_out",y),volatility:Zt(this._reports,ie.AUDIO,"delta_rtt_ms_out",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.AUDIO,"total_packets_lost_out",y),W=Un(this._reports,ie.AUDIO,"total_packets_out",y),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,y),min:en(this._reports,ie.AUDIO,"mos_emodel_out",y),max:tn(this._reports,ie.AUDIO,"mos_emodel_out",y),volatility:Zt(this._reports,ie.AUDIO,"mos_emodel_out",y)},effective:{avg:nn(this._reports,ie.AUDIO,"mos_out",!1,y),min:en(this._reports,ie.AUDIO,"mos_out",y),max:tn(this._reports,ie.AUDIO,"mos_out",y),volatility:Zt(this._reports,ie.AUDIO,"mos_out",y)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[y].jitter=A,e[y].rtt=N,e[y].traffic=R,e[y].bitrate=S,e[y].loss=G,e[y].mos=K}}),Object.keys(_[ie.VIDEO]).forEach(y=>{const d=_[ie.VIDEO][y];if(e[y]={type:ie.VIDEO,direction:d.direction},d.direction===Ht.INBOUND){const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_in",!1,y),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_in",y),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_in",y),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_in",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_in",!1,y),min:en(this._reports,ie.VIDEO,"delta_kbs_in",y),max:tn(this._reports,ie.VIDEO,"delta_kbs_in",y),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_in",y),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_in",!1,y),min:en(this._reports,ie.VIDEO,"delta_KBytes_in",y),max:tn(this._reports,ie.VIDEO,"delta_KBytes_in",y),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_in",y),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N=Un(this._reports,ie.VIDEO,"total_packets_lost_in",y),H=Un(this._reports,ie.VIDEO,"total_packets_in",y),W={lost:N,avg:Math.round((N/(N+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[y].jitter=A,e[y].traffic=R,e[y].bitrate=S,e[y].loss=W}else{const A={avg:nn(this._reports,ie.VIDEO,"delta_jitter_ms_out",!1,y),min:en(this._reports,ie.VIDEO,"delta_jitter_ms_out",y),max:tn(this._reports,ie.VIDEO,"delta_jitter_ms_out",y),volatility:Zt(this._reports,ie.VIDEO,"delta_jitter_ms_out",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},S={avg:nn(this._reports,ie.VIDEO,"delta_kbs_out",!1,y),min:en(this._reports,ie.VIDEO,"delta_kbs_out",y),max:tn(this._reports,ie.VIDEO,"delta_kbs_out",y),volatility:Zt(this._reports,ie.VIDEO,"delta_kbs_out",y),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:nn(this._reports,ie.VIDEO,"delta_KBytes_out",!1,y),min:en(this._reports,ie.VIDEO,"delta_KBytes_out",y),max:tn(this._reports,ie.VIDEO,"delta_KBytes_out",y),volatility:Zt(this._reports,ie.VIDEO,"delta_KBytes_out",y),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},N={avg:$f(this._reports,ie.VIDEO,y),min:en(this._reports,ie.VIDEO,"delta_rtt_ms_out",y),max:tn(this._reports,ie.VIDEO,"delta_rtt_ms_out",y),volatility:Zt(this._reports,ie.VIDEO,"delta_rtt_ms_out",y),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Un(this._reports,ie.VIDEO,"total_packets_lost_out",y),W=Un(this._reports,ie.VIDEO,"total_packets_out",y),G={lost:H,avg:Math.round((H/(H+W)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[y].jitter=A,e[y].rtt=N,e[y].traffic=R,e[y].bitrate=S,e[y].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,y=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])-y,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),y=_-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?y*.008*1024/R*1e3:0;return{packetsSent:c,deltaPacketsSent:e,KBytesSent:_,deltaKBytesSent:y,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,y=c-r[n].total_packets_in,d=c!==r[n].total_packets_in?_*100/(_+y):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:y,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,y=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?y*.008*1024/S*1e3:0;return{total_KBytes_received:a,total_KBytes_sent:c,delta_KBytes_received:_,delta_KBytes_sent:y,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],y=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:y}},{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],y=wn(_,n,Ht.INBOUND);y&&(y.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,y,d),S=Bu(o,ie.AUDIO,y),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,y),S=Df(o,ie.VIDEO,y,d),R=Bu(o,ie.VIDEO,y),N=o[ge.DECODER_IMPLEMENTATION]||null,H=o[ge.CODEC_ID]||null,W=Nf(o),G=A1(o,y,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],y=wn(_,n,Ht.OUTBOUND);y&&(y.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,y,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,y),N=Nf(o),H=C1(o),W=I1(o,y,d),G=Of(o,ie.VIDEO,y,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 y=n[ie.AUDIO][_];if(y.codec_id_in===o[ge.ID]||y.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=R1(o);o[ge.ID]===y.codec_id_in?e.push({ssrc:y.ssrc,type:Me.AUDIO,value:{codec_in:d}}):e.push({ssrc:y.ssrc,type:Me.AUDIO,value:{codec_out:d}})}}),Object.keys(n[ie.VIDEO]).forEach(_=>{const y=n[ie.VIDEO][_];if(y.codec_id_in===o[ge.ID]||y.codec_id_out===o[ge.ID]){Rt(gi,`analyze() - got stats ${o[ge.TYPE]} for ${r}`,o);const d=$1(o);o[ge.ID]===y.codec_id_in?e.push({ssrc:y.ssrc,type:Me.VIDEO,value:{codec_in:d}}):e.push({ssrc:y.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],y=wn(_,n,Ht.OUTBOUND),d=wn(_,a,Ht.OUTBOUND);if(o[ge.KIND]===ie.AUDIO){const A=xf(o,ie.AUDIO,d,y),S=Bu(o,ie.AUDIO,y),R=kf(o,ie.AUDIO,y,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,y),S=Bu(o,ie.VIDEO,y),R=kf(o,ie.VIDEO,y,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),y=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=y&&y[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),y=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=y&&y[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=y&&y[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),y=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=y&&y[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),y&&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),y=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=y&&y[n].delta_rtt_ms_out||null,W=e[n].delta_jitter_ms_out,G=_&&_[n].delta_jitter_ms_out||null,K=y&&y[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),y&&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 y=null;return n.forEach(d=>{!y&&d.timestamp&&(y=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=y,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(),y=this.analyze(_,null,null,null),d=Date.now();y.experimental.time_to_measure_ms=d-e,y.experimental.time_to_wait_ms=c,this._exporter.saveReferenceReport(y),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(y=>y.isRunning);for(const y of _){const d=await y.collectStats();d&&e.probes.push(d),Rt(jn,`got probe ${y.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(),y=Date.now();_.delta_time_consumed_to_measure_ms=y-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 y=0;const d=_.length;for(let S=0;S<d;S++)y+=_[S];const A=y/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((_,y)=>{try{_.disconnect(),a++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting source ${y}:`,d)}});let c=0;r.destinations.forEach((_,y)=>{try{_.disconnect(),c++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${y}:`,d)}});let e=0;r.gains.forEach((_,y)=>{try{_.disconnect(),e++}catch(d){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${y}:`,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((_,y)=>{const d=setTimeout(()=>{y(new Error("Hold operation timeout"))},5e3),A=()=>{clearTimeout(d),c.putOnHoldTimestamp=r?Date.now():void 0,_()},S=R=>{clearTimeout(d),y(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(y=>y.roomId===c.roomId&&(r?n!==y._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()),y=e.createAnalyser();y.fftSize=1024;const d=new Float32Array(y.fftSize);_.connect(y);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(()=>{y.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 y=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]=y,y.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 y=!c;e.audioTag.muted=y,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 y=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(a[0],y);const d=y.getTracks();await _.replaceTrack(d[0]),this.muteReconfigure(e)}catch(y){console.error(y)}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(y=>y.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((y,d)=>{y&&y.connection&&y.connection.getReceivers().forEach((A,S)=>{var R,N,H;A.track.enabled=!y.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=`${y._id}-${W}`;A.track&&A.track.readyState==="live"&&_.set(G,A.track)})}),await this.setupActiveStream(),await XA.forEach(n,async(y,d)=>{if(!y||!y.connection)return;const A=c.createMediaStreamDestination();e.destinations.set(y._id,A);let S=0;if(_.forEach((H,W)=>{if(!W.startsWith(y._id))try{const G=c.createMediaStreamSource(new MediaStream([H])),K=c.createGain(),ae=`${y._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=`${y._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 ${y._id}`);const R=y.connection.getSenders()[0],N=A.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(y,A.stream),R&&N[0])try{await R.replaceTrack(N[0]),this.muteReconfigure(y)}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 y=c,d=this.hasAutoAnswerHeaders(n),A=y.direction==="incoming"&&!this.hasActiveCalls&&(d||this.autoAnswer);y.roomId=e,y.localMuted=!1,y.autoAnswer=A,A?this.addCall(y,!1):this.addCall(y),this.addCallStatus(c.id),this.addRoom(_),A&&this.answerCall(y._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,_;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 y=this.getActiveCalls[r.id];y&&this.activeCallListRemove(y),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(_=this.initialStreamValue)==null||_.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,_;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 y=this.getActiveCalls[r.id];y&&this.activeCallListRemove(y),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(_=this.initialStreamValue)==null||_.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=_=>{Object.entries(_.audio).forEach(([A,S])=>{S.direction==="inbound"&&!c.includes(A)&&(c.push(A),e=A)});const y=_.audio[e];if(!y)return;const d=F1(y,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 y=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(A=>A.audioTag&&A.audioTag.id===r._id)&&kA(y,r,this.selectedOutputDevice,this.speakerVolume);const d=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!d),await this.setupVUMeter(y,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 _,y,d,A;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const S=JSON.parse(e.body)||{};((y=(_=S.plugindata)==null?void 0:_.data)==null?void 0:y.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
159
|
`),y=_[_.length-1],d=JSON.parse(y);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 y=this.speaking;if(this.reset(),y)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 y=await this.modelProcessFunc(e),d=y.isSpeech>=this.options.positiveSpeechThreshold;if(_({probs:y,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})),y.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,_=Object.prototype.hasOwnProperty,y=(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 g of e(u))!_.call(s,g)&&g!==p&&a(s,g,{get:()=>u[g],enumerable:!(m=c(u,g))||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 g=H.indexOf(s);g!==-1&&H.splice(g,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,g,T=[],b=new Set;for(let E of m){let C=await G(E);typeof C=="string"?T.push({name:E,err:C}):(g||(g=C),g===C&&b.add(E))}if(!g)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[g,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 g,T;u?.tensorLayout!==void 0&&u.tensorLayout==="NHWC"?(g=s.dims[2],T=s.dims[3]):(g=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*g,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<g;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 g,T,b;u?.tensorLayout!==void 0&&u.tensorLayout==="NHWC"?(g=s.dims[2],T=s.dims[1],b=s.dims[3]):(g=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*g;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(g,T);for(let Y=0;Y<T*g;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,g=u.norm??{mean:255,bias:0},T,b;typeof g.mean=="number"?T=[g.mean,g.mean,g.mean,g.mean]:T=[g.mean[0],g.mean[1],g.mean[2],g.mean[3]??255],typeof g.bias=="number"?b=[g.bias,g.bias,g.bias,g.bias]:b=[g.bias[0],g.bias[1],g.bias[2],g.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,g=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(g){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:g,dispose:T}=u,b=[1,m,p,4];return new wt({location:"texture",type:"float32",texture:s,dims:b,download:g,dispose:T})},Se=(s,u)=>{let{dataType:p,dims:m,download:g,dispose:T}=u;return new wt({location:"gpu-buffer",type:p??"float32",gpuBuffer:s,dims:m,download:g,dispose:T})},$e=(s,u)=>{let{dataType:p,dims:m,download:g,dispose:T}=u;return new wt({location:"ml-tensor",type:p??"float32",mlTensor:s,dims:m,download:g,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,g;if(typeof s=="object"&&"location"in s)switch(this.dataLocation=s.location,m=s.type,g=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");g=w,this.cpuData=b,this.dataLocation="cpu"}let T=It(g);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=g,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 g=0;g<p.length;g++){if(m&&!p[g].includes("TRACE_FUNC")){let T=`FUNC_${s}::${p[g].trim().split(" ")[1]}`;u&&(T+=`::${u}`),ut("CPU",T);return}p[g].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 g={},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}.`);g[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,g[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)g[C]=null;let w=await this.handler.run(u,g,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,g){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 g=="object"&&g!==null)b=g;else if(typeof g<"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:g}=p;Dh(g,m).then(()=>{postMessage({type:u})},T=>{postMessage({type:u,err:T})});break}case"copy-from":{let{buffer:m}=p,g=ic(m);postMessage({type:u,out:g});break}case"create":{let{model:m,options:g}=p;Mh(m,g).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:g,inputs:T,outputIndices:b,options:w}=p;Lh(m,g,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 g=Ws&&!(s||u);if(g)if(gn)g=$r(gn);else if(m&&!p)g=!0;else throw new Error("cannot determine the script source URL.");if(g)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 g=s.wasmPaths,T=typeof g=="string"?g:void 0,b=g?.mjs,w=b?.href??b,E=g?.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,St,yr=d(()=>{gr(),yn=(s,u)=>{let p=$t(),m=p.lengthBytesUTF8(s)+1,g=p._malloc(m);return p.stringToUTF8(s,g,m),u.push(g),g},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(([g,T])=>{let b=u?u+g:g;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}`)})},St=s=>{let u=$t(),p=u.stackSave();try{let m=u.PTR_SIZE,g=u.stackAlloc(2*m);u._OrtGetLastError(g,g+m);let T=Number(u.getValue(g,m===4?"i32":"i64")),b=u.getValue(g+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=[],g=s||{};try{if(s?.logSeverityLevel===void 0)g.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)g.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&&(g.terminate=!1);let T=0;return s?.tag!==void 0&&(T=yn(s.tag,m)),p=u._OrtCreateRunOptions(g.logSeverityLevel,g.logVerbosityLevel,!!g.terminate,T),p===0&&St("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&&St(`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 g=yn(u,m),T=yn(p,m);$t()._OrtAddSessionConfigEntry(s,g,T)!==0&&St(`Can't set a session config entry: ${u} - ${p}.`)},cr=async(s,u,p)=>{for(let m of u){let g=typeof m=="string"?m:m.name,T=[];switch(g){case"webnn":if(g="WEBNN",typeof m!="string"){let $=m?.deviceType;$&&Tr(s,"deviceType",$,p)}break;case"webgpu":if(g="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: ${g}`)}let b=yn(g,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&&St(`Can't append execution provider: ${g}.`)}},$i=async s=>{let u=$t(),p=0,m=[],g=s||{};xr(g);try{let T=Ii(g.graphOptimizationLevel??"all"),b=Ri(g.executionMode??"sequential"),w=typeof g.logId=="string"?yn(g.logId,m):0,E=g.logSeverityLevel??2;if(!Number.isInteger(E)||E<0||E>4)throw new Error(`log severity level is not valid: ${E}`);let C=g.logVerbosityLevel??0;if(!Number.isInteger(C)||C<0||C>4)throw new Error(`log verbosity level is not valid: ${C}`);let $=typeof g.optimizedModelFilePath=="string"?yn(g.optimizedModelFilePath,m):0;if(p=u._OrtCreateSessionOptions(T,!!g.enableCpuMemArena,!!g.enableMemPattern,b,!!g.enableProfiling,0,w,E,C,$),p===0&&St("Can't create session options."),g.executionProviders&&await cr(p,g.executionProviders,m),g.enableGraphCapture!==void 0){if(typeof g.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${g.enableGraphCapture}`);Tr(p,"enableGraphCapture",g.enableGraphCapture.toString(),m)}if(g.freeDimensionOverrides)for(let[x,O]of Object.entries(g.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&&St(`Can't set a free dimension override: ${x} - ${O}.`)}return g.extra!==void 0&&hs(g.extra,"",new WeakSet,(x,O)=>{Tr(p,x,O,m)}),[p,m]}catch(T){throw p!==0&&u._OrtReleaseSessionOptions(p)!==0&&St("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((g,T)=>g*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 g=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 g.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,g=u.length;if(m===0)return u;if(g===0)return s;let T=Math.max(s.length,u.length),b=new Array(T);if(p){if(m<2||g<2)return;let w=lo.calcMatMulShape([s[m-2],s[m-1]],[u[g-2],u[g-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=g-w<0?1:u[g-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 g=1;g<=p;g++)if(s[p-g]!==1&&s[p-g]!==u[m-g])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 g=new Array(m),T=m-1;for(;T>=0;){if(u[T]%p===0){g[T]=u[T]/p;break}if(p%u[T]!==0)throw new Error("cannot convert shape");g[T]=1,p/=u[T],T--}for(T--;T>=0;T--)g[T]=u[T];return g}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 g=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.");g*=Number(u[T])}return g}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 g=p-3;g>=0;--g)m[g]=m[g+1]*u[g+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((g,T)=>g+p[T]+p[T+m])}static areEqual(u,p){return u.length!==p.length?!1:u.every((m,g)=>m===p[g])}},fn=class Ul{static adjustPoolAttributes(u,p,m,g,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<g.length){if(g[w]<0)throw new Error("strides should be greater than or equal to 1")}else g.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,g,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(g.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],g[E],T,E,E+u.length-2,w)}}static computePoolOutputShape(u,p,m,g,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,g,T,b,w),E}static computeConvOutputShape(u,p,m,g,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,g,T,b,w),E}static computeShapeHelper(u,p,m,g,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],g[C],T[C],b[C],w,C,C+p.length-2,E))}static adjustPadAndReturnShape(u,p,m,g,T,b,w,E){let C=m*(g-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+g-u;return T[b]=Math.floor(E==="SAME_LOWER"?($+1)/2:$/2),T[w]=$-T[b],Math.floor((u+$-g)/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,g){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(g&&!_s.isValidBroadcast(g,[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 g=s.byteLength/m,T=new(Or(u))(s.buffer,s.byteOffset,g);switch(u){case"int64":case"uint64":{let b=new Int32Array(g);for(let w=0;w<g;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 g=BigInt64Array.from(m,BigInt);return new Uint8Array(g.buffer)}case"uint64":{if(m.some(T=>T<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let g=BigUint64Array.from(m,BigInt);return new Uint8Array(g.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 g=Int8Array.from(m,Number);return new Uint8Array(g.buffer)}case"uint8":{if(m.some(g=>g<0||g>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 g=Uint32Array.from(m,Number);return new Uint8Array(g.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,g)=>m*g)*p/8):0},Oa=class{constructor(s){this.isDataConverted=!1;let{sessionId:u,context:p,tensor:m,dataType:g,shape:T,fallbackDataType:b}=s;this.sessionId=u,this.mlContext=p,this.mlTensor=m,this.dataType=g,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,g)=>m===p[g])}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 g=this.tensorManager.getMLContext(s),T;if(!g.opSupportLimits().input.dataTypes.includes(u)){if(T=Li.get(u),!T||!g.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(g,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,g){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${u}, dataType: ${p}, shape: ${m}, copyOld: ${g}}`);let T=this.tensorTrackersById.get(u);if(!T)throw new Error("Tensor not found.");return T.ensureTensor(s,p,m,g)}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 g=this.getMLContext(s),T=Xr(),b=new Oa({sessionId:s,context:g,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,g,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:g,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((g,T)=>g===m[T]&&s[g]===u[g])},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(g=>g.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,g){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,g)}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 g=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(s,g,m,p,!1);let T=this.temporarySessionTensorIds.get(s);return T?T.push(g):this.temporarySessionTensorIds.set(s,[g]),g}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 g=Jr.get(p);if(!g)throw new Error(`Unsupported ONNX data type: ${p}`);let T=this.tensorManager.registerTensor(s,u,g,m);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${u}, dataType: ${g}, dimensions: ${m}} -> {tensorId: ${T}}`),T}registerMLConstant(s,u,p,m,g,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(g.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),g.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: ${g.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${g.dataType}, shape: ${g.shape}}} ${b?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),m.constant(g,$)}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),g=Jr.get(br(u));return typeof g>"u"?!1:p?!!m?.opSupportLimits().input.dataTypes.includes(g):!!m?.opSupportLimits().output.dataTypes.includes(g)}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 g=ms(p),T=s.device.createBuffer({size:g,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let b=s.getCommandEncoder();s.endComputePass(),b.copyBufferToBuffer(u,0,T,0,g),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,g=u.byteLength,T=ms(g),b=this.storageCache.get(s);if(!b)throw new Error("gpu data for uploading does not exist");if(Number(b.originalSize)!==g)throw new Error(`inconsistent data size. gpu data size=${b.originalSize}, data size=${g}`);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,g)),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 g=ms(p.originalSize),T=this.backend.getCommandEncoder();this.backend.endComputePass(),T.copyBufferToBuffer(p.gpuData.buffer,0,m.gpuData.buffer,0,g)}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
|
-
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,g=(u&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,T=(u&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(g||T){let w=(g?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,
|
|
163
|
+
*/(function(o,n){var r=(()=>{var a=Object.defineProperty,c=Object.getOwnPropertyDescriptor,e=Object.getOwnPropertyNames,_=Object.prototype.hasOwnProperty,y=(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 g of e(u))!_.call(s,g)&&g!==p&&a(s,g,{get:()=>u[g],enumerable:!(m=c(u,g))||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 g=H.indexOf(s);g!==-1&&H.splice(g,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,g,T=[],b=new Set;for(let E of m){let C=await G(E);typeof C=="string"?T.push({name:E,err:C}):(g||(g=C),g===C&&b.add(E))}if(!g)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[g,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 g,T;u?.tensorLayout!==void 0&&u.tensorLayout==="NHWC"?(g=s.dims[2],T=s.dims[3]):(g=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*g,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<g;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 g,T,b;u?.tensorLayout!==void 0&&u.tensorLayout==="NHWC"?(g=s.dims[2],T=s.dims[1],b=s.dims[3]):(g=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*g;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(g,T);for(let Y=0;Y<T*g;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,g=u.norm??{mean:255,bias:0},T,b;typeof g.mean=="number"?T=[g.mean,g.mean,g.mean,g.mean]:T=[g.mean[0],g.mean[1],g.mean[2],g.mean[3]??255],typeof g.bias=="number"?b=[g.bias,g.bias,g.bias,g.bias]:b=[g.bias[0],g.bias[1],g.bias[2],g.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,g=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(g){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:g,dispose:T}=u,b=[1,m,p,4];return new wt({location:"texture",type:"float32",texture:s,dims:b,download:g,dispose:T})},Se=(s,u)=>{let{dataType:p,dims:m,download:g,dispose:T}=u;return new wt({location:"gpu-buffer",type:p??"float32",gpuBuffer:s,dims:m,download:g,dispose:T})},$e=(s,u)=>{let{dataType:p,dims:m,download:g,dispose:T}=u;return new wt({location:"ml-tensor",type:p??"float32",mlTensor:s,dims:m,download:g,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,g;if(typeof s=="object"&&"location"in s)switch(this.dataLocation=s.location,m=s.type,g=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");g=w,this.cpuData=b,this.dataLocation="cpu"}let T=It(g);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=g,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 g=0;g<p.length;g++){if(m&&!p[g].includes("TRACE_FUNC")){let T=`FUNC_${s}::${p[g].trim().split(" ")[1]}`;u&&(T+=`::${u}`),ut("CPU",T);return}p[g].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 g={},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}.`);g[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,g[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)g[C]=null;let w=await this.handler.run(u,g,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,g){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 g=="object"&&g!==null)b=g;else if(typeof g<"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:g}=p;Dh(g,m).then(()=>{postMessage({type:u})},T=>{postMessage({type:u,err:T})});break}case"copy-from":{let{buffer:m}=p,g=ic(m);postMessage({type:u,out:g});break}case"create":{let{model:m,options:g}=p;Mh(m,g).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:g,inputs:T,outputIndices:b,options:w}=p;Lh(m,g,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 g=Ws&&!(s||u);if(g)if(gn)g=$r(gn);else if(m&&!p)g=!0;else throw new Error("cannot determine the script source URL.");if(g)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 g=s.wasmPaths,T=typeof g=="string"?g:void 0,b=g?.mjs,w=b?.href??b,E=g?.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,g=p._malloc(m);return p.stringToUTF8(s,g,m),u.push(g),g},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(([g,T])=>{let b=u?u+g:g;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,g=u.stackAlloc(2*m);u._OrtGetLastError(g,g+m);let T=Number(u.getValue(g,m===4?"i32":"i64")),b=u.getValue(g+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=[],g=s||{};try{if(s?.logSeverityLevel===void 0)g.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)g.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&&(g.terminate=!1);let T=0;return s?.tag!==void 0&&(T=yn(s.tag,m)),p=u._OrtCreateRunOptions(g.logSeverityLevel,g.logVerbosityLevel,!!g.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 g=yn(u,m),T=yn(p,m);$t()._OrtAddSessionConfigEntry(s,g,T)!==0&&Et(`Can't set a session config entry: ${u} - ${p}.`)},cr=async(s,u,p)=>{for(let m of u){let g=typeof m=="string"?m:m.name,T=[];switch(g){case"webnn":if(g="WEBNN",typeof m!="string"){let $=m?.deviceType;$&&Tr(s,"deviceType",$,p)}break;case"webgpu":if(g="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: ${g}`)}let b=yn(g,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: ${g}.`)}},$i=async s=>{let u=$t(),p=0,m=[],g=s||{};xr(g);try{let T=Ii(g.graphOptimizationLevel??"all"),b=Ri(g.executionMode??"sequential"),w=typeof g.logId=="string"?yn(g.logId,m):0,E=g.logSeverityLevel??2;if(!Number.isInteger(E)||E<0||E>4)throw new Error(`log severity level is not valid: ${E}`);let C=g.logVerbosityLevel??0;if(!Number.isInteger(C)||C<0||C>4)throw new Error(`log verbosity level is not valid: ${C}`);let $=typeof g.optimizedModelFilePath=="string"?yn(g.optimizedModelFilePath,m):0;if(p=u._OrtCreateSessionOptions(T,!!g.enableCpuMemArena,!!g.enableMemPattern,b,!!g.enableProfiling,0,w,E,C,$),p===0&&Et("Can't create session options."),g.executionProviders&&await cr(p,g.executionProviders,m),g.enableGraphCapture!==void 0){if(typeof g.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${g.enableGraphCapture}`);Tr(p,"enableGraphCapture",g.enableGraphCapture.toString(),m)}if(g.freeDimensionOverrides)for(let[x,O]of Object.entries(g.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 g.extra!==void 0&&hs(g.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((g,T)=>g*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 g=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 g.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,g=u.length;if(m===0)return u;if(g===0)return s;let T=Math.max(s.length,u.length),b=new Array(T);if(p){if(m<2||g<2)return;let w=lo.calcMatMulShape([s[m-2],s[m-1]],[u[g-2],u[g-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=g-w<0?1:u[g-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 g=1;g<=p;g++)if(s[p-g]!==1&&s[p-g]!==u[m-g])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 g=new Array(m),T=m-1;for(;T>=0;){if(u[T]%p===0){g[T]=u[T]/p;break}if(p%u[T]!==0)throw new Error("cannot convert shape");g[T]=1,p/=u[T],T--}for(T--;T>=0;T--)g[T]=u[T];return g}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 g=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.");g*=Number(u[T])}return g}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 g=p-3;g>=0;--g)m[g]=m[g+1]*u[g+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((g,T)=>g+p[T]+p[T+m])}static areEqual(u,p){return u.length!==p.length?!1:u.every((m,g)=>m===p[g])}},fn=class Ul{static adjustPoolAttributes(u,p,m,g,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<g.length){if(g[w]<0)throw new Error("strides should be greater than or equal to 1")}else g.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,g,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(g.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],g[E],T,E,E+u.length-2,w)}}static computePoolOutputShape(u,p,m,g,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,g,T,b,w),E}static computeConvOutputShape(u,p,m,g,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,g,T,b,w),E}static computeShapeHelper(u,p,m,g,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],g[C],T[C],b[C],w,C,C+p.length-2,E))}static adjustPadAndReturnShape(u,p,m,g,T,b,w,E){let C=m*(g-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+g-u;return T[b]=Math.floor(E==="SAME_LOWER"?($+1)/2:$/2),T[w]=$-T[b],Math.floor((u+$-g)/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,g){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(g&&!_s.isValidBroadcast(g,[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 g=s.byteLength/m,T=new(Or(u))(s.buffer,s.byteOffset,g);switch(u){case"int64":case"uint64":{let b=new Int32Array(g);for(let w=0;w<g;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 g=BigInt64Array.from(m,BigInt);return new Uint8Array(g.buffer)}case"uint64":{if(m.some(T=>T<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let g=BigUint64Array.from(m,BigInt);return new Uint8Array(g.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 g=Int8Array.from(m,Number);return new Uint8Array(g.buffer)}case"uint8":{if(m.some(g=>g<0||g>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 g=Uint32Array.from(m,Number);return new Uint8Array(g.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,g)=>m*g)*p/8):0},Oa=class{constructor(s){this.isDataConverted=!1;let{sessionId:u,context:p,tensor:m,dataType:g,shape:T,fallbackDataType:b}=s;this.sessionId=u,this.mlContext=p,this.mlTensor=m,this.dataType=g,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,g)=>m===p[g])}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 g=this.tensorManager.getMLContext(s),T;if(!g.opSupportLimits().input.dataTypes.includes(u)){if(T=Li.get(u),!T||!g.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(g,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,g){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${u}, dataType: ${p}, shape: ${m}, copyOld: ${g}}`);let T=this.tensorTrackersById.get(u);if(!T)throw new Error("Tensor not found.");return T.ensureTensor(s,p,m,g)}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 g=this.getMLContext(s),T=Xr(),b=new Oa({sessionId:s,context:g,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,g,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:g,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((g,T)=>g===m[T]&&s[g]===u[g])},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(g=>g.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,g){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,g)}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 g=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(s,g,m,p,!1);let T=this.temporarySessionTensorIds.get(s);return T?T.push(g):this.temporarySessionTensorIds.set(s,[g]),g}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 g=Jr.get(p);if(!g)throw new Error(`Unsupported ONNX data type: ${p}`);let T=this.tensorManager.registerTensor(s,u,g,m);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${u}, dataType: ${g}, dimensions: ${m}} -> {tensorId: ${T}}`),T}registerMLConstant(s,u,p,m,g,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(g.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),g.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: ${g.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${g.dataType}, shape: ${g.shape}}} ${b?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),m.constant(g,$)}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),g=Jr.get(br(u));return typeof g>"u"?!1:p?!!m?.opSupportLimits().input.dataTypes.includes(g):!!m?.opSupportLimits().output.dataTypes.includes(g)}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 g=ms(p),T=s.device.createBuffer({size:g,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let b=s.getCommandEncoder();s.endComputePass(),b.copyBufferToBuffer(u,0,T,0,g),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,g=u.byteLength,T=ms(g),b=this.storageCache.get(s);if(!b)throw new Error("gpu data for uploading does not exist");if(Number(b.originalSize)!==g)throw new Error(`inconsistent data size. gpu data size=${b.originalSize}, data size=${g}`);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,g)),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 g=ms(p.originalSize),T=this.backend.getCommandEncoder();this.backend.endComputePass(),T.copyBufferToBuffer(p.gpuData.buffer,0,m.gpuData.buffer,0,g)}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
|
+
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,g=(u&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,T=(u&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(g||T){let w=(g?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,g)=>{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,g),$=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)};
|
|
167
167
|
indices[${ke}] = dim${ke};
|
|
@@ -245,7 +245,7 @@ a=path:${n.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization
|
|
|
245
245
|
let aIndices = perm(indices);
|
|
246
246
|
|
|
247
247
|
${F.setByOffset("global_idx",P.getByIndices("aIndices"))}
|
|
248
|
-
}`},{name:"Transpose",shaderCache:{hint:`${u}`,inputDependencies:["rank"]},getRunData:()=>{let D=ne.size(T);return{outputs:[{dims:T,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:[{type:12,data:D},...Qe(b,w)]}},getShaderSource:C}},ji=(s,u)=>{fo(s.inputs,u.perm),s.compute(Ln(s.inputs[0],u.perm))},Ts=s=>
|
|
248
|
+
}`},{name:"Transpose",shaderCache:{hint:`${u}`,inputDependencies:["rank"]},getRunData:()=>{let D=ne.size(T);return{outputs:[{dims:T,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:[{type:12,data:D},...Qe(b,w)]}},getShaderSource:C}},ji=(s,u)=>{fo(s.inputs,u.perm),s.compute(Ln(s.inputs[0],u.perm))},Ts=s=>Ct({perm:s.perm})}),yo,vo,To,bs,bo,Ur,ws,Gi,Wi,Ki,qn,Yi,Xi,Ji,Qi,Zi,ea,ta,na,Ss,wo,Cl=d(()=>{rt(),ct(),at(),ri(),pr(),yo={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},vo={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},To={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},bs={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},bo=(s,u)=>{let p=[];for(let m=u-s;m<u;++m)p.push(m);return p},Ur=(s,u)=>{let p=[],m=s.length;for(let T=0;T<m;T++)u.indexOf(T)===-1&&p.push(s[T]);let g=u.map(T=>s[T]);return[p,g]},ws=(s,u)=>{let p=s.length+u.length,m=[],g=0;for(let T=0;T<p;T++)u.indexOf(T)===-1?m.push(s[g++]):m.push(1);return m},Gi=(s,u)=>{for(let p=0;p<s.length;++p)if(s[s.length-p-1]!==u-1-p)return!1;return!0},Wi=(s,u)=>{let p=[];if(!Gi(s,u)){for(let m=0;m<u;++m)s.indexOf(m)===-1&&p.push(m);s.forEach(m=>p.push(m))}return p},Ki=(s,u,p,m,g,T,b)=>{let w=p[0].dims,E=ne.size(T),C=ne.size(b),$=le("_A",p[0].dataType,w),x=Ge("output",g,T),O=64;E===1&&(O=256);let k=`
|
|
249
249
|
var<workgroup> aBestValues : array<f32, ${O}>;
|
|
250
250
|
`,D=P=>`
|
|
251
251
|
${P.registerUniform("reduceSize","u32").declareVariables($,x)}
|
|
@@ -304,7 +304,7 @@ a=path:${n.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization
|
|
|
304
304
|
${V[3]}
|
|
305
305
|
${V.length===4?U.setByOffset("global_idx","value"):V.slice(4).join(`
|
|
306
306
|
`)}
|
|
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))),
|
|
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 g=s.inputs,T=g.length===1?p:Ua(g,p);s.compute(Cs(u,{hint:T.cacheKey,inputDependencies:["rank"]},[g[0]],T.noopWithEmptyAxes&&T.axes.length===0?Es:m,T.axes,g[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,g)=>{let T=[];for(let b=0;b<p.rank;b++)(g.indexOf(b)>=0||g.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,g)=>{let T=1;for(let b=0;b<p.rank;b++)(g.indexOf(b)>=0||g.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,g)=>{let T=[];for(let b=0;b<p.rank;b++)(g.indexOf(b)>=0||g.length===0)&&T.push(`input_indices[${b}] = 0;`);return[`${T.join(`
|
|
309
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,g=1;for(let T=0;T<u.length;T++)u.indexOf(T)===-1?m*=s[T]:g*=s[T];return g<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,g,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")};
|
|
@@ -316,7 +316,7 @@ var best_index : i32 = 0;`,`if (${m.getByIndices("input_indices")} ${u.selectLas
|
|
|
316
316
|
var best_index : i32 = 0;`,`if (${m.getByIndices("input_indices")} ${u.selectLastIndex>0?">=":">"} value) {
|
|
317
317
|
value = ${m.getByIndices("input_indices")};
|
|
318
318
|
best_index = i32(last_index);
|
|
319
|
-
}`,"",g.setByOffset("global_idx","best_index")]};s.compute(Cs("argMax",{hint:u.cacheKey,inputDependencies:["rank"]},[s.inputs[0]],p,[u.axis],7,u.keepDims),{inputs:[0]})},h=s=>
|
|
319
|
+
}`,"",g.setByOffset("global_idx","best_index")]};s.compute(Cs("argMax",{hint:u.cacheKey,inputDependencies:["rank"]},[s.inputs[0]],p,[u.axis],7,u.keepDims),{inputs:[0]})},h=s=>Ct(s)}),v,I,q,j,Oe,it,an,Pr,ts=d(()=>{rt(),ct(),Qr(),at(),v=(s,u)=>{let p=s[0],m=s[1],g=s[2],T=s[3],b=s[4],w=s[5];if(b&&w)throw new Error("Attention cannot have both past and attention_bias");if(p.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let E=p.dims[0],C=p.dims[1],$=p.dims[2];if(g.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(m.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(m.dims[0]!==$)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(g.dims[0]!==m.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let x=g.dims[0]/3,O=x,k=O;if(u.qkvHiddenSizes.length>0){if(u.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let V of u.qkvHiddenSizes)if(V%u.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");x=u.qkvHiddenSizes[0],O=u.qkvHiddenSizes[1],k=u.qkvHiddenSizes[2]}let D=C;if(x!==O)throw new Error("qkv_hidden_sizes first element should be same as the second");if(g.dims[0]!==x+O+k)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let P=0;if(b){if(O!==k)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(b.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(b.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(b.dims[1]!==E)throw new Error('Input "past" second dimension must be batch_size');if(b.dims[2]!==u.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(b.dims[4]!==O/u.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');u.pastPresentShareBuffer||(P=b.dims[3])}let F=D+P,L=-1,U=0;if(T)throw new Error("Mask not supported");if(b)throw new Error("past is not supported");if(w){if(w.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(w.dims[0]!==E||w.dims[1]!==u.numHeads||w.dims[2]!==C||w.dims[3]!==F)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:E,sequenceLength:C,pastSequenceLength:P,kvSequenceLength:D,totalSequenceLength:F,maxSequenceLength:L,inputHiddenSize:$,hiddenSize:x,vHiddenSize:k,headSize:Math.floor(x/u.numHeads),vHeadSize:Math.floor(k/u.numHeads),numHeads:u.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:u.maskFilterValue,maskType:U,scale:u.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},I=(s,u,p)=>u&&s?`
|
|
320
320
|
let total_sequence_length_input = u32(${u.getByOffset("0")});
|
|
321
321
|
let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
|
|
322
322
|
let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
|
|
@@ -564,7 +564,7 @@ var best_index : i32 = 0;`,`if (${m.getByIndices("input_indices")} ${u.selectLas
|
|
|
564
564
|
let x = ${x.getByOffset("global_idx")};
|
|
565
565
|
let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
|
|
566
566
|
${F.setByOffset("global_idx","value")}
|
|
567
|
-
}`;return{name:"BatchNormalization",shaderCache:{hint:`${u.epsilon}_${u.format}_${m}_${b}`,inputDependencies:C?["rank","type","type","type","type"]:void 0},getShaderSource:U,getRunData:()=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:C?[{type:12,data:E},...Qe(T)]:[{type:12,data:E}]})}},Oo=s=>
|
|
567
|
+
}`;return{name:"BatchNormalization",shaderCache:{hint:`${u.epsilon}_${u.format}_${m}_${b}`,inputDependencies:C?["rank","type","type","type","type"]:void 0},getShaderSource:U,getRunData:()=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:C?[{type:12,data:E},...Qe(T)]:[{type:12,data:E}]})}},Oo=s=>Ct(s),ym=(s,u)=>{let{inputs:p,outputCount:m}=s,g=Oo({...u,outputCount:m});if(Q.webgpu.validateInputContent&&z(p,g),u.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");s.compute(he(p,g))}}),vm,Tm,bm,yI=d(()=>{ct(),at(),vm=s=>{if(s[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(s[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(s[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(s[0].dims[2]!==s[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Tm=s=>{let u=s[0].dims,p=s[0].dims[2],m=ne.size(u)/4,g=s[0].dataType,T=le("input",g,u,4),b=le("bias",g,[p],4),w=le("residual",g,u,4),E=Ge("output",g,u,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:u,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)}}),getShaderSource:C=>`
|
|
568
568
|
const channels = ${p}u / 4;
|
|
569
569
|
${C.declareVariables(T,b,w,E)}
|
|
570
570
|
|
|
@@ -583,7 +583,7 @@ var best_index : i32 = 0;`,`if (${m.getByIndices("input_indices")} ${u.selectLas
|
|
|
583
583
|
|
|
584
584
|
let a = ${C.getByOffset("global_idx")};
|
|
585
585
|
${$.setByOffset("global_idx",E)}
|
|
586
|
-
}`},xt=(s,u,p,m,g,T=s.dataType,b,w)=>{let E=[{type:12,data:Math.ceil(ne.size(s.dims)/4)}];return b&&E.push(...b),{name:u,shaderCache:{hint:g,inputDependencies:["type"]},getShaderSource:C=>wm(C,ne.size(s.dims),s.dataType,T,p,m,w),getRunData:C=>({outputs:[{dims:s.dims,dataType:T}],dispatchGroup:{x:Math.ceil(ne.size(C[0].dims)/64/4)},programUniforms:E})}},Sm=s=>{s.compute(xt(s.inputs[0],"Abs","abs"))},Em=s=>{s.compute(xt(s.inputs[0],"Acos","acos"))},Cm=s=>{s.compute(xt(s.inputs[0],"Acosh","acosh"))},Am=s=>{s.compute(xt(s.inputs[0],"Asin","asin"))},Im=s=>{s.compute(xt(s.inputs[0],"Asinh","asinh"))},Rm=s=>{s.compute(xt(s.inputs[0],"Atan","atan"))},$m=s=>{s.compute(xt(s.inputs[0],"Atanh","atanh"))},xm=s=>
|
|
586
|
+
}`},xt=(s,u,p,m,g,T=s.dataType,b,w)=>{let E=[{type:12,data:Math.ceil(ne.size(s.dims)/4)}];return b&&E.push(...b),{name:u,shaderCache:{hint:g,inputDependencies:["type"]},getShaderSource:C=>wm(C,ne.size(s.dims),s.dataType,T,p,m,w),getRunData:C=>({outputs:[{dims:s.dims,dataType:T}],dispatchGroup:{x:Math.ceil(ne.size(C[0].dims)/64/4)},programUniforms:E})}},Sm=s=>{s.compute(xt(s.inputs[0],"Abs","abs"))},Em=s=>{s.compute(xt(s.inputs[0],"Acos","acos"))},Cm=s=>{s.compute(xt(s.inputs[0],"Acosh","acosh"))},Am=s=>{s.compute(xt(s.inputs[0],"Asin","asin"))},Im=s=>{s.compute(xt(s.inputs[0],"Asinh","asinh"))},Rm=s=>{s.compute(xt(s.inputs[0],"Atan","atan"))},$m=s=>{s.compute(xt(s.inputs[0],"Atanh","atanh"))},xm=s=>Ct(s),Om=(s,u)=>{let p;switch(u.to){case 10:p="vec4<f16>";break;case 1:p="vec4<f32>";break;case 12:p="vec4<u32>";break;case 6:p="vec4<i32>";break;case 9:p="vec4<bool>";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${u.to}`)}s.compute(xt(s.inputs[0],"Cast",p,void 0,u.cacheKey,u.to))},km=s=>{let u,p,m=s.length>=2&&s[1].data!==0,g=s.length>=3&&s[2].data!==0;switch(s[0].dataType){case 1:u=m?s[1].getFloat32Array()[0]:-34028234663852886e22,p=g?s[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:u=m?s[1].getUint16Array()[0]:64511,p=g?s[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Ct({min:u,max:p})},Dm=(s,u)=>{let p=u||km(s.inputs),m=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"Clip",g=>`clamp(${g}, vec4<${m}>(uniforms.min), vec4<${m}>(uniforms.max))`,void 0,p.cacheKey,void 0,[{type:s.inputs[0].dataType,data:p.min},{type:s.inputs[0].dataType,data:p.max}],[{name:"min",type:m},{name:"max",type:m}]),{inputs:[0]})},Nm=s=>{s.compute(xt(s.inputs[0],"Ceil","ceil"))},Mm=s=>{s.compute(xt(s.inputs[0],"Cos","cos"))},Um=s=>{s.compute(xt(s.inputs[0],"Cosh","cosh"))},Al=s=>Ct(s),Pm=(s,u)=>{let p=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"Elu",m=>`elu_vf32(${m})`,`
|
|
587
587
|
const elu_alpha_ = ${p}(${u.alpha});
|
|
588
588
|
|
|
589
589
|
fn elu_f32(a: ${p}) -> ${p} {
|
|
@@ -604,7 +604,7 @@ fn erf_vf32(v: vec4<${s}>) -> vec4<${s}> {
|
|
|
604
604
|
let absv = abs(v);
|
|
605
605
|
let x = 1.0 / (1.0 + r0 * absv);
|
|
606
606
|
return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
|
|
607
|
-
}`,Lm=s=>{let u=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"Erf",p=>`erf_vf32(${p})`,Qu(u)))},qm=s=>{s.compute(xt(s.inputs[0],"Exp","exp"))},Hm=s=>{s.compute(xt(s.inputs[0],"Floor","floor"))},zm=s=>{let u=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"Gelu",p=>`0.5 * ${p} * (1.0 + erf_vf32(${p} * 0.7071067811865475))`,Qu(u)))},Fm=(s,u)=>{let p=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"LeakyRelu",m=>`select(leaky_relu_alpha_ * ${m}, ${m}, ${m} >= vec4<${p}>(0.0))`,`const leaky_relu_alpha_ = ${p}(${u.alpha});`,u.cacheKey))},Bm=s=>{s.compute(xt(s.inputs[0],"Not",u=>`!${u}`))},Vm=s=>{s.compute(xt(s.inputs[0],"Neg",u=>`-${u}`))},jm=s=>{s.compute(xt(s.inputs[0],"Reciprocal",u=>`1.0/${u}`))},Gm=s=>{let u=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"Relu",p=>`select(vec4<${u}>(0.0), ${p}, ${p} > vec4<${u}>(0.0))`))},Wm=s=>{s.compute(xt(s.inputs[0],"Sigmoid",u=>`(1.0 / (1.0 + exp(-${u})))`))},Km=s=>
|
|
607
|
+
}`,Lm=s=>{let u=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"Erf",p=>`erf_vf32(${p})`,Qu(u)))},qm=s=>{s.compute(xt(s.inputs[0],"Exp","exp"))},Hm=s=>{s.compute(xt(s.inputs[0],"Floor","floor"))},zm=s=>{let u=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"Gelu",p=>`0.5 * ${p} * (1.0 + erf_vf32(${p} * 0.7071067811865475))`,Qu(u)))},Fm=(s,u)=>{let p=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"LeakyRelu",m=>`select(leaky_relu_alpha_ * ${m}, ${m}, ${m} >= vec4<${p}>(0.0))`,`const leaky_relu_alpha_ = ${p}(${u.alpha});`,u.cacheKey))},Bm=s=>{s.compute(xt(s.inputs[0],"Not",u=>`!${u}`))},Vm=s=>{s.compute(xt(s.inputs[0],"Neg",u=>`-${u}`))},jm=s=>{s.compute(xt(s.inputs[0],"Reciprocal",u=>`1.0/${u}`))},Gm=s=>{let u=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"Relu",p=>`select(vec4<${u}>(0.0), ${p}, ${p} > vec4<${u}>(0.0))`))},Wm=s=>{s.compute(xt(s.inputs[0],"Sigmoid",u=>`(1.0 / (1.0 + exp(-${u})))`))},Km=s=>Ct(s),Ym=(s,u)=>{let p=Gt(s.inputs[0].dataType);s.compute(xt(s.inputs[0],"HardSigmoid",m=>`max(vec4<${p}>(0.0), min(vec4<${p}>(1.0), ${u.alpha} * ${m} + vec4<${p}>(${u.beta})))`,void 0,u.cacheKey))},Xm=s=>{s.compute(xt(s.inputs[0],"Sin","sin"))},Jm=s=>{s.compute(xt(s.inputs[0],"Sinh","sinh"))},Qm=s=>{s.compute(xt(s.inputs[0],"Sqrt","sqrt"))},Zm=s=>{s.compute(xt(s.inputs[0],"Tan","tan"))},Kd=s=>`sign(${s}) * (1 - exp(-2 * abs(${s}))) / (1 + exp(-2 * abs(${s})))`,eg=s=>{s.compute(xt(s.inputs[0],"Tanh",Kd))},Yd=(s="f32")=>`
|
|
608
608
|
const fast_gelu_a: ${s} = 0.5;
|
|
609
609
|
const fast_gelu_b: ${s} = 0.7978845608028654;
|
|
610
610
|
const fast_gelu_c: ${s} = 0.035677408136300125;
|
|
@@ -721,7 +721,7 @@ fn quick_gelu_impl(x: vec4<${s}>) -> vec4<${s}> {
|
|
|
721
721
|
}
|
|
722
722
|
|
|
723
723
|
${Eg(b,x)}
|
|
724
|
-
}`;return{name:"Concat",shaderCache:{hint:`${u}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:p,dataType:m}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:$}),getShaderSource:D}},Ag=(s,u)=>{let p=s.inputs,m=p[0].dims,g=ne.normalizeAxis(u.axis,m.length);wg(p,g);let T=m.slice();T[g]=p.reduce((w,E)=>w+(E.dims.length>g?E.dims[g]:0),0);let b=p.filter(w=>ne.size(w.dims)>0);s.compute(Cg(b,g,T,p[0].dataType),{inputs:b})},Ig=s=>
|
|
724
|
+
}`;return{name:"Concat",shaderCache:{hint:`${u}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:p,dataType:m}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:$}),getShaderSource:D}},Ag=(s,u)=>{let p=s.inputs,m=p[0].dims,g=ne.normalizeAxis(u.axis,m.length);wg(p,g);let T=m.slice();T[g]=p.reduce((w,E)=>w+(E.dims.length>g?E.dims[g]:0),0);let b=p.filter(w=>ne.size(w.dims)>0);s.compute(Cg(b,g,T,p[0].dataType),{inputs:b})},Ig=s=>Ct({axis:s.axis})}),Pa,La,qa,Qd,Ha=d(()=>{rt(),ct(),Pa=(s,u,p="f32")=>{switch(s.activation){case"Relu":return`value = max(value, ${u}(0.0));`;case"Sigmoid":return`value = (${u}(1.0) / (${u}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${u}(${p}(uniforms.clip_min)), ${u}(${p}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${u}(0.0), min(${u}(1.0), ${p}(uniforms.alpha) * value + ${p}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${p}(uniforms.alpha) * value, value, value >= ${u}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value));
|
|
725
725
|
value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
|
|
726
726
|
`;case"":return"";default:throw new Error(`Unsupported activation ${s.activation}`)}},La=(s,u)=>{s.activation==="Clip"?u.push({type:1,data:s.clipMax},{type:1,data:s.clipMin}):s.activation==="HardSigmoid"?u.push({type:1,data:s.alpha},{type:1,data:s.beta}):s.activation==="LeakyRelu"&&u.push({type:1,data:s.alpha})},qa=(s,u)=>{s.activation==="Clip"?u.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):s.activation==="HardSigmoid"?u.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):s.activation==="LeakyRelu"&&u.push({name:"alpha",type:"f32"})},Qd=s=>{let u=s?.activation||"";if(u==="HardSigmoid"){let[p,m]=s?.activation_params||[.2,.5];return{activation:u,alpha:p,beta:m}}else if(u==="Clip"){let[p,m]=s?.activation_params||[fs,Mi];return{activation:u,clipMax:m,clipMin:p}}else if(u==="LeakyRelu"){let[p]=s?.activation_params||[.01];return{activation:u,alpha:p}}return{activation:u}}}),Sn,Rg,Zd=d(()=>{Sn=(s,u)=>{switch(s){case 1:return u;case 2:return`vec2<${u}>`;case 3:return`vec3<${u}>`;case 4:return`vec4<${u}>`;default:throw new Error(`${s}-component is not supported.`)}},Rg=s=>`
|
|
727
727
|
${s?"value = value + getBiasByOutputCoords(coords);":""}
|
|
@@ -1460,7 +1460,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1460
1460
|
sum = sum + ${b.getByIndices("inputIndices")};
|
|
1461
1461
|
}
|
|
1462
1462
|
${w.setByOffset("global_idx","sum")};
|
|
1463
|
-
}`};return{name:"CumSum",shaderCache:{hint:m.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:u,dataType:s}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},{type:12,data:C},...Qe(u,u)]}),getShaderSource:$}},ny=(s,u)=>{let p=s.inputs[0].dims,m=s.inputs[0].dataType,g=s.inputs[1];s.compute(ty(m,p,g,u),{inputs:[0]})},ry=s=>{let u=s.exclusive===1,p=s.reverse===1;return
|
|
1463
|
+
}`};return{name:"CumSum",shaderCache:{hint:m.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:u,dataType:s}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},{type:12,data:C},...Qe(u,u)]}),getShaderSource:$}},ny=(s,u)=>{let p=s.inputs[0].dims,m=s.inputs[0].dataType,g=s.inputs[1];s.compute(ty(m,p,g,u),{inputs:[0]})},ry=s=>{let u=s.exclusive===1,p=s.reverse===1;return Ct({exclusive:u,reverse:p})}}),sy,iy,ay,oy,ly,xI=d(()=>{rt(),ct(),Ft(),at(),sy=s=>{if(!s||s.length!==1)throw new Error("DepthToSpace requires 1 input.");if(s[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},iy=(s,u,p,m)=>{let g=[];g.push(`fn perm(i: ${m.type.indices}) -> ${p.type.indices} {
|
|
1464
1464
|
var a: ${p.type.indices};`);for(let T=0;T<u;++T)g.push(p.indicesSet("a",s[T],`i[${T}]`));return g.push("return a;}"),g.join(`
|
|
1465
1465
|
`)},ay=(s,u)=>{let p,m,g,T,b,w,E=u.format==="NHWC",C=u.blocksize,$=u.mode==="DCR";E?([p,m,g,T]=s.dims,b=$?[p,m,g,C,C,T/C**2]:[p,m,g,T/C**2,C,C],w=$?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([p,m,g,T]=[s.dims[0],s.dims[2],s.dims[3],s.dims[1]],b=$?[p,C,C,T/C**2,m,g]:[p,T/C**2,C,C,m,g],w=$?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let x=s.reshape(b),O=x.dims.length,k=s.dataType,D=le("a",k,O),P=Ge("output",k,O),F=L=>`
|
|
1466
1466
|
${L.registerUniform("output_size","u32").declareVariables(D,P)}
|
|
@@ -1474,7 +1474,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1474
1474
|
let aIndices = perm(indices);
|
|
1475
1475
|
|
|
1476
1476
|
${P.setByOffset("global_idx",D.getByIndices("aIndices"))}
|
|
1477
|
-
}`;return{name:"DepthToSpace",shaderCache:{hint:`${s.dims};${u.blocksize};${u.mode}`,inputDependencies:["rank"]},getRunData:L=>{let U=E?[p,m*C,g*C,T/C**2]:[p,T/C**2,m*C,g*C],V=ne.size(U),B=x.dims,Y=ne.sortBasedOnPerm(B,w);return{outputs:[{dims:U,dataType:L[0].dataType}],dispatchGroup:{x:Math.ceil(V/64)},programUniforms:[{type:12,data:V},...Qe(B,Y)]}},getShaderSource:F}},oy=(s,u)=>{sy(s.inputs),s.compute(ay(s.inputs[0],u))},ly=s=>
|
|
1477
|
+
}`;return{name:"DepthToSpace",shaderCache:{hint:`${s.dims};${u.blocksize};${u.mode}`,inputDependencies:["rank"]},getRunData:L=>{let U=E?[p,m*C,g*C,T/C**2]:[p,T/C**2,m*C,g*C],V=ne.size(U),B=x.dims,Y=ne.sortBasedOnPerm(B,w);return{outputs:[{dims:U,dataType:L[0].dataType}],dispatchGroup:{x:Math.ceil(V/64)},programUniforms:[{type:12,data:V},...Qe(B,Y)]}},getShaderSource:F}},oy=(s,u)=>{sy(s.inputs),s.compute(ay(s.inputs[0],u))},ly=s=>Ct({blocksize:s.blocksize,mode:s.mode,format:s.format})}),nc,$l,ph,uy,cy,dy,hy,_h,py,_y,fy,OI=d(()=>{rt(),ct(),Ft(),at(),nc="[a-zA-Z]|\\.\\.\\.",$l="("+nc+")+",ph="^"+$l+"$",uy="("+$l+",)*"+$l,cy="^"+uy+"$",dy=class{constructor(s=-1){this.symbolToIndices=new Map,this.inputIndex=s}addSymbol(s,u){let p=this.symbolToIndices.get(s);p===void 0?p=[u]:p.push(u),this.symbolToIndices.set(s,p)}},hy=class{constructor(s,u){this.equation=u,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[p,m]=u.includes("->")?u.split("->",2):[u,""];if(!p.match(RegExp(cy)))throw new Error("Invalid LHS term");if(p.split(",").forEach((g,T)=>{let b=s[T].dims.slice();if(!g.match(RegExp(ph)))throw new Error("Invalid LHS term");let w=this.processTerm(g,!0,b,T);this.lhs.push(w)}),m==="")m+=[...this.symbolToInfo.entries()].filter(([g,T])=>T.count===1||g==="...").map(([g])=>g).join("");else if(!m.match(RegExp($l)))throw new Error("Invalid RHS");m.match(RegExp(nc,"g"))?.forEach(g=>{if(g==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let T=this.symbolToInfo.get(g);if(T===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(T.dimValue)}}),this.rhs=this.processTerm(m,!1,this.outputDims)}addSymbol(s,u,p){let m=this.symbolToInfo.get(s);if(m!==void 0){if(m.dimValue!==u&&m.count!==1)throw new Error("Dimension mismatch");m.count++,m.inputIndices.push(p)}else m={count:1,dimValue:u,inputIndices:[p]};this.symbolToInfo.set(s,m)}processTerm(s,u,p,m=-1){let g=p.length,T=!1,b=[],w=0;if(!s.match(RegExp(ph))&&!u&&s!=="")throw new Error("Invalid LHS term");let E=s.match(RegExp(nc,"g")),C=new dy(m);return E?.forEach(($,x)=>{if($==="..."){if(T)throw new Error("Only one ellipsis is allowed per input term");T=!0;let O=g-E.length+1;if(O<0)throw new Error("Ellipsis out of bounds");if(b=p.slice(w,w+O),this.hasEllipsis){if(this.ellipsisDims.length!==b.length||this.ellipsisDims.toString()!==b.toString())throw new Error("Ellipsis dimensions mismatch")}else if(u)this.hasEllipsis=!0,this.ellipsisDims=b;else throw new Error("Ellipsis must be specified in the LHS");for(let k=0;k<b.length;k++){let D=String.fromCharCode(48+k);C.addSymbol(D,x+k),this.addSymbol(D,p[w++],m)}}else C.addSymbol($,x+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol($,p[w++],m)}),C}},_h=s=>s+"_max",py=(s,u,p,m)=>{let g=s.map(C=>C.length).map((C,$)=>le(`input${$}`,u,C)),T=ne.size(m),b=Ge("output",u,m.length),w=[...p.symbolToInfo.keys()].filter(C=>!p.rhs.symbolToIndices.has(C)),E=C=>{let $=[],x="var prod = 1.0;",O="var sum = 0.0;",k="sum += prod;",D=[],P=[],F=[],L=[],U=p.symbolToInfo.size===p.rhs.symbolToIndices.size;p.symbolToInfo.forEach((B,Y)=>{if(p.rhs.symbolToIndices.has(Y)){let te=p.rhs.symbolToIndices.get(Y)?.[0];te!==void 0&&p.lhs.forEach((Z,pe)=>{if(B.inputIndices.includes(pe)){let xe=Z.symbolToIndices.get(Y);if(xe===void 0)throw new Error("Invalid symbol error");xe.forEach(je=>{$.push(`${g[pe].indicesSet(`input${pe}Indices`,je,b.indicesGet("outputIndices",te))}`)})}})}else p.lhs.forEach((te,Z)=>{if(B.inputIndices.includes(Z)){let pe=te.symbolToIndices.get(Y);if(pe===void 0)throw new Error("Invalid symbol error");pe.forEach(xe=>{D.push(`${g[Z].indicesSet(`input${Z}Indices`,xe,`${Y}`)}`)}),L.push(`prod *= ${g[Z].getByIndices(`input${Z}Indices`)};`)}}),P.push(`for(var ${Y}: u32 = 0; ${Y} < uniforms.${_h(Y)}; ${Y}++) {`),F.push("}")});let V=U?[...$,`let sum = ${g.map((B,Y)=>B.getByIndices(`input${Y}Indices`)).join(" * ")};`]:[...$,O,...P,...D,x,...L,k,...F];return`
|
|
1478
1478
|
${C.registerUniforms(w.map(B=>({name:`${_h(B)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...g,b)}
|
|
1479
1479
|
|
|
1480
1480
|
${C.mainStart()}
|
|
@@ -1485,7 +1485,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1485
1485
|
${V.join(`
|
|
1486
1486
|
`)};
|
|
1487
1487
|
${b.setByOffset("global_idx","sum")};
|
|
1488
|
-
}`};return{name:"Einsum",shaderCache:{hint:p.equation,inputDependencies:s.map(()=>"rank")},getRunData:()=>{let C=w.filter(x=>p.symbolToInfo.has(x)).map(x=>({type:12,data:p.symbolToInfo.get(x)?.dimValue||0}));C.push({type:12,data:T});let $=s.map((x,O)=>[...Qe(x)]).reduce((x,O)=>x.concat(O),C);return $.push(...Qe(m)),{outputs:[{dims:m,dataType:u}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:$}},getShaderSource:E}},_y=(s,u)=>{let p=new hy(s.inputs,u.equation),m=p.outputDims,g=s.inputs.map((T,b)=>T.dims);s.compute(py(g,s.inputs[0].dataType,p,m))},fy=s=>{let u=s.equation.replace(/\s+/g,"");return
|
|
1488
|
+
}`};return{name:"Einsum",shaderCache:{hint:p.equation,inputDependencies:s.map(()=>"rank")},getRunData:()=>{let C=w.filter(x=>p.symbolToInfo.has(x)).map(x=>({type:12,data:p.symbolToInfo.get(x)?.dimValue||0}));C.push({type:12,data:T});let $=s.map((x,O)=>[...Qe(x)]).reduce((x,O)=>x.concat(O),C);return $.push(...Qe(m)),{outputs:[{dims:m,dataType:u}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:$}},getShaderSource:E}},_y=(s,u)=>{let p=new hy(s.inputs,u.equation),m=p.outputDims,g=s.inputs.map((T,b)=>T.dims);s.compute(py(g,s.inputs[0].dataType,p,m))},fy=s=>{let u=s.equation.replace(/\s+/g,"");return Ct({equation:u})}}),my,fh,gy,yy,vy,kI=d(()=>{rt(),ct(),at(),my=s=>{if(!s||s.length!==2)throw new Error("Expand requires 2 input.");let u=s[0].dims,p=Array.from(s[1].getBigInt64Array(),Number),m=p.length<u.length?0:p.length-u.length,g=u.length<p.length?0:u.length-p.length;for(;m<p.length&&g<u.length;++m,++g)if(p[m]!==u[g]&&p[m]!==1&&u[g]!==1)throw new Error("Expand requires shape to be broadcastable to input")},fh=(s,u)=>{let p=s.length-u.length,m=[];for(let g=0;g<p;++g)m.push(s[g]);for(let g=0;g<u.length;++g)m.push(u[g]===1?s[g+p]:u[g]);return m},gy=(s,u)=>s.length>u.length?fh(s,u):fh(u,s),yy=s=>{let u=s[0].dims,p=Array.from(s[1].getBigInt64Array(),Number),m=gy(u,p),g=s[0].dataType,T=g===9||ne.size(u)===1,b=g===9||u.length>0&&u[u.length-1]%4===0?4:1,w=T||m.length>0&&m[m.length-1]%4===0?4:1,E=Math.ceil(ne.size(m)/w),C=x=>{let O=le("input",g,u.length,b),k=Ge("output",g,m.length,w),D;if(g===9){let P=(F,L,U="")=>`
|
|
1489
1489
|
let outputIndices${L} = ${k.offsetToIndices(`outputOffset + ${L}u`)};
|
|
1490
1490
|
let offset${L} = ${O.broadcastedIndicesToOffset(`outputIndices${L}`,k)};
|
|
1491
1491
|
let index${L} = offset${L} / 4u;
|
|
@@ -1554,7 +1554,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1554
1554
|
${O.mainStart()}
|
|
1555
1555
|
${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
1556
1556
|
${L}
|
|
1557
|
-
}`};return{name:"Gather",shaderCache:{hint:u.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:b,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:$}),getShaderSource:x}},Ey=s=>
|
|
1557
|
+
}`};return{name:"Gather",shaderCache:{hint:u.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:b,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:$}),getShaderSource:x}},Ey=s=>Ct({axis:s.axis}),Cy=(s,u)=>{let p=s.inputs;wy(p),s.compute(Sy(s.inputs,u))}}),Ay,Iy,Ry,MI=d(()=>{rt(),ct(),at(),Ay=(s,u,p,m,g,T,b,w,E)=>{let C=[{type:12,data:T},{type:12,data:m},{type:12,data:g},{type:12,data:p},{type:12,data:b},{type:12,data:w},{type:12,data:E}],$=[T];C.push(...Qe(u.dims,$));let x=O=>{let k=le("indices_data",u.dataType,u.dims.length),D=Ge("input_slice_offsets_data",12,1,1),P=[k,D],F=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:g.length},{name:"sizes_from_slice_dims_data",type:"u32",length:p.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`
|
|
1558
1558
|
${O.registerUniforms(F).declareVariables(...P)}
|
|
1559
1559
|
${O.mainStart()}
|
|
1560
1560
|
${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1624,7 +1624,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1624
1624
|
let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};
|
|
1625
1625
|
let dequantized_data = ${Gt(C)}(quantized_data - zero_point) * scale;
|
|
1626
1626
|
${U.setByOffset("global_idx","dequantized_data")};
|
|
1627
|
-
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${u.cacheKey};${s.filter((k,D)=>D!==1).map(k=>k.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:s.length},(k,D)=>"rank")},getRunData:()=>({outputs:[{dims:w,dataType:C}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:x}),getShaderSource:O}},Oy=(s,u)=>{let p=s.inputs;$y(p,u),s.compute(xy(s.inputs,u))},ky=s=>
|
|
1627
|
+
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${u.cacheKey};${s.filter((k,D)=>D!==1).map(k=>k.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:s.length},(k,D)=>"rank")},getRunData:()=>({outputs:[{dims:w,dataType:C}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:x}),getShaderSource:O}},Oy=(s,u)=>{let p=s.inputs;$y(p,u),s.compute(xy(s.inputs,u))},ky=s=>Ct({blockSize:s.blockSize,gatherAxis:s.gatherAxis,quantizeAxis:s.quantizeAxis})}),Dy,Ny,My,Uy,PI=d(()=>{rt(),ct(),Ft(),at(),Dy=s=>{if(!s||s.length!==2)throw new Error("GatherElements requires 2 inputs.");if(s[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(s[0].dims.length!==s[1].dims.length)throw new Error(`GatherElements requires that the data input and
|
|
1628
1628
|
indices input tensors be of same rank.`)},Ny=(s,u)=>{let p=s[0].dims,m=s[0].dataType,g=p.length,T=s[1].dims,b=s[1].dataType,w=ne.normalizeAxis(u.axis,g),E=p[w],C=T.slice(0),$=ne.size(C),x=le("input",m,g),O=le("indicesInput",b,T.length),k=Ge("output",m,C.length),D=[{type:12,data:$},{type:6,data:E},{type:12,data:w}];return D.push(...Qe(p,T,C)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:C,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:D}),getShaderSource:P=>`
|
|
1629
1629
|
${P.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(x,O,k)}
|
|
1630
1630
|
${P.mainStart()}
|
|
@@ -1641,7 +1641,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1641
1641
|
let value = ${x.getByIndices("inputIndices")};
|
|
1642
1642
|
|
|
1643
1643
|
${k.setByOffset("global_idx","value")};
|
|
1644
|
-
}`}},My=s=>
|
|
1644
|
+
}`}},My=s=>Ct({axis:s.axis}),Uy=(s,u)=>{let p=s.inputs;Dy(p),s.compute(Ny(s.inputs,u))}}),Py,Ly,qy,Hy,LI=d(()=>{rt(),ct(),at(),Py=s=>{if(!s)throw new Error("Input is missing");if(s.length<2||s.length>3)throw new Error("Invaid input number.");if(s.length===3&&s[2].dims.length>2)throw new Error("Invalid input shape of C");if(s[0].dataType!==s[1].dataType||s.length===3&&s[0].dataType!==s[2].dataType)throw new Error("Input types are mismatched")},Ly=(s,u)=>{let p=s[0].dims.slice(),m=s[1].dims.slice(),[g,T,b]=Dr.getShapeOfGemmResult(p,u.transA,m,u.transB,s.length===3?s[2].dims:void 0),w=[g,T];if(!w)throw new Error("Can't use gemm on the given tensors");let E=16,C=Math.ceil(T/E),$=Math.ceil(g/E),x=!0,O=ne.size(w),k=[{type:12,data:x?C:O},{type:12,data:g},{type:12,data:T},{type:12,data:b},{type:1,data:u.alpha},{type:1,data:u.beta}],D=["type","type"];s.length===3&&(k.push(...Qe(s[2].dims)),D.push("rank")),k.push(...Qe(w));let P=L=>{let U="";u.transA&&u.transB?U="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":u.transA&&!u.transB?U="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!u.transA&&u.transB?U="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!u.transA&&!u.transB&&(U="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let V=u.alpha===1?"":"value *= uniforms.alpha;",B=le("a",s[0].dataType,s[0].dims),Y=le("b",s[1].dataType,s[1].dims),te=B.type.value,Z=null,pe=[B,Y];s.length===3&&(Z=le("c",s[2].dataType,s[2].dims.length),pe.push(Z));let xe=Ge("output",s[0].dataType,w.length);pe.push(xe);let je=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return`
|
|
1645
1645
|
${L.registerUniforms(je).declareVariables(...pe)}
|
|
1646
1646
|
|
|
1647
1647
|
${L.mainStart()}
|
|
@@ -1894,14 +1894,14 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1894
1894
|
var y = gs_denormalize(f32(nxy[1]), H_in);
|
|
1895
1895
|
|
|
1896
1896
|
${Wy(b,w,u)}
|
|
1897
|
-
}`;return{name:"GridSample",shaderCache:{hint:`${u.cacheKey}`,inputDependencies:["type","type"]},getRunData:x=>{let O=ne.size(T);return{outputs:[{dims:T,dataType:x[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:C}},getShaderSource:$}},Yy=(s,u)=>{zy(s.inputs),s.compute(Ky(s.inputs,u))},Xy=s=>
|
|
1897
|
+
}`;return{name:"GridSample",shaderCache:{hint:`${u.cacheKey}`,inputDependencies:["type","type"]},getRunData:x=>{let O=ne.size(T);return{outputs:[{dims:T,dataType:x[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:C}},getShaderSource:$}},Yy=(s,u)=>{zy(s.inputs),s.compute(Ky(s.inputs,u))},Xy=s=>Ct({alignCorners:s.align_corners,mode:s.mode,paddingMode:s.padding_mode,format:s.format})}),tr,Jy,Qy,mh,Zy,xl,ev,tv=d(()=>{rt(),ct(),Ft(),Qr(),ts(),at(),pr(),tr=(s,u)=>s.length>u&&s[u].dims.length>0?s[u]:void 0,Jy=(s,u)=>{let p=s[0],m=tr(s,1),g=tr(s,2),T=tr(s,3),b=tr(s,4),w=tr(s,5),E=tr(s,6),C=tr(s,7);if(p.dims.length!==3&&p.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let $=p.dims[0],x=p.dims[1],O=p.dims.length===3?p.dims[2]:u.numHeads*p.dims[4],k=x,D=0,P=0,F=Math.floor(O/u.numHeads);if(E&&C&&ne.size(E.dims)&&ne.size(C.dims)){if(E.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(E.dims[0]!==$||E.dims[1]!==u.numHeads||E.dims[3]!==F)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(C.dims[0]!==$||C.dims[1]!==u.numHeads||C.dims[3]!==F)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(E.dims[2]!==C.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(C.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');D=E.dims[2],P=E.dims[2]}else if(E&&ne.size(E.dims)||C&&ne.size(C.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let L;if(m&&ne.size(m.dims)>0){if(p.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(m.dims.length<3||m.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(p.dims[0]!==m.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(m.dims.length===3){if(m.dims[2]!==p.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');L=2,k=m.dims[1]}else if(m.dims.length===5){if(m.dims[2]!==u.numHeads||m.dims[3]!==2||m.dims[4]!==F)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(g)throw new Error('Expect "value" be none when "key" has packed kv format.');L=5,k=m.dims[1]}else{if(m.dims[1]!==u.numHeads||m.dims[3]!==F)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');L=0,k=m.dims[2]}}else{if(p.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(p.dims[2]!==u.numHeads||p.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');L=3}if(T&&ne.size(T.dims)>0){if(T.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(m&&m.dims.length===5&&m.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let U=D+k,V=0;if(b&&ne.size(b.dims)>0){V=8;let Z=b.dims;throw Z.length===1?Z[0]===$?V=1:Z[0]===3*$+2&&(V=3):Z.length===2&&Z[0]===$&&Z[1]===U&&(V=5),V===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let B=!1,Y=O;if(g&&ne.size(g.dims)>0){if(g.dims.length!==3&&g.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(p.dims[0]!==g.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(g.dims.length===3){if(k!==g.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Y=g.dims[2]}else{if(k!==g.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Y=g.dims[1]*g.dims[3],B=!0}}let te=!1;if(b&&ne.size(b.dims)>0)throw new Error("Key padding mask is not supported");if(w&&ne.size(w.dims)>0){if(w.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(w.dims[0]!==$||w.dims[1]!==u.numHeads||w.dims[2]!==x||w.dims[3]!==U)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:$,sequenceLength:x,pastSequenceLength:D,kvSequenceLength:k,totalSequenceLength:U,maxSequenceLength:P,inputHiddenSize:0,hiddenSize:O,vHiddenSize:Y,headSize:F,vHeadSize:Math.floor(Y/u.numHeads),numHeads:u.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:u.maskFilterValue,maskType:V,scale:u.scale,broadcastResPosBias:te,passPastInKv:B,qkvFormat:L}},Qy=s=>Ct({...s}),mh=Ct({perm:[0,2,1,3]}),Zy=(s,u,p,m,g,T,b)=>{let w=[m,g,T],E=ne.size(w),C=[{type:12,data:E},{type:12,data:b},{type:12,data:T}],$=x=>{let O=Ge("qkv_with_bias",u.dataType,w),k=le("qkv",u.dataType,w),D=le("bias",p.dataType,w),P=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
|
|
1898
1898
|
${x.registerUniforms(P).declareVariables(k,D,O)}
|
|
1899
1899
|
${x.mainStart()}
|
|
1900
1900
|
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
1901
1901
|
let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
|
|
1902
1902
|
|
|
1903
1903
|
qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
|
|
1904
|
-
}`};return s.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:w,dataType:u.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:C}),getShaderSource:$},{inputs:[u,p],outputs:[-1]})[0]},xl=(s,u,p,m,g,T,b,w)=>{let E=T;if(b&&ne.size(b.dims)>0){if(m===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return E=Zy(s,T,b,u,m,p*g,w),E=E.reshape([u,m,p,g]),p===1||m===1?E:s.compute(Ln(E,mh.perm),{inputs:[E],outputs:[-1]})[0]}else return T.dims.length===3&&(E=T.reshape([u,m,p,g])),p===1||m===1?E:s.compute(Ln(E,mh.perm),{inputs:[E],outputs:[-1]})[0]},ev=(s,u)=>{let p=Jy(s.inputs,u),m=s.inputs[0],g=tr(s.inputs,1),T=tr(s.inputs,2),b=tr(s.inputs,3),w=tr(s.inputs,4),E=tr(s.inputs,5),C=tr(s.inputs,6),$=tr(s.inputs,7);if(m.dims.length===5)throw new Error("Packed QKV is not implemented");if(g?.dims.length===5)throw new Error("Packed KV is not implemented");let x=g&&T&&g.dims.length===4&&T.dims.length===4,O=xl(s,p.batchSize,p.numHeads,p.sequenceLength,p.headSize,m,b,0);if(x)return it(s,O,g,T,w,void 0,C,$,E,p);if(!g||!T)throw new Error("key and value must be provided");let k=xl(s,p.batchSize,p.numHeads,p.kvSequenceLength,p.headSize,g,b,p.hiddenSize),D=xl(s,p.batchSize,p.numHeads,p.kvSequenceLength,p.vHeadSize,T,b,2*p.hiddenSize);it(s,O,k,D,w,void 0,C,$,E,p)}}),nv,rv,sv,iv,gh,av,ov,lv=d(()=>{rt(),ct(),Ft(),at(),nv=s=>{if(!s||s.length<1)throw new Error("too few inputs")},rv=(s,u)=>{let p=[],m=u.numOutputs;return s[1].dims[0]>0&&(s[1].getBigInt64Array().forEach(g=>p.push(Number(g))),m=p.length),
|
|
1904
|
+
}`};return s.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:w,dataType:u.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:C}),getShaderSource:$},{inputs:[u,p],outputs:[-1]})[0]},xl=(s,u,p,m,g,T,b,w)=>{let E=T;if(b&&ne.size(b.dims)>0){if(m===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return E=Zy(s,T,b,u,m,p*g,w),E=E.reshape([u,m,p,g]),p===1||m===1?E:s.compute(Ln(E,mh.perm),{inputs:[E],outputs:[-1]})[0]}else return T.dims.length===3&&(E=T.reshape([u,m,p,g])),p===1||m===1?E:s.compute(Ln(E,mh.perm),{inputs:[E],outputs:[-1]})[0]},ev=(s,u)=>{let p=Jy(s.inputs,u),m=s.inputs[0],g=tr(s.inputs,1),T=tr(s.inputs,2),b=tr(s.inputs,3),w=tr(s.inputs,4),E=tr(s.inputs,5),C=tr(s.inputs,6),$=tr(s.inputs,7);if(m.dims.length===5)throw new Error("Packed QKV is not implemented");if(g?.dims.length===5)throw new Error("Packed KV is not implemented");let x=g&&T&&g.dims.length===4&&T.dims.length===4,O=xl(s,p.batchSize,p.numHeads,p.sequenceLength,p.headSize,m,b,0);if(x)return it(s,O,g,T,w,void 0,C,$,E,p);if(!g||!T)throw new Error("key and value must be provided");let k=xl(s,p.batchSize,p.numHeads,p.kvSequenceLength,p.headSize,g,b,p.hiddenSize),D=xl(s,p.batchSize,p.numHeads,p.kvSequenceLength,p.vHeadSize,T,b,2*p.hiddenSize);it(s,O,k,D,w,void 0,C,$,E,p)}}),nv,rv,sv,iv,gh,av,ov,lv=d(()=>{rt(),ct(),Ft(),at(),nv=s=>{if(!s||s.length<1)throw new Error("too few inputs")},rv=(s,u)=>{let p=[],m=u.numOutputs;return s[1].dims[0]>0&&(s[1].getBigInt64Array().forEach(g=>p.push(Number(g))),m=p.length),Ct({numOutputs:m,axis:u.axis,splitSizes:p})},sv=s=>`
|
|
1905
1905
|
fn calculateOutputIndex(index: u32) -> u32 {
|
|
1906
1906
|
for (var i: u32 = 0u; i < ${s}u; i += 1u ) {
|
|
1907
1907
|
if (index < ${Ke("uniforms.size_in_split_axis","i",s)}) {
|
|
@@ -1929,7 +1929,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1929
1929
|
${w.indicesSet("indices",T,"index")};
|
|
1930
1930
|
}
|
|
1931
1931
|
writeBufferData(output_number, indices, global_idx);
|
|
1932
|
-
}`;return{name:"Split",shaderCache:{hint:u.cacheKey,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:C,dispatchGroup:{x:Math.ceil(m/64)},programUniforms:O})}},av=(s,u)=>{nv(s.inputs);let p=s.inputs.length===1?u:rv(s.inputs,u);s.compute(gh(s.inputs,p),{inputs:[0]})},ov=s=>{let u=s.axis,p=s.splitSizes,m=s.numOutputs<0?p.length:s.numOutputs;if(m!==p.length)throw new Error("numOutputs and splitSizes length must be equal");return
|
|
1932
|
+
}`;return{name:"Split",shaderCache:{hint:u.cacheKey,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:C,dispatchGroup:{x:Math.ceil(m/64)},programUniforms:O})}},av=(s,u)=>{nv(s.inputs);let p=s.inputs.length===1?u:rv(s.inputs,u);s.compute(gh(s.inputs,p),{inputs:[0]})},ov=s=>{let u=s.axis,p=s.splitSizes,m=s.numOutputs<0?p.length:s.numOutputs;if(m!==p.length)throw new Error("numOutputs and splitSizes length must be equal");return Ct({axis:u,numOutputs:m,splitSizes:p})}}),uv,rc,cv,dv=d(()=>{rt(),ct(),Ft(),at(),uv=(s,u)=>{let[p,m,g,T]=s,{numHeads:b,rotaryEmbeddingDim:w}=u;if(p.dims.length!==3&&p.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${p.dims.length}`);if(!ne.areEqual(m.dims,[])&&!ne.areEqual(m.dims,[1])&&m.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${m.dims.length}`);if(g.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${g.dims.length}`);if(T.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${T.dims.length}`);if(!ne.areEqual(g.dims,T.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(w>0&&b===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let E=p.dims[0],C=p.dims[p.dims.length-2],$=g.dims[0],x=ne.sizeFromDimension(p.dims,1)/C,O=w===0?g.dims[1]*2:x/b;if(w>O)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(m.dims.length===2){if(E!==m.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${m.dims[0]}`);if(C!==m.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${m.dims[1]}`)}if(O/2!==g.dims[1]&&w/2!==g.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${g.dims[1]}`);if(C>$)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},rc=(s,u)=>{let{interleaved:p,numHeads:m,rotaryEmbeddingDim:g,scale:T}=u,b=s[0].dims[0],w=ne.sizeFromDimension(s[0].dims,1),E=s[0].dims[s[0].dims.length-2],C=w/E,$=s[2].dims[1],x=g===0?$*2:C/m,O=new Array(b,E,C/x,x-$),k=ne.computeStrides(O),D=[{type:1,data:T},{type:12,data:O},{type:12,data:k},...s[0].dims.length===3?new Array({type:12,data:[w,C,x,1]}):[],...s[0].dims.length===4?new Array({type:12,data:[w,x,E*x,1]}):[],...Qe(s[0].dims,s[1].dims,s[2].dims,s[3].dims,s[0].dims)],P=F=>{let L=le("input",s[0].dataType,s[0].dims.length),U=le("position_ids",s[1].dataType,s[1].dims.length),V=le("cos_cache",s[2].dataType,s[2].dims.length),B=le("sin_cache",s[3].dataType,s[3].dims.length),Y=Ge("output",s[0].dataType,s[0].dims.length);return F.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:O.length},{name:"global_strides",type:"u32",length:k.length},{name:"input_output_strides",type:"u32",length:k.length}]),`
|
|
1933
1933
|
${F.declareVariables(L,U,V,B,Y)}
|
|
1934
1934
|
|
|
1935
1935
|
${F.mainStart(dr)}
|
|
@@ -1955,7 +1955,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1955
1955
|
let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
|
|
1956
1956
|
${Y.setByOffset("k",L.getByOffset("k"))}
|
|
1957
1957
|
}
|
|
1958
|
-
}`};return{name:"RotaryEmbedding",shaderCache:{hint:
|
|
1958
|
+
}`};return{name:"RotaryEmbedding",shaderCache:{hint:Ct({interleaved:p}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:P,getRunData:()=>({outputs:[{dims:s[0].dims,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(ne.size(O)/dr)},programUniforms:D})}},cv=(s,u)=>{uv(s.inputs,u),s.compute(rc(s.inputs,u))}}),hv,pv,yh,_v,fv,HI=d(()=>{Ft(),rt(),ts(),tv(),lv(),pr(),dv(),at(),hv=(s,u)=>{if(u.doRotary&&s.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let p=s[0],m=s[1],g=s[2],T=s[3],b=s[4];if(u.doRotary!==0&&s.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(u.localWindowSize!==-1)throw new Error("Local attention is not supported");if(u.softcap!==0)throw new Error("Softcap is not supported");if(u.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(u.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(p.dims.length!==3&&p.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let w=!1,E=p.dims[0],C=p.dims[1],$=p.dims.length===3?w?p.dims[2]/3:p.dims[2]:u.numHeads*p.dims[4],x=C,O=0,k=!m||m.dims.length===0,D=Math.floor(k?$/(u.numHeads+2*u.kvNumHeads):$/u.numHeads);k&&($=D*u.numHeads);let P=T&&T.dims.length!==0,F=b&&b.dims.length!==0;if(P&&T.dims.length===4&&T.dims[0]===E&&T.dims[1]!==u.kvNumHeads&&T.dims[2]===u.kvNumHeads&&T.dims[3]===D)throw new Error("BSNH pastKey/pastValue is not supported");if(P&&F){if(T.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(b.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');O=T.dims[2]}else if(P||F)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let L=1;if(m&&m.dims.length>0){if(p.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(m.dims.length<3||m.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(p.dims[0]!==m.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(m.dims.length===3){if(p.dims[2]%m.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');x=m.dims[1]}else if(m.dims.length===5){if(m.dims[2]!==u.numHeads||m.dims[3]!==2||m.dims[4]!==D)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(g)throw new Error('Expect "value" be none when "key" has packed kv format.');x=m.dims[1]}else{if(m.dims[1]!==u.numHeads||m.dims[3]!==D)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');x=m.dims[2]}}else{if(p.dims.length!==3&&p.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(p.dims.length===5&&(p.dims[2]!==u.numHeads||p.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');L=3}let U=0,V=!1,B=u.kvNumHeads?D*u.kvNumHeads:$;if(g&&g.dims.length>0){if(g.dims.length!==3&&g.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(p.dims[0]!==g.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(g.dims.length===3){if(x!==g.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');B=g.dims[2]}else{if(x!==g.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');B=g.dims[1]*g.dims[3],V=!0}}let Y=s.length>4?s[5]:void 0;if(Y&&Y.dims.length!==1&&Y.dims[0]!==E)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:E,sequenceLength:C,pastSequenceLength:O,kvSequenceLength:x,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:$,vHiddenSize:B,headSize:D,vHeadSize:Math.floor(B/u.kvNumHeads),numHeads:u.numHeads,kvNumHeads:u.kvNumHeads,nReps:u.numHeads/u.kvNumHeads,pastPresentShareBuffer:!1,maskType:U,scale:u.scale,broadcastResPosBias:!1,passPastInKv:V,qkvFormat:L}},pv=Ct({perm:[0,2,1,3]}),yh=(s,u,p)=>{let m=u,g=p.kvNumHeads;return u.dims.length===3&&p.kvSequenceLength!==0&&(m=u.reshape([p.batchSize,p.kvSequenceLength,g,p.headSize]),m=s.compute(Ln(m,pv.perm),{inputs:[m],outputs:[-1]})[0]),m},_v=(s,u,p,m)=>{let g=7,T=["type","type"],b=[s*u],w=s*u,E=[{type:12,data:w},{type:12,data:u},{type:12,data:s}],C=$=>{let x=le("seq_lens",p.dataType,p.dims),O=le("total_seq_lens",m.dataType,m.dims),k=Ge("pos_ids",g,b),D=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
|
|
1959
1959
|
${$.registerUniforms(D).declareVariables(x,O,k)}
|
|
1960
1960
|
${$.mainStart()}
|
|
1961
1961
|
${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -1986,7 +1986,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
1986
1986
|
${k.setByOffset("global_idx","seqlen")}
|
|
1987
1987
|
};
|
|
1988
1988
|
}
|
|
1989
|
-
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${s};${u}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:b,dataType:g}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:E}),getShaderSource:C}},fv=(s,u)=>{let p=hv(s.inputs,u);if(s.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(s.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let m=s.inputs[0],g=s.inputs[1]&&s.inputs[1].dims.length>0?s.inputs[1]:void 0,T=s.inputs[2]&&s.inputs[2].dims.length>0?s.inputs[2]:void 0,b=s.inputs[3]&&s.inputs[3].dims.length!==0?s.inputs[3]:void 0,w=s.inputs[4]&&s.inputs[4].dims.length!==0?s.inputs[4]:void 0,E=s.inputs.length>4?s.inputs[5]:void 0,C=s.inputs.length>5?s.inputs[6]:void 0,$=p.kvNumHeads?p.kvNumHeads:p.numHeads,x=
|
|
1989
|
+
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${s};${u}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:b,dataType:g}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:E}),getShaderSource:C}},fv=(s,u)=>{let p=hv(s.inputs,u);if(s.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(s.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let m=s.inputs[0],g=s.inputs[1]&&s.inputs[1].dims.length>0?s.inputs[1]:void 0,T=s.inputs[2]&&s.inputs[2].dims.length>0?s.inputs[2]:void 0,b=s.inputs[3]&&s.inputs[3].dims.length!==0?s.inputs[3]:void 0,w=s.inputs[4]&&s.inputs[4].dims.length!==0?s.inputs[4]:void 0,E=s.inputs.length>4?s.inputs[5]:void 0,C=s.inputs.length>5?s.inputs[6]:void 0,$=p.kvNumHeads?p.kvNumHeads:p.numHeads,x=Ct({axis:2,numOutputs:3,splitSizes:[p.numHeads*p.headSize,$*p.headSize,$*p.headSize]}),[O,k,D]=!g&&!T?s.compute(gh([m],x),{inputs:[m],outputs:[-1,-1,-1]}):[m,g,T],P,F;if(u.doRotary){let B=s.compute(_v(p.batchSize,p.sequenceLength,E,C),{inputs:[E,C],outputs:[-1]})[0],Y=s.inputs[7],te=s.inputs[8],Z=Ct({interleaved:u.rotaryInterleaved!==0,numHeads:p.numHeads,rotaryEmbeddingDim:0,scale:u.scale}),pe=[O,B,Y,te],xe=[-1];P=s.compute(rc(pe,Z),{inputs:pe,outputs:xe})[0],pe.splice(0,1,k);let je=Ct({interleaved:u.rotaryInterleaved!==0,numHeads:p.kvNumHeads,rotaryEmbeddingDim:0,scale:u.scale});F=s.compute(rc(pe,je),{inputs:pe,outputs:xe})[0]}let L=xl(s,p.batchSize,p.numHeads,p.sequenceLength,p.headSize,u.doRotary?P:O,void 0,0),U=yh(s,u.doRotary?F:k,p),V=yh(s,D,p);it(s,L,U,V,void 0,void 0,b,w,void 0,p,E,C)}}),vh,mv,gv,yv,zI=d(()=>{rt(),ct(),pr(),at(),vh=(s,u,p,m,g,T,b,w)=>{let E=Ut(T),C=E===1?"f32":`vec${E}f`,$=E===1?"vec2f":`mat2x${E}f`,x=g*b,O=64;x===1&&(O=256);let k=[g,b,T/E],D=[g,b,2],P=["rank","type","type"],F=[];F.push(...Qe(k,D));let L=U=>{let V=le("x",u.dataType,3,E),B=le("scale",p.dataType,p.dims),Y=le("bias",m.dataType,m.dims),te=Ge("output",1,3,2),Z=[V,B,Y,te];return`
|
|
1990
1990
|
var<workgroup> workgroup_shared : array<${$}, ${O}>;
|
|
1991
1991
|
const workgroup_size = ${O}u;
|
|
1992
1992
|
${U.declareVariables(...Z)}
|
|
@@ -2223,7 +2223,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2223
2223
|
${Ot.setByIndices(`${Ot.type.indices}(batch, row, col + local_idx)`,"output_value")}
|
|
2224
2224
|
}
|
|
2225
2225
|
}
|
|
2226
|
-
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${u.blockSize};${x};${O};${F};${P}`,inputDependencies:Array(s.length).fill("rank")},getRunData:()=>({outputs:[{dims:k,dataType:$}],dispatchGroup:{x:B},programUniforms:Y}),getShaderSource:xe}},Iv=(s,u)=>{Ev(s.inputs,u),u.blockSize===32&&s.adapterInfo.isVendor("intel")&&s.adapterInfo.isArchitecture("gen-12lp")?s.compute(Av(s.inputs,u)):s.compute(Cv(s.inputs,u))},Rv=s=>
|
|
2226
|
+
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${u.blockSize};${x};${O};${F};${P}`,inputDependencies:Array(s.length).fill("rank")},getRunData:()=>({outputs:[{dims:k,dataType:$}],dispatchGroup:{x:B},programUniforms:Y}),getShaderSource:xe}},Iv=(s,u)=>{Ev(s.inputs,u),u.blockSize===32&&s.adapterInfo.isVendor("intel")&&s.adapterInfo.isArchitecture("gen-12lp")?s.compute(Av(s.inputs,u)):s.compute(Cv(s.inputs,u))},Rv=s=>Ct(s)}),$v,xv,Ov,kv,Dv,Nv,Mv,Uv,Pv,jI=d(()=>{rt(),ct(),at(),$v=s=>{if(!s||s.length<1)throw new Error("Too few inputs");if(s[0].dataType!==1&&s[0].dataType!==10)throw new Error("Input type must be float or float16.");if(s.length>=2){let u=s[0].dims.length*2===s[1].dims[0];if(s.length===4&&(u=s[3].dims[0]*2===s[1].dims[0]),!u)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},xv=(s,u,p)=>{let m="";for(let g=u-1;g>=0;--g)m+=`
|
|
2227
2227
|
k = i32(${s.indicesGet("indices",g)}) - ${Ke("uniforms.pads",g,p)};
|
|
2228
2228
|
if (k < 0) {
|
|
2229
2229
|
break;
|
|
@@ -2425,7 +2425,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2425
2425
|
let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Y.getByIndices("scale_indices")};`:`let zero_point_value = ${E?g?"i32":"u32":V.type.value}(0);`};
|
|
2426
2426
|
// Compute and write output
|
|
2427
2427
|
${te.setByOffset("global_idx",`${te.type.value}(x_value - zero_point_value) * scale_value`)};
|
|
2428
|
-
}`};return{name:"DequantizeLinear",shaderCache:{hint:u.cacheKey,inputDependencies:Y?["rank","rank","rank"]:["rank","rank"]},getShaderSource:je,getRunData:()=>({outputs:[{dims:T,dataType:b}],dispatchGroup:{x:Math.ceil(w/L/64),y:1,z:1},programUniforms:xe})}},Xv=(s,u)=>{Kv(s.inputs,u),s.compute(Yv(s.inputs,u))},Jv=s=>
|
|
2428
|
+
}`};return{name:"DequantizeLinear",shaderCache:{hint:u.cacheKey,inputDependencies:Y?["rank","rank","rank"]:["rank","rank"]},getShaderSource:je,getRunData:()=>({outputs:[{dims:T,dataType:b}],dispatchGroup:{x:Math.ceil(w/L/64),y:1,z:1},programUniforms:xe})}},Xv=(s,u)=>{Kv(s.inputs,u),s.compute(Yv(s.inputs,u))},Jv=s=>Ct({axis:s.axis,blockSize:s.blockSize})}),Qv,Zv,eT,KI=d(()=>{_n(),rt(),at(),Qv=(s,u,p)=>{let m=s===u,g=s<u&&p<0,T=s>u&&p>0;if(m||g||T)throw new Error("Range these inputs' contents are invalid.")},Zv=(s,u,p,m)=>{let g=Math.abs(Math.ceil((u-s)/p)),T=[g],b=g,w=[{type:12,data:b},{type:m,data:s},{type:m,data:p},...Qe(T)],E=C=>{let $=Ge("output",m,T.length),x=$.type.value,O=[{name:"outputSize",type:"u32"},{name:"start",type:x},{name:"delta",type:x}];return`
|
|
2429
2429
|
${C.registerUniforms(O).declareVariables($)}
|
|
2430
2430
|
${C.mainStart()}
|
|
2431
2431
|
${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
@@ -2476,7 +2476,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2476
2476
|
${tT(u.reduction,"output[data_offset + i]","value",D.type.value)}
|
|
2477
2477
|
}
|
|
2478
2478
|
|
|
2479
|
-
}`};return{name:"ScatterND",shaderCache:{hint:`${u.cacheKey}_${u.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:g,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:C}),getShaderSource:$}},rT=s=>
|
|
2479
|
+
}`};return{name:"ScatterND",shaderCache:{hint:`${u.cacheKey}_${u.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:g,dataType:s[0].dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:C}),getShaderSource:$}},rT=s=>Ct({reduction:s.reduction}),sT=(s,u)=>{s.compute(nT(s.inputs,u),{inputs:[s.inputs[1],s.inputs[2]],outputs:[]})}}),iT,aT,oT,Rh,lT,uT,cT,dT,hT,pT,_T,fT,$h,mT,gT,yT,vT,TT,bT,wT,XI=d(()=>{rt(),ct(),Ft(),at(),iT=(s,u)=>{if(s.every(p=>p>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),s.length>0){if(u.mode==="linear"){if(!(s.length===2||s.length===3||s.length===4&&s[0]===1&&s[1]===1||s.length===4&&s[0]===1&&s[3]===1||s.length===5&&s[0]===1&&s[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
|
|
2480
2480
|
one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(u.mode==="cubic"&&!(s.length===2||s.length===4&&s[0]===1&&s[1]===1||s.length===4&&s[0]===1&&s[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},aT=(s,u,p)=>{u.every(g=>g>=0&&g<p||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let m=new Array(p).fill(1);return u.forEach((g,T)=>m[g]=s[T]),m},oT=(s,u,p,m,g,T)=>{let[b,w,E]=p>10?[1,2,3]:[-1,s.length>1?1:-1,-1],C=s[0].dims.length;if(b>0&&s.length>b&&s[b].dims.length>0)s[b].getFloat32Array().forEach($=>T.push($));else if(u.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(w>0&&s.length>w&&s[w].dims.length===1&&s[w].dims[0]>0){if(s[w].getFloat32Array().forEach($=>m.push($)),m.length!==0&&m.length!==C&&p>=18&&m.length!==u.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");iT(m,u),u.axes.length>0&&aT(m,u.axes,C).forEach(($,x)=>m[x]=$)}if(E>0&&s.length>E&&s[E].dims.length===1&&s[E].dims[0]>0&&(s[E].getBigInt64Array().forEach($=>g.push(Number($))),g.length!==0&&g.length!==C&&p>=18&&g.length!==u.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(u.axes.length>0){if(m.length!==0&&m.length!==u.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(g.length!==0&&g.length!==u.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof m<"u"&&typeof g<"u"&&m.length>0&&g.length>C)throw new Error("Resize requires only of scales or sizes to be specified")},Rh=(s,u,p,m)=>`
|
|
2481
2481
|
// The whole part and the fractional part are calculated separately due to inaccuracy of floating
|
|
2482
2482
|
// point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
|
|
@@ -2746,7 +2746,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2746
2746
|
output[global_idx] = ${u.extrapolationValue};
|
|
2747
2747
|
}`;case"linear":return`output[global_idx] = ${b.length===2||b.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${u.mode}`)}})()};
|
|
2748
2748
|
`}
|
|
2749
|
-
}`;return{name:"Resize",shaderCache:{hint:`${u.cacheKey}|${p}|${C.length>0?u.mode==="cubic"?C:C.length:""}|${g.length>0?g:""}|${w.length>0?w:""}|${k}|${u.mode==="nearest"?b.length:b}`,inputDependencies:["rank"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:E,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},{type:1,data:C},{type:1,data:w},...Qe(b,E)]})}},TT=s=>{let u=s.customDataBuffer;return new Uint32Array(u,u.byteOffset,1)[0]},bT=(s,u)=>{let p=[],m=[],g=[],T=TT(s);if(u.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");oT(s.inputs,u,T,p,m,g),s.compute(vT(s.inputs[0],u,T,p,m,g),{inputs:[0]})},wT=s=>{let u=s.antialias,p=s.axes,m=s.coordinateTransformMode,g=s.cubicCoeffA,T=s.excludeOutside!==0,b=s.extrapolationValue,w=s.keepAspectRatioPolicy,E=s.mode,C=s.nearestMode===""?"simple":s.nearestMode;return
|
|
2749
|
+
}`;return{name:"Resize",shaderCache:{hint:`${u.cacheKey}|${p}|${C.length>0?u.mode==="cubic"?C:C.length:""}|${g.length>0?g:""}|${w.length>0?w:""}|${k}|${u.mode==="nearest"?b.length:b}`,inputDependencies:["rank"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:E,dataType:s.dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},{type:1,data:C},{type:1,data:w},...Qe(b,E)]})}},TT=s=>{let u=s.customDataBuffer;return new Uint32Array(u,u.byteOffset,1)[0]},bT=(s,u)=>{let p=[],m=[],g=[],T=TT(s);if(u.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");oT(s.inputs,u,T,p,m,g),s.compute(vT(s.inputs[0],u,T,p,m,g),{inputs:[0]})},wT=s=>{let u=s.antialias,p=s.axes,m=s.coordinateTransformMode,g=s.cubicCoeffA,T=s.excludeOutside!==0,b=s.extrapolationValue,w=s.keepAspectRatioPolicy,E=s.mode,C=s.nearestMode===""?"simple":s.nearestMode;return Ct({antialias:u,axes:p,coordinateTransformMode:m,cubicCoeffA:g,excludeOutside:T,extrapolationValue:b,keepAspectRatioPolicy:w,mode:E,nearestMode:C})}}),ST,ET,CT,JI=d(()=>{rt(),ct(),at(),ST=s=>{if(!s||s.length<3)throw new Error("layerNorm requires at least 3 inputs.");let u=s[0],p=s[1],m=s[2];if(u.dataType!==p.dataType||u.dataType!==m.dataType)throw new Error("All inputs must have the same data type");if(u.dims.length!==3&&u.dims.length!==2)throw new Error("Input must be 2D or 3D");if(p.dims.length!==3&&p.dims.length!==2)throw new Error("Skip must be 2D or 3D");let g=u.dims[u.dims.length-1],T=u.dims[u.dims.length-2];if(p.dims[p.dims.length-1]!==g)throw new Error("Skip must have the same hidden size as input");if(p.dims[p.dims.length-2]!==T)throw new Error("Skip must have the same sequence length as input");if(m.dims.length!==1)throw new Error("Gamma must be 1D");if(m.dims[m.dims.length-1]!==g)throw new Error("Gamma must have the same hidden size as input");if(s.length>3){let b=s[3];if(b.dims.length!==1)throw new Error("Beta must be 1D");if(b.dims[b.dims.length-1]!==g)throw new Error("Beta must have the same hidden size as input")}if(s.length>4){let b=s[4];if(b.dims.length!==1)throw new Error("Bias must be 1D");if(b.dims[b.dims.length-1]!==g)throw new Error("Bias must have the same hidden size as input")}},ET=(s,u,p,m)=>{let g=u.simplified,T=s[0].dims,b=ne.size(T),w=T,E=b,C=T.slice(-1)[0],$=m?T.slice(0,-1).concat(1):[],x=!g&&s.length>3,O=s.length>4,k=m&&p>1,D=m&&p>2,P=p>3,F=64,L=Ut(C),U=[{type:12,data:E},{type:12,data:L},{type:12,data:C},{type:1,data:u.epsilon}],V=Y=>{let te=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Z=[le("x",s[0].dataType,s[0].dims,L),le("skip",s[1].dataType,s[1].dims,L),le("gamma",s[2].dataType,s[2].dims,L)];x&&Z.push(le("beta",s[3].dataType,s[3].dims,L)),O&&Z.push(le("bias",s[4].dataType,s[4].dims,L)),Z.push(Ge("output",s[0].dataType,w,L)),k&&Z.push(Ge("mean_output",1,$)),D&&Z.push(Ge("inv_std_output",1,$)),P&&Z.push(Ge("input_skip_bias_sum",s[0].dataType,w,L));let pe=Nt(s[0].dataType),xe=Nt(1,L);return`
|
|
2750
2750
|
|
|
2751
2751
|
${Y.registerUniforms(te).declareVariables(...Z)}
|
|
2752
2752
|
var<workgroup> sum_shared : array<${xe}, ${F}>;
|
|
@@ -2798,7 +2798,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2798
2798
|
${pe}(inv_std_dev) * gamma[offset1d + i]
|
|
2799
2799
|
${x?"+ beta[offset1d + i]":""};
|
|
2800
2800
|
}
|
|
2801
|
-
}`},B=[{dims:w,dataType:s[0].dataType}];return p>1&&B.push({dims:$,dataType:1}),p>2&&B.push({dims:$,dataType:1}),p>3&&B.push({dims:T,dataType:s[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${L};${k};${D};${P}`,inputDependencies:s.map((Y,te)=>"type")},getShaderSource:V,getRunData:()=>({outputs:B,dispatchGroup:{x:Math.ceil(E/C)},programUniforms:U})}},CT=(s,u)=>{ST(s.inputs);let p=[0];s.outputCount>1&&p.push(-3),s.outputCount>2&&p.push(-3),s.outputCount>3&&p.push(3),s.compute(ET(s.inputs,u,s.outputCount,!1),{outputs:p})}}),AT,kl,IT,xh,RT,$T,xT,OT,QI=d(()=>{rt(),ct(),Ft(),at(),AT=(s,u)=>{if(!s||s.length<1)throw new Error("too few inputs");if(u.axes.length!==0){if(u.axes.length!==u.starts.length||u.axes.length!==u.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(u.starts.length!==u.ends.length)throw new Error("starts and ends must have the same length");s.slice(1).forEach((p,m)=>{if(s[m+1].dataType!==6&&s[m+1].dataType!==7)throw new Error(`Input ${m} must be an array of int32 or int64`)})},kl=(s,u)=>{let p=[];if(s.length>u)if(s[u].dataType===7)s[u].getBigInt64Array().forEach(m=>p.push(Number(m)));else if(s[u].dataType===6)s[u].getInt32Array().forEach(m=>p.push(Number(m)));else throw new Error(`Input ${u} must be an array of int32 or int64`);return p},IT=(s,u)=>{if(s.length>1){let p=kl(s,1),m=kl(s,2),g=kl(s,3);return g.length===0&&(g=[...Array(s[0].dims.length).keys()]),
|
|
2801
|
+
}`},B=[{dims:w,dataType:s[0].dataType}];return p>1&&B.push({dims:$,dataType:1}),p>2&&B.push({dims:$,dataType:1}),p>3&&B.push({dims:T,dataType:s[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${L};${k};${D};${P}`,inputDependencies:s.map((Y,te)=>"type")},getShaderSource:V,getRunData:()=>({outputs:B,dispatchGroup:{x:Math.ceil(E/C)},programUniforms:U})}},CT=(s,u)=>{ST(s.inputs);let p=[0];s.outputCount>1&&p.push(-3),s.outputCount>2&&p.push(-3),s.outputCount>3&&p.push(3),s.compute(ET(s.inputs,u,s.outputCount,!1),{outputs:p})}}),AT,kl,IT,xh,RT,$T,xT,OT,QI=d(()=>{rt(),ct(),Ft(),at(),AT=(s,u)=>{if(!s||s.length<1)throw new Error("too few inputs");if(u.axes.length!==0){if(u.axes.length!==u.starts.length||u.axes.length!==u.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(u.starts.length!==u.ends.length)throw new Error("starts and ends must have the same length");s.slice(1).forEach((p,m)=>{if(s[m+1].dataType!==6&&s[m+1].dataType!==7)throw new Error(`Input ${m} must be an array of int32 or int64`)})},kl=(s,u)=>{let p=[];if(s.length>u)if(s[u].dataType===7)s[u].getBigInt64Array().forEach(m=>p.push(Number(m)));else if(s[u].dataType===6)s[u].getInt32Array().forEach(m=>p.push(Number(m)));else throw new Error(`Input ${u} must be an array of int32 or int64`);return p},IT=(s,u)=>{if(s.length>1){let p=kl(s,1),m=kl(s,2),g=kl(s,3);return g.length===0&&(g=[...Array(s[0].dims.length).keys()]),Ct({starts:p,ends:m,axes:g})}else return u},xh=(s,u,p,m,g)=>{let T=s;return s<0&&(T+=p[m[u]]),g[u]<0?Math.max(0,Math.min(T,p[m[u]]-1)):Math.max(0,Math.min(T,p[m[u]]))},RT=(s,u,p)=>`fn calculateInputIndices(output_indices: ${u.type.indices}) -> ${s.type.indices} {
|
|
2802
2802
|
var input_indices: ${s.type.indices};
|
|
2803
2803
|
var carry = 0u;
|
|
2804
2804
|
for (var i = ${p.length-1}; i >= 0; i--) {
|
|
@@ -2824,7 +2824,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2824
2824
|
let output_indices = ${x.offsetToIndices("global_idx")};
|
|
2825
2825
|
let input_indices = calculateInputIndices(output_indices);
|
|
2826
2826
|
${x.setByOffset("global_idx",O.getByIndices("input_indices"))}
|
|
2827
|
-
}`;return{name:"Slice",shaderCache:{hint:`${E.length}_${b.length}_${T.length}`,inputDependencies:["rank"]},getShaderSource:F,getRunData:()=>({outputs:[$],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:P})}},xT=(s,u)=>{AT(s.inputs,u);let p=IT(s.inputs,u);s.compute($T(s.inputs,p),{inputs:[0]})},OT=s=>{let u=s.starts,p=s.ends,m=s.axes;return
|
|
2827
|
+
}`;return{name:"Slice",shaderCache:{hint:`${E.length}_${b.length}_${T.length}`,inputDependencies:["rank"]},getShaderSource:F,getRunData:()=>({outputs:[$],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:P})}},xT=(s,u)=>{AT(s.inputs,u);let p=IT(s.inputs,u);s.compute($T(s.inputs,p),{inputs:[0]})},OT=s=>{let u=s.starts,p=s.ends,m=s.axes;return Ct({starts:u,ends:p,axes:m})}}),kT,DT,NT,MT,ZI=d(()=>{rt(),ct(),Ft(),pr(),at(),kT=s=>{if(!s||s.length!==1)throw new Error("Softmax op requires 1 input.")},DT=(s,u)=>{let p=s.inputs[0],m=p.dims,g=ne.size(m),T=m.length,b=ne.normalizeAxis(u.axis,T),w=b<m.length-1,E,C=[];w?(C=Array.from({length:T},(Z,pe)=>pe),C[b]=T-1,C[T-1]=b,E=s.compute(Ln(p,C),{inputs:[p],outputs:[-1]})[0]):E=p;let $=E.dims,x=$[T-1],O=g/x,k=Ut(x),D=x/k,P=64;O===1&&(P=256);let F=(Z,pe)=>pe===4?`max(max(${Z}.x, ${Z}.y), max(${Z}.z, ${Z}.w))`:pe===2?`max(${Z}.x, ${Z}.y)`:pe===3?`max(max(${Z}.x, ${Z}.y), ${Z}.z)`:Z,L=le("x",E.dataType,E.dims,k),U=Ge("result",E.dataType,E.dims,k),V=L.type.value,B=Nt(E.dataType)==="f32"?`var threadMax = ${V}(-3.402823e+38f);`:`var threadMax = ${V}(-65504.0h);`,Y=Z=>`
|
|
2828
2828
|
var<workgroup> rowMaxShared : ${V};
|
|
2829
2829
|
var<workgroup> rowSumShared : ${V};
|
|
2830
2830
|
var<workgroup> threadShared : array<${V}, ${P}>;
|
|
@@ -2898,7 +2898,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2898
2898
|
value = max(value, ${V}(0.0));
|
|
2899
2899
|
setValue(row, col, row_stride, value);
|
|
2900
2900
|
}
|
|
2901
|
-
}`,te=s.compute({name:"Softmax",shaderCache:{hint:`${k};${P}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:$,dataType:E.dataType}],dispatchGroup:{x:O},programUniforms:[{type:6,data:D}]}),getShaderSource:Y},{inputs:[E],outputs:[w?-1:0]})[0];w&&s.compute(Ln(te,C),{inputs:[te]})},NT=(s,u)=>{kT(s.inputs),DT(s,u)},MT=s=>
|
|
2901
|
+
}`,te=s.compute({name:"Softmax",shaderCache:{hint:`${k};${P}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:$,dataType:E.dataType}],dispatchGroup:{x:O},programUniforms:[{type:6,data:D}]}),getShaderSource:Y},{inputs:[E],outputs:[w?-1:0]})[0];w&&s.compute(Ln(te,C),{inputs:[te]})},NT=(s,u)=>{kT(s.inputs),DT(s,u)},MT=s=>Ct({axis:s.axis})}),Oh,UT,PT,LT,qT,eR=d(()=>{rt(),ct(),at(),Oh=s=>Array.from(s.getBigInt64Array(),Number),UT=s=>{if(!s||s.length!==2)throw new Error("Tile requires 2 inputs.");if(s[0].dataType!==1&&s[0].dataType!==10&&s[0].dataType!==6&&s[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(s[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(s[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Oh(s[1]).length!==s[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},PT=(s,u)=>{let p=[];for(let m=0;m<s.length;++m)p.push(s[m]*u[m]);return p},LT=(s,u)=>{let p=s[0].dims,m=u??Oh(s[1]),g=PT(p,m),T=ne.size(g),b=s[0].dataType,w=le("input",b,p.length),E=Ge("output",b,g.length),C=$=>`
|
|
2902
2902
|
const inputShape = ${w.indices(...p)};
|
|
2903
2903
|
${$.registerUniform("output_size","u32").declareVariables(w,E)}
|
|
2904
2904
|
${$.mainStart()}
|
|
@@ -2943,7 +2943,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2943
2943
|
}`},zT=s=>{let u=s[1].dims,p=s[2].dims,m=s[0].dims,g=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,g),getRunData:()=>({outputs:[{dims:b,dataType:g}],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,g){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}});g&&w.push({binding:w.length,resource:g});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 g=_o(u,this.backend.device.limits),T=s.getShaderSource(g),b=`${m.join(`
|
|
2944
2944
|
`)}
|
|
2945
2945
|
${g.additionalImplementations}
|
|
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:g.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,g=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(u<=g&&p<=g&&m<=g)return[u,p,m];let T=u*p*m,b=Math.ceil(Math.sqrt(T));if(b>g){if(b=Math.ceil(Math.cbrt(T)),b>g)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 g=s[m].dataType;switch(u[m]){case"none":{p.push("");break}case"type":{p.push(`${g}`);break}case"rank":{let T=s[m].dims.length;p.push(`${g};${T}`);break}case"dims":{let T=s[m].dims.join(",");p.push(`${g};${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},g=T=>u.features.has(T)&&p.push(T)&&!0;g("chromium-experimental-timestamp-query-inside-passes")||g("timestamp-query"),g("shader-f16"),g("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 g=p[m],T=g.kernelId,b=this.kernels.get(T),w=b.kernelType,E=b.kernelName,C=g.programName,$=g.inputTensorViews,x=g.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,g,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?g(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 g=BT.get(s);if(!g)throw new Error(`kernel not implemented: ${s}`);let T={kernelType:s,kernelName:m,kernelEntry:g[0],attributes:[g[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 g=m.kernelType,T=m.kernelName,b=m.kernelEntry,w=m.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${g}] ${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 "[${g}] ${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 "[${g}] ${T}" failed. ${C}`)),1}finally{E&&p.push(this.device.popErrorScope().then(C=>C?`GPU validation error for kernel "[${g}] ${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 g=this.sessionExternalDataMapping.get(s);g||(g=new Map,this.sessionExternalDataMapping.set(s,g));let T=g.get(u),b=this.gpuDataManager.registerExternalBuffer(p,m,T);return g.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 g=this.getComputePassEncoder(),T=s[m];this.writeTimestamp(this.pendingDispatchNumber*2),g.setPipeline(T.computePipeline),g.setBindGroup(0,T.bindGroup),g.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,g){this.module=u,this.dataType=p,this.data=m,this.dims=g}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,g=p/s.PTR_SIZE,T=m===4?"i32":"i64";this.opKernelContext=Number(s.getValue(m*g++,T));let b=Number(s.getValue(m*g++,T));this.outputCount=Number(s.getValue(m*g++,T)),this.customDataOffset=Number(s.getValue(m*g++,"*")),this.customDataSize=Number(s.getValue(m*g++,T));let w=[];for(let E=0;E<b;E++){let C=Number(s.getValue(m*g++,T)),$=Number(s.getValue(m*g++,"*")),x=Number(s.getValue(m*g++,T)),O=[];for(let k=0;k<x;k++)O.push(Number(s.getValue(m*g++,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??[],g=(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,g,T,this.outputCount)}output(s,u){let p=this.module.stackSave();try{let m=this.module.PTR_SIZE,g=m===4?"i32":"i64",T=this.module.stackAlloc((1+u.length)*m);this.module.setValue(T,u.length,g);for(let b=0;b<u.length;b++)this.module.setValue(T+m*(b+1),u[b],g);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 g=u.jsepInit;if(!g)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),g("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);g("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&&St("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 g=s.webgpu.forceFallbackAdapter;if(g!==void 0&&typeof g!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${g}"`);if(p=await navigator.gpu.requestAdapter({powerPreference:m,forceFallbackAdapter:g}),!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,g=u.stackAlloc(2*m);u._OrtGetInputOutputCount(s,g,g+m)!==0&&St("Can't get session input/output count.");let T=m===4?"i32":"i64";return[Number(u.getValue(g,T)),Number(u.getValue(g+m,T))]}finally{u.stackRestore(p)}},Nh=(s,u)=>{let p=$t(),m=p.stackSave(),g=0;try{let T=p.PTR_SIZE,b=p.stackAlloc(2*T);p._OrtGetInputOutputMetadata(s,u,b,b+T)!==0&&St("Can't get session input/output metadata.");let w=Number(p.getValue(b,"*"));g=Number(p.getValue(b+T,"*"));let E=p.HEAP32[g/4];if(E===0)return[w,0];let C=p.HEAPU32[g/4+1],$=[];for(let x=0;x<C;x++){let O=Number(p.getValue(g+8+x*T,"*"));$.push(O!==0?p.UTF8ToString(O):Number(p.getValue(g+8+(x+C)*T,"*")))}return[w,E,$]}finally{p.stackRestore(m),g!==0&&p._OrtFree(g)}},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,g=$t();Array.isArray(s)?[p,m]=s:s.buffer===g.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&&g.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=>{g.mountExternalData(te,Z)}))}await Promise.all(B)}for(let B of u?.executionProviders??[])if((typeof B=="string"?B:B.name)==="webnn"){if(g.shouldTransferToMLTensor=!1,typeof B!="string"){let Y=B,te=Y?.context,Z=Y?.gpuDevice,pe=Y?.deviceType,xe=Y?.powerPreference;te?g.currentContext=te:Z?g.currentContext=await g.webnnCreateMLContext(Z):g.currentContext=await g.webnnCreateMLContext({deviceType:pe,powerPreference:xe})}else g.currentContext=await g.webnnCreateMLContext();break}T=await g._OrtCreateSession(p,m,b),g.webgpuOnCreateSession?.(T),T===0&&St("Can't create a session."),g.jsepOnCreateSession?.(),g.currentContext&&(g.webnnRegisterMLContext(T,g.currentContext),g.currentContext=void 0,g.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&&St("Can't get an input name."),C.push(Y);let pe=g.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&&St("Can't get an output name."),$.push(Y);let pe=g.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=g.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=g._OrtCreateBinding(T),w===0&&St("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=>g._OrtFree(O)),$.forEach(O=>g._OrtFree(O)),w!==0&&g._OrtReleaseBinding(w)!==0&&St("Can't release IO binding."),T!==0&&g._OrtReleaseSession(T)!==0&&St("Can't release session."),x}finally{g._free(p),b!==0&&g._OrtReleaseSessionOptions(b)!==0&&St("Can't release session options."),E.forEach(x=>g._free(x)),g.unmountExternalData?.()}},Uh=s=>{let u=$t(),p=ca.get(s);if(!p)throw new Error(`cannot release session. invalid session id: ${s}`);let[m,g,T,b,w]=p;b&&(w&&u._OrtClearBoundOutputs(b.handle)!==0&&St("Can't clear bound outputs."),u._OrtReleaseBinding(b.handle)!==0&&St("Can't release IO binding.")),u.jsepOnReleaseSession?.(s),u.webnnOnReleaseSession?.(s),u.webgpuOnReleaseSession?.(s),g.forEach(E=>u._OrtFree(E)),T.forEach(E=>u._OrtFree(E)),u._OrtReleaseSession(m)!==0&&St("Can't release session."),ca.delete(s)},Ph=async(s,u,p,m,g,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(g);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&&St(`Can't create tensor for input/output. session=${m}, index=${T}.`),u.push(L)}finally{w.stackRestore(P)}},Lh=async(s,u,p,m,g,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(g[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&&St(`Can't bind input[${et}] for session=${s}.`)}for(let et=0;et<F;et++){let Ot=m[et];g[et]?.[3]?b._OrtBindOutput(Ye,x[Ot],B[et],0)!==0&&St(`Can't bind pre-allocated output[${et}] for session=${s}.`):b._OrtBindOutput(Ye,x[Ot],0,ot[Ot])!==0&&St(`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&&St("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(g[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&&St(`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&&St("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&&St("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&&St("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],g=u._OrtEndProfiling(m);g===0&&St("Can't get an profile file name."),u._OrtFree(g)},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 g={type:"init-wasm",in:Q};if(!g.in.wasm.wasmPaths&&p){let T=Vs();T&&(g.in.wasm.wasmPaths=T)}Lr.postMessage(g),ac=p}catch(g){u(g)}},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 g={type:"create",in:{model:s,options:{...u}}},T=[];s instanceof Uint8Array&&T.push(s.buffer),Lr.postMessage(g,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,g,T)=>{if(da()){if(p.some(b=>b[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(g.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,g,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:g}=s[2];return Xe.fromGpuBuffer(p,{dataType:u,dims:s[1],download:m,dispose:g})}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:g}=s[2];return Xe.fromMLTensor(p,{dataType:u,dims:s[1],download:m,dispose:g})}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=[],g=[];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),g.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[g[O]]}"`)),E=T.map((x,O)=>x?Fh(x,()=>`output "${this.outputNames[b[O]]}"`):null),C=await lb(this.sessionId,g,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"?y("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)})();/**
|
|
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:g.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,g=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(u<=g&&p<=g&&m<=g)return[u,p,m];let T=u*p*m,b=Math.ceil(Math.sqrt(T));if(b>g){if(b=Math.ceil(Math.cbrt(T)),b>g)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 g=s[m].dataType;switch(u[m]){case"none":{p.push("");break}case"type":{p.push(`${g}`);break}case"rank":{let T=s[m].dims.length;p.push(`${g};${T}`);break}case"dims":{let T=s[m].dims.join(",");p.push(`${g};${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},g=T=>u.features.has(T)&&p.push(T)&&!0;g("chromium-experimental-timestamp-query-inside-passes")||g("timestamp-query"),g("shader-f16"),g("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 g=p[m],T=g.kernelId,b=this.kernels.get(T),w=b.kernelType,E=b.kernelName,C=g.programName,$=g.inputTensorViews,x=g.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,g,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?g(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 g=BT.get(s);if(!g)throw new Error(`kernel not implemented: ${s}`);let T={kernelType:s,kernelName:m,kernelEntry:g[0],attributes:[g[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 g=m.kernelType,T=m.kernelName,b=m.kernelEntry,w=m.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${g}] ${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 "[${g}] ${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 "[${g}] ${T}" failed. ${C}`)),1}finally{E&&p.push(this.device.popErrorScope().then(C=>C?`GPU validation error for kernel "[${g}] ${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 g=this.sessionExternalDataMapping.get(s);g||(g=new Map,this.sessionExternalDataMapping.set(s,g));let T=g.get(u),b=this.gpuDataManager.registerExternalBuffer(p,m,T);return g.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 g=this.getComputePassEncoder(),T=s[m];this.writeTimestamp(this.pendingDispatchNumber*2),g.setPipeline(T.computePipeline),g.setBindGroup(0,T.bindGroup),g.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,g){this.module=u,this.dataType=p,this.data=m,this.dims=g}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,g=p/s.PTR_SIZE,T=m===4?"i32":"i64";this.opKernelContext=Number(s.getValue(m*g++,T));let b=Number(s.getValue(m*g++,T));this.outputCount=Number(s.getValue(m*g++,T)),this.customDataOffset=Number(s.getValue(m*g++,"*")),this.customDataSize=Number(s.getValue(m*g++,T));let w=[];for(let E=0;E<b;E++){let C=Number(s.getValue(m*g++,T)),$=Number(s.getValue(m*g++,"*")),x=Number(s.getValue(m*g++,T)),O=[];for(let k=0;k<x;k++)O.push(Number(s.getValue(m*g++,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??[],g=(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,g,T,this.outputCount)}output(s,u){let p=this.module.stackSave();try{let m=this.module.PTR_SIZE,g=m===4?"i32":"i64",T=this.module.stackAlloc((1+u.length)*m);this.module.setValue(T,u.length,g);for(let b=0;b<u.length;b++)this.module.setValue(T+m*(b+1),u[b],g);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 g=u.jsepInit;if(!g)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),g("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);g("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 g=s.webgpu.forceFallbackAdapter;if(g!==void 0&&typeof g!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${g}"`);if(p=await navigator.gpu.requestAdapter({powerPreference:m,forceFallbackAdapter:g}),!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,g=u.stackAlloc(2*m);u._OrtGetInputOutputCount(s,g,g+m)!==0&&Et("Can't get session input/output count.");let T=m===4?"i32":"i64";return[Number(u.getValue(g,T)),Number(u.getValue(g+m,T))]}finally{u.stackRestore(p)}},Nh=(s,u)=>{let p=$t(),m=p.stackSave(),g=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,"*"));g=Number(p.getValue(b+T,"*"));let E=p.HEAP32[g/4];if(E===0)return[w,0];let C=p.HEAPU32[g/4+1],$=[];for(let x=0;x<C;x++){let O=Number(p.getValue(g+8+x*T,"*"));$.push(O!==0?p.UTF8ToString(O):Number(p.getValue(g+8+(x+C)*T,"*")))}return[w,E,$]}finally{p.stackRestore(m),g!==0&&p._OrtFree(g)}},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,g=$t();Array.isArray(s)?[p,m]=s:s.buffer===g.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&&g.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=>{g.mountExternalData(te,Z)}))}await Promise.all(B)}for(let B of u?.executionProviders??[])if((typeof B=="string"?B:B.name)==="webnn"){if(g.shouldTransferToMLTensor=!1,typeof B!="string"){let Y=B,te=Y?.context,Z=Y?.gpuDevice,pe=Y?.deviceType,xe=Y?.powerPreference;te?g.currentContext=te:Z?g.currentContext=await g.webnnCreateMLContext(Z):g.currentContext=await g.webnnCreateMLContext({deviceType:pe,powerPreference:xe})}else g.currentContext=await g.webnnCreateMLContext();break}T=await g._OrtCreateSession(p,m,b),g.webgpuOnCreateSession?.(T),T===0&&Et("Can't create a session."),g.jsepOnCreateSession?.(),g.currentContext&&(g.webnnRegisterMLContext(T,g.currentContext),g.currentContext=void 0,g.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=g.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=g.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=g.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=g._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=>g._OrtFree(O)),$.forEach(O=>g._OrtFree(O)),w!==0&&g._OrtReleaseBinding(w)!==0&&Et("Can't release IO binding."),T!==0&&g._OrtReleaseSession(T)!==0&&Et("Can't release session."),x}finally{g._free(p),b!==0&&g._OrtReleaseSessionOptions(b)!==0&&Et("Can't release session options."),E.forEach(x=>g._free(x)),g.unmountExternalData?.()}},Uh=s=>{let u=$t(),p=ca.get(s);if(!p)throw new Error(`cannot release session. invalid session id: ${s}`);let[m,g,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),g.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,g,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(g);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,g,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(g[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];g[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(g[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],g=u._OrtEndProfiling(m);g===0&&Et("Can't get an profile file name."),u._OrtFree(g)},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 g={type:"init-wasm",in:Q};if(!g.in.wasm.wasmPaths&&p){let T=Vs();T&&(g.in.wasm.wasmPaths=T)}Lr.postMessage(g),ac=p}catch(g){u(g)}},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 g={type:"create",in:{model:s,options:{...u}}},T=[];s instanceof Uint8Array&&T.push(s.buffer),Lr.postMessage(g,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,g,T)=>{if(da()){if(p.some(b=>b[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(g.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,g,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:g}=s[2];return Xe.fromGpuBuffer(p,{dataType:u,dims:s[1],download:m,dispose:g})}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:g}=s[2];return Xe.fromMLTensor(p,{dataType:u,dims:s[1],download:m,dispose:g})}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=[],g=[];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),g.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[g[O]]}"`)),E=T.map((x,O)=>x?Fh(x,()=>`output "${this.outputNames[b[O]]}"`):null),C=await lb(this.sessionId,g,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"?y("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)})();/**
|
|
2947
2947
|
* @license
|
|
2948
2948
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
2949
2949
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
@@ -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 _=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]),y=new o.Tensor("float32",e,[2,1,64]);return jf.log.debug("vad is initialized"),new Vf(o,a,_,y,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 y={input:new this.ortInstance.Tensor("float32",e,[1,e.length]),state:this._state,sr:this._sr},d=await this._session.run(y);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,_,y,d){d===void 0&&(d=y);var A=Object.getOwnPropertyDescriptor(_,y);(!A||("get"in A?!_.__esModule:A.writable||A.configurable))&&(A={enumerable:!0,get:function(){return _[y]}}),Object.defineProperty(e,d,A)}:function(e,_,y,d){d===void 0&&(d=y),e[d]=_[y]}),r=Gn&&Gn.__exportStar||function(e,_){for(var y in e)y!=="default"&&!Object.prototype.hasOwnProperty.call(_,y)&&n(_,e,y)};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,y=us,d=Ea,A=zd,S=wl;o.defaultNonRealTimeVADOptions={...y.defaultFrameProcessorOptions,modelURL:e.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:_.defaultModelFetcher};class R{static async new(H={}){const W={...o.defaultNonRealTimeVADOptions,...H};(0,y.validateOptions)(W),W.ortConfig!==void 0&&W.ortConfig(c);const G=()=>W.modelFetcher(W.modelURL),K=await A.SileroLegacy.new(c,G),ae=new y.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,y=new ArrayBuffer(44+o.length*e),d=new DataView(y);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),y}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",y=>{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 y=0;y<c.numberOfChannels;y++)e[_]+=c.getChannelData(y)[_];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,y=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:()=>{y.log.debug("VAD misfire")},onSpeechStart:()=>{y.log.debug("Detected speech start")},onSpeechEnd:()=>{y.log.debug("Detected speech end")},onSpeechRealStart:()=>{y.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 y=Yf;Object.defineProperty(o,"AudioNodeVAD",{enumerable:!0,get:function(){return y.AudioNodeVAD}}),Object.defineProperty(o,"DEFAULT_MODEL",{enumerable:!0,get:function(){return y.DEFAULT_MODEL}}),Object.defineProperty(o,"MicVAD",{enumerable:!0,get:function(){return y.MicVAD}}),Object.defineProperty(o,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return y.getDefaultRealTimeVADOptions}})}(Hd);const Xf=Tb({__proto__:null,default:eI(Hd)},[Hd]);let At;const Jf=Ct.ref(!1),Qf=Ct.ref(!1),Zf=Ct.ref(!1),em=Ct.ref({}),tm=Ct.ref({}),nm=Ct.ref(!1),rm=Ct.ref(void 0),Xu=Ct.ref({}),Vd=Ct.ref({}),Ju=Ct.ref([]),sm=Ct.ref("default"),im=Ct.ref("default"),am=Ct.ref(!1),om=Ct.ref(!1),lm=Ct.ref(!0),um=Ct.ref(!1),cm=Ct.ref(null),Sl=Ct.ref(void 0),dm=Ct.ref(!1),hm=Ct.ref(2),pm=Ct.ref(1),jd=Ct.ref({}),_m=Ct.ref({}),fm=Ct.ref({}),Gd=Ct.computed(()=>{const o={};return Object.entries(em.value).forEach(([n,r])=>{jd.value[n]?.isTransferred||(o[n]=r)}),o}),hI=Ct.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=Ct.computed(()=>Ju.value.filter(o=>o.kind==="audioinput").map(o=>({deviceId:o.deviceId,kind:o.kind,groupId:o.groupId,label:o.label}))),_I=Ct.computed(()=>Ju.value.filter(o=>o.kind==="audiooutput").map(o=>({deviceId:o.deviceId,kind:o.kind,groupId:o.groupId,label:o.label}))),mm=Ct.computed(()=>Object.values(Gd.value).filter(o=>o.roomId===Sl.value));Ct.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),At=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}),At.on("connection",_=>{nm.value=!1,Jf.value=!0,Qf.value=_,a(At)}).on("reconnecting",_=>{Zf.value=_}).on("changeActiveCalls",_=>{em.value={..._}}).on("changeActiveMessages",_=>{tm.value={..._}}).on("newMSRPMessage",_=>{const y=_.session._id,d=Vd.value[y]||[];d.push(_.message),Vd.value[y]=[...d]}).on("callAddingInProgressChanged",_=>{rm.value=_}).on("changeAvailableDeviceList",_=>{Ju.value=[..._]}).on("changeActiveInputMediaDevice",_=>{im.value=_}).on("changeActiveOutputMediaDevice",_=>{sm.value=_}).on("changeMuteWhenJoin",_=>{am.value=_}).on("changeIsCallWaiting",_=>{lm.value=_}).on("changeIsDND",_=>{om.value=_}).on("changeIsMuted",_=>{um.value=_}).on("changeActiveStream",_=>{cm.value=_}).on("currentActiveRoomChanged",_=>{Sl.value=_}).on("addRoom",({roomList:_})=>{Xu.value={..._}}).on("updateRoom",({roomList:_})=>{Xu.value={..._}}).on("removeRoom",({roomList:_})=>{Xu.value={..._}}).on("changeCallStatus",_=>{jd.value={..._}}).on("changeCallTime",_=>{_m.value={..._}}).on("changeCallMetrics",_=>{fm.value={..._}}).begin(),a(At)}catch(e){console.error(e),c()}})},unregister(){At?.unregister()},register(){At?.register()},disconnect(){At?.disconnect()},initCall(o,n=!1,r=!1){At?.audio.initCall(o,n,r)},answerCall(o){At?.audio.answerCall(o)},terminateCall(o){At?.audio.terminateCall(o)},mute(){At?.audio.mute()},unmute(){At?.audio.unmute()},transferCall(o,n){At?.audio.transferCall(o,n)},mergeCall(o){At?.audio.mergeCall(o)},mergeCallByIds(o,n){At?.audio.mergeCallByIds(o,n)},holdCall(o,n){At?.audio.holdCall(o,n)},unholdCall(o){At?.audio.unholdCall(o)},async moveCall(o,n){await At?.audio.moveCall(o,n)},muteCaller(o){At?.audio.muteCaller(o)},unmuteCaller(o){At?.audio.unmuteCaller(o)},setMuteWhenJoin(o){At?.audio.setMuteWhenJoin(o)},setDND(o){At?.audio.setDND(o)},setCallWaiting(o){At?.audio.setCallWaiting(o)},async setMicrophone(o){await At?.audio.setMicrophone(o)},async setSpeaker(o){await At?.audio.setSpeaker(o)},sendDTMF(o,n){At?.audio.sendDTMF(o,n)},async setActiveRoom(o){await At?.audio.setActiveRoom(o)},setMicrophoneSensitivity(o){hm.value=o,At?.audio.setMicrophoneSensitivity(o)},setSpeakerVolume(o){pm.value=o,At?.audio.setSpeakerVolume(o)},setAutoAnswer(o){dm.value=o,At?.audio.setAutoAnswer(o)},setMetricsConfig(o){At?.audio.setMetricsConfig(o)},msrpAnswer(o){At?.msrp.msrpAnswer(o)},messageTerminate(o){At?.msrp.messageTerminate(o)},sendMSRP(o,n){At?.msrp.sendMSRP(o,n)},initMSRP(o,n,r){At?.msrp.initMSRP(o,n,r)}}},gm=Symbol();function fI(){return Ct.provide(gm,Wd),Wd}function mI(){const o=Ct.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]),y=new o.Tensor("float32",e,[2,1,64]);return jf.log.debug("vad is initialized"),new Vf(o,a,_,y,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 y={input:new this.ortInstance.Tensor("float32",e,[1,e.length]),state:this._state,sr:this._sr},d=await this._session.run(y);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,_,y,d){d===void 0&&(d=y);var A=Object.getOwnPropertyDescriptor(_,y);(!A||("get"in A?!_.__esModule:A.writable||A.configurable))&&(A={enumerable:!0,get:function(){return _[y]}}),Object.defineProperty(e,d,A)}:function(e,_,y,d){d===void 0&&(d=y),e[d]=_[y]}),r=Gn&&Gn.__exportStar||function(e,_){for(var y in e)y!=="default"&&!Object.prototype.hasOwnProperty.call(_,y)&&n(_,e,y)};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,y=us,d=Ea,A=zd,S=wl;o.defaultNonRealTimeVADOptions={...y.defaultFrameProcessorOptions,modelURL:e.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:_.defaultModelFetcher};class R{static async new(H={}){const W={...o.defaultNonRealTimeVADOptions,...H};(0,y.validateOptions)(W),W.ortConfig!==void 0&&W.ortConfig(c);const G=()=>W.modelFetcher(W.modelURL),K=await A.SileroLegacy.new(c,G),ae=new y.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,y=new ArrayBuffer(44+o.length*e),d=new DataView(y);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),y}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",y=>{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 y=0;y<c.numberOfChannels;y++)e[_]+=c.getChannelData(y)[_];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,y=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:()=>{y.log.debug("VAD misfire")},onSpeechStart:()=>{y.log.debug("Detected speech start")},onSpeechEnd:()=>{y.log.debug("Detected speech end")},onSpeechRealStart:()=>{y.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 y=Yf;Object.defineProperty(o,"AudioNodeVAD",{enumerable:!0,get:function(){return y.AudioNodeVAD}}),Object.defineProperty(o,"DEFAULT_MODEL",{enumerable:!0,get:function(){return y.DEFAULT_MODEL}}),Object.defineProperty(o,"MicVAD",{enumerable:!0,get:function(){return y.MicVAD}}),Object.defineProperty(o,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return y.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),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",_=>{nm.value=!1,Jf.value=!0,Qf.value=_,a(St)}).on("reconnecting",_=>{Zf.value=_}).on("changeActiveCalls",_=>{em.value={..._}}).on("changeActiveMessages",_=>{tm.value={..._}}).on("newMSRPMessage",_=>{const y=_.session._id,d=Vd.value[y]||[];d.push(_.message),Vd.value[y]=[...d]}).on("callAddingInProgressChanged",_=>{rm.value=_}).on("changeAvailableDeviceList",_=>{Ju.value=[..._]}).on("changeActiveInputMediaDevice",_=>{im.value=_}).on("changeActiveOutputMediaDevice",_=>{sm.value=_}).on("changeMuteWhenJoin",_=>{am.value=_}).on("changeIsCallWaiting",_=>{lm.value=_}).on("changeIsDND",_=>{om.value=_}).on("changeIsMuted",_=>{um.value=_}).on("changeActiveStream",_=>{cm.value=_}).on("currentActiveRoomChanged",_=>{Sl.value=_}).on("addRoom",({roomList:_})=>{Xu.value={..._}}).on("updateRoom",({roomList:_})=>{Xu.value={..._}}).on("removeRoom",({roomList:_})=>{Xu.value={..._}}).on("changeCallStatus",_=>{jd.value={..._}}).on("changeCallTime",_=>{_m.value={..._}}).on("changeCallMetrics",_=>{fm.value={..._}}).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
|